.net中,處於安全的考慮,RSACryptoServiceProvider類,解密時只有同時擁有公鑰和私鑰才能夠。緣由是公鑰是公開的,會被多人持有。這樣的數據傳輸是不安全的。C#RSA私鑰加密,公鑰解密出錯的緣由!html
公鑰密鑰生成後,保存在同名文件夾下面,以下圖:算法
using System; using System.IO; using System.Security.Cryptography;//必須引用 namespace RSA { class Program { static void Main(string[] args) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); using (StreamWriter writer = new StreamWriter("PrivateKey.xml")) //這個文件要保密... { writer.WriteLine(rsa.ToXmlString(true)); } using (StreamWriter writer = new StreamWriter("PublicKey.xml")) { writer.WriteLine(rsa.ToXmlString(false)); } } } }
public static void GKEY()//(計算機)生成密鑰 GKEY(generate key),generate the RSA public and private keys { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { string publicKey = rsa.ToXmlString(false); // 公鑰 string privateKey = rsa.ToXmlString(true); // 私鑰 } }
直接斷點調式複製公鑰密鑰出來用安全
#region RSA /// <summary> /// RSA加密 /// </summary> /// <param name="publickey"></param> /// <param name="content"></param> /// <returns></returns> public static string RSAEncrypt(string publickey, string content) { publickey = @"<RSAKeyValue><Modulus>0wE26IHp4U9OLtPhJ+fT8ej6aWORFP8pd++MjUuhkQQm/zhcImbxQbjxtSAftz+kkDwGDFJpSldQPyigOGcUx7PofTc6VhiFik9E9SsxV9n0iEEtqUndDfmBJfPAWt+4UDMwKakgZqFoapDuwjKlTErFvKCyKCs+qN9OZvZwKWk=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); byte[] cipherbytes; rsa.FromXmlString(publickey); cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false); return Convert.ToBase64String(cipherbytes); } /// <summary> /// RSA解密 /// </summary> /// <param name="privatekey"></param> /// <param name="content"></param> /// <returns></returns> public static string RSADecrypt(string privatekey, string content) { privatekey = @"<RSAKeyValue><Modulus>0wE26IHp4U9OLtPhJ+fT8ej6aWORFP8pd++MjUuhkQQm/zhcImbxQbjxtSAftz+kkDwGDFJpSldQPyigOGcUx7PofTc6VhiFik9E9SsxV9n0iEEtqUndDfmBJfPAWt+4UDMwKakgZqFoapDuwjKlTErFvKCyKCs+qN9OZvZwKWk=</Modulus><Exponent>AQAB</Exponent><P>8Ei6NIsZtgV3DQjuGHfGLS6o1O+IUXxzjqLxdMm77yhEPUxR9YPIxODJ2VVTddXSAHxViJJt30yJ7JhVz6cpQw==</P><Q>4M49NrmalgVQFMsea2RMB1qN8fAPfIw5G9q9hzsLcWSCmkeRRIQlvPYflVEKAYKiDVVzENETbnnduFXWBABx4w==</Q><DP>t+JQbemN0Zi5FQaif6MZzHYKynpNTl75aE0Wj5Pa+RlNr8N6bXNe8Bw/HM2Jw4HQ5oJASvYUk3DVlHS4JuP8VQ==</DP><DQ>lT62iv9brp9mU/epgVh71SH8PJPIZEJfo6tryjyb0zMMNcqvmZI1z6aCv0mm3+vPFBUXqCF1yhFj7n4l8FAvSw==</DQ><InverseQ>flrvgxHvf4l+fdymEVDgKjsfGqshOpppoNgZj9kpeWBto3o8z++Ki6eSLQT3nVnpx2QCZeTWkxTED4nhSLKscw==</InverseQ><D>cQTCg1Eqk7sltmFYxUYgOP/AOPjSufteG9acYwYymPkvZh6rAuY+rSRBmvGE62NUYskzuB/gM6iG2/2HrA5SixfNgCvZ+nsK+kX5pzQRsYdD71ViQW0hOanXwj45I2zHRgBiuTtCUP0fs5pISmQkaeJkDL5pO2l+wvlgl+wunj0=</D></RSAKeyValue>"; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); byte[] cipherbytes; rsa.FromXmlString(privatekey); cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false); return Encoding.UTF8.GetString(cipherbytes); } #endregion
須要依賴一個第三方庫,叫BouncyCastle
在線獲取安裝包的代碼以下:app
PM > Install-Package BouncyCastleide
若是不知道怎麼打開vs2013 控制檯的請看下面
tips:打開VS2013控制檯方法測試
public static void XMLConvertToPEM()//XML格式密鑰轉PEM { var rsa2 = new RSACryptoServiceProvider(); using (var sr = new StreamReader("e:\\PrivateKey.xml")) { rsa2.FromXmlString(sr.ReadToEnd()); } var p = rsa2.ExportParameters(true); var key = new RsaPrivateCrtKeyParameters( new BigInteger(1, p.Modulus), new BigInteger(1, p.Exponent), new BigInteger(1, p.D), new BigInteger(1, p.P), new BigInteger(1, p.Q), new BigInteger(1, p.DP), new BigInteger(1, p.DQ), new BigInteger(1, p.InverseQ)); using (var sw = new StreamWriter("e:\\PrivateKey.pem")) { var pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(sw); pemWriter.WriteObject(key); } }
public static void PEMConvertToXML()//PEM格式密鑰轉XML { AsymmetricCipherKeyPair keyPair; using (var sr = new StreamReader("e:\\PrivateKey.pem")) { var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(sr); keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject(); } var key = (RsaPrivateCrtKeyParameters)keyPair.Private; var p = new RSAParameters { Modulus = key.Modulus.ToByteArrayUnsigned(), Exponent = key.PublicExponent.ToByteArrayUnsigned(), D = key.Exponent.ToByteArrayUnsigned(), P = key.P.ToByteArrayUnsigned(), Q = key.Q.ToByteArrayUnsigned(), DP = key.DP.ToByteArrayUnsigned(), DQ = key.DQ.ToByteArrayUnsigned(), InverseQ = key.QInv.ToByteArrayUnsigned(), }; var rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(p); using (var sw = new StreamWriter("e:\\PrivateKey.xml")) { sw.Write(rsa.ToXmlString(true)); } }
請點擊:參考spa
CER和pfx證書的生成和使用.net