C# RSA加解密
引入dll(BouncyCastle.Crypto)
- 密钥实体
/// <summary>
/// 密钥实体
/// </summary>
public class RSAKEY {
/// <summary>
/// 公钥
/// </summary>
public string PublicKey { get; set; }
/// <summary>
/// 私钥
/// </summary>
public string PrivateKey { get; set; }
}
- RSA加密和解密
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Crypto.Encodings;
/// <summary>
/// RSA加密
/// </summary>
public class RSACrypto
{
/// <summary>
/// 获取秘钥
/// </summary>
/// <returns></returns>
public RSAKEY GetKey()
{
//RSA密钥对的构造器
RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();
//RSA密钥构造器的参数
RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(
Org.BouncyCastle.Math.BigInteger.ValueOf(3),
new Org.BouncyCastle.Security.SecureRandom(),
1024,//密钥长度
25);
//用参数初始化密钥构造器
keyGenerator.Init(param);
//产生密钥对
AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair();
//获取公钥和密钥
AsymmetricKeyParameter publicKey = keyPair.Public;
AsymmetricKeyParameter privateKey = keyPair.Private;
SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);
Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object();
byte[] publicInfoByte = asn1ObjectPublic.GetEncoded("UTF-8");
Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();
byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded("UTF-8");
return new RSAKEY(){
PublicKey = Convert.ToBase64String(publicInfoByte),
PrivateKey = Convert.ToBase64String(privateInfoByte)
};
}
/// <summary>
/// 获取公钥数据
/// </summary>
/// <param name="key">公钥</param>
/// <returns></returns>
private AsymmetricKeyParameter GetPublicKeyParameter(string key)
{
key = ReplaceCharacter(key);
byte[] publicInfoByte = Convert.FromBase64String(key);
Asn1Object pubKeyObj = Asn1Object.FromByteArray(publicInfoByte);//这里也可以从流中读取,从本地导入
AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(publicInfoByte);
return pubKey;
}
/// <summary>
/// 获取私钥数据
/// </summary>
/// <param name="key">私钥</param>
/// <returns></returns>
private AsymmetricKeyParameter GetPrivateKeyParameter(string key)
{
key = ReplaceCharacter(key);
byte[] privateInfoByte = Convert.FromBase64String(key);
AsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(privateInfoByte);
return priKey;
}
/// <summary>
/// 私钥加密
/// </summary>
/// <param name="val">值</param>
/// <param name="key">私钥</param>
/// <returns></returns>
public string EncryptByPrivateKey(string val, string key)
{
//非对称加密算法,加解密用
IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
//加密
try
{
engine.Init(true, GetPrivateKeyParameter(key));
byte[] byteData = System.Text.Encoding.UTF8.GetBytes(val);
var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);
return Convert.ToBase64String(ResultData);
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// 私钥解密
/// </summary>
/// <param name="val">值</param>
/// <param name="key">公钥</param>
/// <returns></returns>
public string DecryptByPrivateKey(string val, string key)
{
//非对称加密算法,加解密用
IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
//解密
try
{
engine.Init(false, GetPrivateKeyParameter(key));
byte[] byteData = Convert.FromBase64String(val);
var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);
return System.Text.Encoding.UTF8.GetString(ResultData);
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// 公钥加密
/// </summary>
/// <param name="val">值</param>
/// <param name="key">公钥</param>
/// <returns></returns>
public string EncryptByPublicKey(string val, string key)
{
//非对称加密算法,加解密用
IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
//加密
try
{
engine.Init(true, GetPublicKeyParameter(key));
byte[] byteData = System.Text.Encoding.UTF8.GetBytes(val);
var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);
return Convert.ToBase64String(ResultData);
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// 公钥解密
/// </summary>
/// <param name="val">值</param>
/// <param name="key">公钥</param>
/// <returns></returns>
public string DecryptByPublicKey(string val, string key)
{
val = ReplaceCharacter(val);
//非对称加密算法,加解密用
IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
//解密
try
{
engine.Init(false, GetPublicKeyParameter(key));
byte[] byteData = Convert.FromBase64String(val);
var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);
return System.Text.Encoding.UTF8.GetString(ResultData);
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// 替换指定字符串
/// </summary>
/// <param name="character">字符串</param>
/// <returns></returns>
public string ReplaceCharacter(string character)
{
return character.Replace("\r", "").Replace("\n", "").Replace(" ", "");
}
}
- 调用示例
protected void Page_Load(object sender, EventArgs e)
{
RSACrypto pr = new RSACrypto();
var rsa= pr.GetKey();//获取一对秘钥(公钥和私钥)
string val = "Hello World!";
公钥加密
//string pubkey = rsa.PublicKey;//公钥,对外公布,用于加密
//string enVal = pr.EncryptByPublicKey(val, pubkey);//加密值
私钥解密
//string priKey = rsa.PrivateKey;//私钥,自己保存,用于解密
//string deVal = pr.DecryptByPrivateKey(enVal, priKey);//解密值
//私钥加密
string priKey = rsa.PrivateKey;//私钥,用于加密
string enVal = pr.EncryptByPrivateKey(val, priKey);//加密值
//公钥解密
string pubkey = rsa.PublicKey;//公钥,用于解密
string deVal = pr.DecryptByPublicKey(enVal, pubkey);//解密值
}
4、源码