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

C# 基於大整數類的 RSA 算法實現 (5) — 解密實現與關鍵細節

     編輯:關於C語言

關鍵實現細節說明

  • 分塊大小:理論最大 128 位元組,實際採用 120 位元組留餘量防止位溢出。
  • BigInteger 轉 byte[]:原用 GetBytes() 但發現有機率偏差,改用 ToHexString() 取十六進位字串再轉 byte[]。
  • 解密時必須補位:確保每塊長度固定 128 位元組。

解密核心程式碼


/// 
/// 解密位元組陣列
/// 
/// 待解密資料
/// 密鑰大質數 (d 或 e)
/// 大整數 N
/// 解密後字串
private string DecryptBytes(byte[] dataBytes, BigInteger KeyNum, BigInteger nNum)
{
    int len = dataBytes.Length;
    int len1 = (len % 128 == 0) ? len / 128 : len / 128 + 1;
    List tempbytes = new List();

    for (int i = 0; i < len1; i++)
    {
        int blockLen = (len >= 128) ? 128 : len;
        byte[] oText = new byte[blockLen];
        Array.Copy(dataBytes, i * 128, oText, 0, blockLen);

        BigInteger biText = new BigInteger(oText);
        BigInteger bIEnText = biText.modPow(KeyNum, nNum); // 核心 RSA 運算:m = c^d mod n

        byte[] testbyte = bIEnText.getBytes(); // 注意:此處仍用 getBytes,前文說明有偏風險
        string str = Encoding.UTF8.GetString(testbyte);
        tempbytes.AddRange(testbyte);

        len -= blockLen;
    }
    return Encoding.UTF8.GetString(tempbytes.ToArray());
}

驗證結果

經 10,000 次測試,無誤差出現。完整實現類別與大整數類請參考專案原始碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved