三、算法實現
加密
/// <summary>
/// 加密字符串
/// </summary>
/// <param name="dataStr">待加密字符串 </param>
/// <param name="keyNmu">密鑰大素數 </param>
/// <param name="nNum">大整數 N</param>
/// <returns>加密結果</returns>
private byte[] EncryptString(string dataStr, BigInteger keyNum, BigInteger nNum)
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(dataStr);
int len = bytes.Length;
int len1 = 0;
int blockLen = 0;
if ((len % 120) == 0)
len1 = len / 120;
else
len1 = len / 120 + 1;
List<byte> tempbytes = new List<byte>();
for (int i = 0; i < len1; i++)
{
if (len >= 120)
{
blockLen = 120;
}
else
{
blockLen = len;
}
byte[] oText = new byte[blockLen];
Array.Copy(bytes, i * 120, oText, 0, blockLen);
string res = Encoding.UTF8.GetString (oText);
BigInteger biText = new BigInteger (oText);
BigInteger bIEnText = biText.modPow (keyNum, nNum);
//補位
byte[] testbyte = null;
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();
}