首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 基於大整數類的 RSA 算法實現 (4) — 加密實現

     編輯:關於C語言

加密核心程式碼


/// 
/// 加密字串
/// 
/// 待加密字串
/// 密鑰大質數 (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 進位解析。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved