引用 using System.Security.Cryptography;
直接使用 以下函式即可
/// <summary>
/// RSA加密資料
/// </summary>
/// <param name="express">要加密資料</param>
/// <param name="KeyContainerName">密匙容器的名稱</param>
/// <returns></returns>
public static string RSAEncryption(string express, string KeyContainerName = null)
{
System.Security.Cryptography.CspParameters param = new System.Security.Cryptography.CspParameters();
param.KeyContainerName = KeyContainerName ?? "zhiqiang"; //密匙容器的名稱,保持加密解密一致才能解密成功
using (System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(param))
{
byte[] plaindata = System.Text.Encoding.Default.GetBytes(express);//將要加密的字串轉換為位元組陣列
byte[] encryptdata = rsa.Encrypt(plaindata, false);//將加密後的位元組資料轉換為新的加密位元組陣列
return Convert.ToBase64String(encryptdata);//將加密後的位元組陣列轉換為字串
}
}
/// RSA解密資料
/// </summary>
/// <param name="express">要解密資料</param>
/// <param name="KeyContainerName">密匙容器的名稱</param>
/// <returns></returns>
public static string RSADecrypt(string ciphertext, string KeyContainerName = null)
{
System.Security.Cryptography.CspParameters param = new System.Security.Cryptography.CspParameters();
param.KeyContainerName = KeyContainerName ?? "zhiqiang"; //密匙容器的名稱,保持加密解密一致才能解密成功
using (System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(param))
{
byte[] encryptdata = Convert.FromBase64String(ciphertext);
byte[] decryptdata = rsa.Decrypt(encryptdata, false);
return System.Text.Encoding.Default.GetString(decryptdata);
}
}
參考來源: https://iter01.com/432462.html
沒有留言:
張貼留言