码迷,mamicode.com
首页 > 编程语言 > 详细

C#RSA算法实现+如何将公钥为XML格式转为PEM格式,给object-C使用

时间:2017-11-20 01:20:27      阅读:455      评论:0      收藏:0      [点我收藏+]

标签:如何   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使用

标签:如何   static   odi   a算法   tip   rom   blog   生成密钥   pack   

原文地址:http://www.cnblogs.com/micenote/p/7862989.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!