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

來源:互聯網
上載者:User

標籤:如何   static   odi   a演算法   tip   rom   blog   產生密鑰   pack   

.net中,處於安全的考慮,RSACryptoServiceProvider類,解密時只有同時擁有公開金鑰和私密金鑰才可以。原因是公開金鑰是公開的,會被多人持有。這樣的資料轉送是不安全的。C#RSA私密金鑰加密,公開金鑰解密出錯的原因!

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
線上擷取安裝包的代碼如下:

PM > Install-Package BouncyCastle

如果不知道怎麼開啟vs2013 控制台的請看下面
tips:開啟VS2013控制台方法


開啟VS2013控制台方法.png

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

請點擊這裡跳轉>>線上轉換

如何將密鑰XML格式和PEM格式互轉?【tips:這裡說的是密鑰,公開金鑰使用其他方法】一、將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);        }    }

 

一、將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));        }    }

 

請點擊:參考

其他【tips:待測試】

CER和pfx認證的產生和使用


CER和pfx認證.png
產生公開金鑰.png

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.