二、加密處理(分別對應兩種密鑰取得方式)
公鑰加密
/// <summary>
/// 通過公鑰加密
/// </summary>
/// <param name="dataStr">待加密字符串 </param>
/// <returns>加密結果</returns>
public byte[] EncryptByPublicKey(string dataStr)
{
//取得公鑰參數
RSAParameters rsaparameters = RSA.ExportParameters(false);
byte[] keyN = rsaparameters.Modulus;
byte[] keyE = rsaparameters.Exponent;
//大整數N
BigInteger biN = new BigInteger(keyN);
//公鑰大素數
BigInteger bIE = new BigInteger(keyE);
//加密
return EncryptString(dataStr, bIE, biN);
}
/// <summary>
/// 通過公鑰加密
/// </summary>
/// <param name="dataStr">待加密字符串 </param>
/// <param name="n">大整數 n</param>
/// <param name="e">公鑰 </param>
/// <returns>加密結果</returns>
public byte[] EncryptByPublicKey(string dataStr,string n,string e)
{
//大整數N
BigInteger biN = new BigInteger(n,16);
//公鑰大素數
BigInteger bIE = new BigInteger(e,16);
//加密
return EncryptString(dataStr, bIE, biN);
}
私鑰解密
/// <summary>
/// 通過私鑰解密
/// </summary>
/// <param name="dataBytes">待解密字符 數組</param>
/// <returns>解密結果</returns>
public string DecryptByPrivateKey(byte[] dataBytes)
{
//取得私鑰參數
RSAParameters rsaparameters = RSA.ExportParameters(true);
byte[] keyN = rsaparameters.Modulus;
byte[] keyD = rsaparameters.D;
//大整數N
BigInteger biN = new BigInteger(keyN);
//私鑰大素數
BigInteger biD = new BigInteger(keyD);
//解密
return DecryptBytes(dataBytes, biD, biN);
}
/// <summary>
/// 通過私鑰解密
/// </summary>
/// <param name="dataBytes">待解密字符 數組</param>
/// <param name="n">大整數 n</param>
/// <param name="d">私鑰 </param>
/// <returns>解密結果</returns>
public string DecryptByPrivateKey(byte[] dataBytes,string n,string d)
{
//大整數N
BigInteger biN = new BigInteger(n,16);
//私鑰大素數
BigInteger biD = new BigInteger(d,16);
//解密
return DecryptBytes(dataBytes, biD, biN);
}