runliuv

runliuv@cnblogs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

C#.NET FRAMEWORK XML私钥转PKCS1,PKCS8

使用了 BouncyCastle 这个dll ,到nuget中下载即可。

XML私钥转PKCS1

public string XmlToPem(string xmlPrivateKey)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(xmlPrivateKey);

            string priKey = null;
            var p = rsa.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 (TextWriter sw = new StringWriter())
            {
                var pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(sw);
                pemWriter.WriteObject(key);
                pemWriter.Writer.Flush();
                priKey = sw.ToString();
            }

            return priKey;
        }

XML私钥转PKCS8

public static string XmlToPKCS8(string xmlPrivateKey)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(xmlPrivateKey);

            string priKey = null;
             
            var bcKeyPair = DotNetUtilities.GetRsaKeyPair(rsa);
            var pkcs8Gen = new Pkcs8Generator(bcKeyPair.Private);
            var pemObj = pkcs8Gen.Generate();
            var pkcs8Out = new StringWriter();
            var pemWriter = new PemWriter(pkcs8Out);
            pemWriter.WriteObject(pemObj);
            priKey = pkcs8Out.ToString();
            pkcs8Out.Close();

            return priKey;
        }
posted on 2022-01-25 15:42  runliuv  阅读(577)  评论(0编辑  收藏  举报