Bouncycastle库C#版
官网地址为:http://www.bouncycastle.org/csharp/。
http://blog.csdn.net/popozhu/article/details/5812662
http://www.xuebuyuan.com/301023.html
从PEM文件读取秘钥
PemReader r = new PemReader(new StreamReader("Files/pubkey.pem"));
AsymmetricKeyParameter pubKey = (AsymmetricKeyParameter)r.ReadObject(); PemReader r = new PemReader(new StreamReader("Files/prvkey.pem"));
AsymmetricKeyParameter prvKey = (AsymmetricKeyParameter)r.ReadObject();
加载pfx证书库、读取证书、获取秘钥
FileStream ms = new FileStream("store.p12",OpenMode.Open);
Pkcs12Store store = new Pkcs12StoreBuilder().Build();
store.Load(ms, "".ToCharArray()); //获取第一个别名
IEnumerator itor = store.Aliases.GetEnumerator();
itor.MoveNext();
string alins = itor.Current.ToString(); AsymmetricKeyParameter prvKey=null;
AsymmetricKeyParameter pubKey=null; if(sotre.IsKeyEntry(alins))
prvKey = store.GetKey(alins).Key; cert = store.GetCertificate(alins).Certificate;
pubkey=cert.GetPublicKey();
加密、解密
AsymmetricKeyParameter prvKey=...;
AsymmetricKeyParameter pubKey=...; //公钥加密
string origin="abcd1234";
byte[] originbytes=Encoding.Default.getBytes(origin);
IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");
c.Init(true, pubKey);
byte[] encryBytes = c.DoFinal(origin);
string encryStr=Encoding.Default.GetString(encryBytes); //私钥解密
IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");
c.Init(false, prvKey);
byte[] recoverBytes=c.DoFinal(encryBytes );
string recover=Encoding.Default.GetString(recoverBytes);