/// <summary>
/// RSA 公钥加密
/// </summary>
/// <param name="content">要加密的内容</param>
/// <param name="publickey">公钥</param>
/// <returns></returns>
public static string EncryptByPublicKey(string content, string publickey)
{
byte[] s = Convert.FromBase64String(publickey);
AsymmetricKeyParameter publicKey = PublicKeyFactory.CreateKey(s);
IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");
//公钥加密
c.Init(true, publicKey);
byte[] byteData = Encoding.UTF8.GetBytes(content);
byteData = c.DoFinal(byteData, 0, byteData.Length);
return Convert.ToBase64String(byteData);
}
/// <summary>
/// RSA加密
/// </summary>
/// <param name="content">加密明文</param>
/// <param name="privatekey">私钥</param>
/// <returns>返回密文</returns>
public static string RSAEncry(string content, string privatekey)
{
AsymmetricKeyParameter privateKey = PrivateKeyFactory.CreateKey(Convert.FromBase64String(privatekey));
IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");
//私钥加密
c.Init(true, privateKey);
byte[] byteData = Encoding.UTF8.GetBytes(content);
byteData = c.DoFinal(byteData, 0, byteData.Length);
return Convert.ToBase64String(byteData);
}
/// <summary>
/// RSA解密
/// </summary>
/// <param name="content">密文</param>
/// <param name="privatekey">私钥</param>
/// <returns>明文</returns>
public static string RSADeEncry(string content, string privatekey)
{
try
{
MemoryStream bufferStream = new MemoryStream();
byte[] bytData = Convert.FromBase64String(content);
int inputLength = bytData.Length;
AsymmetricKeyParameter privateKey = PrivateKeyFactory.CreateKey(Convert.FromBase64String(privatekey));
IBufferedCipher cipher = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");
cipher.Init(false, privateKey);
int offSet = 0;
byte[] cache;
int i = 0;
while (inputLength - offSet > 0)
{
if (inputLength - offSet > 128)
{
cache = cipher.DoFinal(bytData, offSet, 128);
}
else
{
cache = cipher.DoFinal(bytData, offSet, inputLength - offSet);
}
bufferStream.Write(cache, 0, cache.Length);
i++;
offSet = i * 128;
}
byte[] decryptedData = bufferStream.ToArray();
bufferStream.Close();
return Encoding.UTF8.GetString(bufferStream.ToArray());
}
catch (Exception e)
{
return e.Message;
}
}