RSA加密与解密

/// <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;
}
}

转载于:https://www.cnblogs.com/brucehome/p/6517771.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值