namespace Utility.Security
{
/// <summary>
/// RSA加密解密
/// </summary>
public class RSAUtil
{
/// <summary>
/// RSA加密
/// </summary>
/// <param name="str">需要加密的字符串</param>
/// <param name="encryptKey">密钥</param>
/// <returns>加密后的字符串</returns>
public static string RSAEncrypt(string str, string encryptKey)
{
byte[] bytes = Encoding.UTF8.GetBytes(str);
byte[] privKeyBytes = Convert.FromBase64String(encryptKey);
AsymmetricKeyParameter asymmetricKeyParameter = PrivateKeyFactory.CreateKey(privKeyBytes);
IAsymmetricBlockCipher signer = new Pkcs1Encoding(new RsaEngine());
signer.Init(true, asymmetricKeyParameter);
//加密
byte[] encryptBytes = signer.ProcessBlock(bytes, 0, bytes.Length);
string rsaString = Convert.ToBase64String(encryptBytes);
return rsaString;
}
/// <summary>
/// RSA解密
/// </summary>
/// <param name="str">需要解密的字符串</param>
/// <param name="decryptKey">密钥</param>
/// <returns>解密后的字符串</returns>
public static string RSADecrypt(string str, string decryptKey)
{
byte[] strBytes = Convert.FromBase64String(str);
byte[] keyBytes = Convert.FromBase64String(decryptKey);
AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(keyBytes);
IAsymmetricBlockCipher signer = new Pkcs1Encoding(new RsaEngine());
signer.Init(false, asymmetricKeyParameter);
byte[] decryptedBytes = signer.ProcessBlock(strBytes, 0, strBytes.Length);
string decryptString = Encoding.UTF8.GetString(decryptedBytes);
return decryptString;
}
}
}