加密核心程式碼
///
/// 加密字串
///
/// 待加密字串
/// 密鑰大質數 (e 或 d)
/// 大整數 N
/// 加密後位元組陣列
private byte[] EncryptString(string dataStr, BigInteger keyNum, BigInteger nNum)
{
byte[] bytes = Encoding.UTF8.GetBytes(dataStr);
int len = bytes.Length;
int len1 = (len % 120 == 0) ? len / 120 : len / 120 + 1;
List tempbytes = new List();
for (int i = 0; i < len1; i++)
{
int blockLen = (len >= 120) ? 120 : len;
byte[] oText = new byte[blockLen];
Array.Copy(bytes, i * 120, oText, 0, blockLen);
BigInteger biText = new BigInteger(oText);
BigInteger bIEnText = biText.modPow(keyNum, nNum); // c = m^e mod n
// 補位:確保輸出固定 128 位元組 (256 十六進位字元)
string resultStr = bIEnText.ToHexString();
if (resultStr.Length < 256)
{
while (resultStr.Length != 256)
resultStr = "0" + resultStr;
}
byte[] returnBytes = new byte[128];
for (int j = 0; j < returnBytes.Length; j++)
returnBytes[j] = Convert.ToByte(resultStr.Substring(j * 2, 2), 16);
tempbytes.AddRange(returnBytes);
len -= blockLen;
}
return tempbytes.ToArray();
}
關鍵點解析
- 分塊 120 位元組:留餘量給 RSA 運算,避免溢出。
- modPow 執行核心運算:
c = m^e mod n。
- 結果補位至 256 十六進位字元 (128 位元組):確保解密端能固定長度讀取。
- 十六進位字串轉 byte[]:每兩字元一位元組,以 16 進位解析。