C#RSA算法實現+如何將公鑰爲XML格式轉爲PEM格式,給object-C使用

.net中,處於安全的考慮,RSACryptoServiceProvider類,解密時只有同時擁有公鑰和私鑰才能夠。緣由是公鑰是公開的,會被多人持有。這樣的數據傳輸是不安全的。C#RSA私鑰加密,公鑰解密出錯的緣由!html

C#中用RSA算法生成公鑰和私鑰

方法一:

公鑰密鑰生成後,保存在同名文件夾下面,以下圖:算法


公鑰密鑰生成,所在路徑【RSA\RSA\bin\Debug】
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); // 私鑰 } }

直接斷點調式複製公鑰密鑰出來用安全

RSA加密解密類

#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

如何將公鑰爲XML格式轉爲PEM格式?

須要依賴一個第三方庫,叫BouncyCastle
在線獲取安裝包的代碼以下:app

PM > Install-Package BouncyCastleide

若是不知道怎麼打開vs2013 控制檯的請看下面
tips:打開VS2013控制檯方法測試


打開VS2013控制檯方法.png

安裝第三方庫成功圖示.png
方法一:在線轉換

請點擊這裏跳轉>>在線轉換加密

如何將密鑰XML格式和PEM格式互轉?【tips:這裏說的是密鑰,公鑰使用其餘方法】

1、將XML格式密鑰轉PEM
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); } }
1、將PEM格式密鑰轉XML
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

其餘【tips:待測試】

CER和pfx證書的生成和使用.net


CER和pfx證書.png

生成公鑰.png



文/飯糰小家(簡書做者) 原文連接:http://www.jianshu.com/p/faefcc58c79b 著做權歸做者全部,轉載請聯繫做者得到受權,並標註「簡書做者」。
相關文章
相關標籤/搜索