首页 > Windows开发 > 详细

c#.net 调用BouncyCastle生成PEM格式的私钥和公钥

时间:2016-10-16 09:43:38      阅读:703      评论:0      收藏:0      [点我收藏+]
            RsaKeyPairGenerator r = new RsaKeyPairGenerator();
            r.Init(new KeyGenerationParameters(new SecureRandom(), 1024));
            AsymmetricCipherKeyPair keys = r.GenerateKeyPair();

            AsymmetricKeyParameter private_key = keys.Private;
            AsymmetricKeyParameter public_key = keys.Public;

            TextWriter textWriter = new StringWriter();
            PemWriter pemWriter = new PemWriter(textWriter);
            pemWriter.WriteObject(keys.Private);
            pemWriter.Writer.Flush();

            string privateKey = textWriter.ToString();
            txtPri.Text = privateKey;


            TextWriter textpubWriter = new StringWriter();
            PemWriter pempubWriter = new PemWriter(textpubWriter);
            pempubWriter.WriteObject(keys.Public);
            pempubWriter.Writer.Flush();
            string pubKey = textpubWriter.ToString();
            txtPub.Text = pubKey;

-

引用:

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;

--XML格式转PEM格式,引用:http://www.jianshu.com/p/faefcc58c79b

 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);
        }
    }

网上示例都是从文件读取出XML格式私钥,存入PEM文件中,PEM中就是转换好的格式。但直接存入string字符串中的代码还没研究出来。    读取XML私钥的代码可以换成生成XML私钥。

c#.net 调用BouncyCastle生成PEM格式的私钥和公钥

原文:http://www.cnblogs.com/runliuv/p/5965951.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!