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

C# 基於大整數類的 RSA 算法實現 (3) — 私鑰加密與公鑰解密

     編輯:關於C語言

私鑰加密(簽名)


/// 透過私鑰加密(簽名)
public byte[] EncryptByPrivateKey(string dataStr)
{
    RSAParameters rsap = RSA.ExportParameters(true);
    BigInteger biN = new BigInteger(rsap.Modulus);
    BigInteger biD = new BigInteger(rsap.D);
    return EncryptString(dataStr, biD, biN); // 以私鑰指數 d 加密
}

/// 指定參數私鑰加密
public byte[] EncryptByPrivateKey(string dataStr, string n, string d)
{
    BigInteger biN = new BigInteger(n, 16);
    BigInteger biD = new BigInteger(d, 16);
    return EncryptString(dataStr, biD, biN);
}

公鑰解密(驗簽)


/// 透過公鑰解密(驗證簽名)
public string DecryptByPublicKey(byte[] dataBytes)
{
    RSAParameters rsap = RSA.ExportParameters(false);
    BigInteger biN = new BigInteger(rsap.Modulus);
    BigInteger biE = new BigInteger(rsap.Exponent);
    return DecryptBytes(dataBytes, biE, biN); // 以公鑰指數 e 解密
}

/// 指定參數公鑰解密
public string DecryptByPublicKey(byte[] dataBytes, string n, string e)
{
    BigInteger biN = new BigInteger(n, 16);
    BigInteger biE = new BigInteger(e, 16);
    return DecryptBytes(dataBytes, biE, biN);
}

原理說明

  • 私鑰加密 = 數位簽名:持有私鑰者對資料加密,任何人可用公鑰解密驗證來源。
  • 公鑰解密 = 驗證簽名:用公鑰指數 e 執行 m = c^e mod n 還原原文。
  • 參數可從 RSA.ExportParameters 取得,或直接傳入十六進位字串。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved