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

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

     編輯:關於C語言

公鑰加密(機密性)


/// 透過公鑰加密
public byte[] EncryptByPublicKey(string dataStr)
{
    RSAParameters rsap = RSA.ExportParameters(false);
    BigInteger biN = new BigInteger(rsap.Modulus);
    BigInteger biE = new BigInteger(rsap.Exponent);
    return EncryptString(dataStr, biE, biN); // 以公鑰指數 e 加密
}

/// 指定參數公鑰加密
public byte[] EncryptByPublicKey(string dataStr, string n, string e)
{
    BigInteger biN = new BigInteger(n, 16);
    BigInteger biE = new BigInteger(e, 16);
    return EncryptString(dataStr, biE, biN);
}

私鑰解密


/// 透過私鑰解密
public string DecryptByPrivateKey(byte[] dataBytes)
{
    RSAParameters rsap = RSA.ExportParameters(true);
    BigInteger biN = new BigInteger(rsap.Modulus);
    BigInteger biD = new BigInteger(rsap.D);
    return DecryptBytes(dataBytes, biD, biN); // 以私鑰指數 d 解密
}

/// 指定參數私鑰解密
public string DecryptByPrivateKey(byte[] dataBytes, string n, string d)
{
    BigInteger biN = new BigInteger(n, 16);
    BigInteger biD = new BigInteger(d, 16);
    return DecryptBytes(dataBytes, biD, biN);
}

雙重用途總結

操作用途指數
公鑰加密機密傳輸(僅私鑰持有者可解)e
私鑰解密接收端解密d
私鑰加密數位簽名(身分驗證)d
公鑰解密驗證簽名e

核心邏輯皆委派給 EncryptString / DecryptBytes,差別在於傳入的指數參數。

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