RSA 相关

1. C# 生成Pem格式的公私钥,支持 PKCS 1 、PKCS2

using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.X509;
using System;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

            string xmlPrivateKey = rsa.ToXmlString(true);//XML密钥
            string pemPrivateKey = Xml2PemPrivate(xmlPrivateKey, "d:/mykey/privatePEM.txt",8);//PEM密钥

            string xmlPublicKey = rsa.ToXmlString(false);//XML公钥
            string pemPublicKey = Xml2PemPublic(xmlPublicKey, "d:/mykey/publicPEM.txt");//PEM公钥
        }

        /// <summary>
        ///  XML格式公钥转PEM格式公钥
        /// </summary>
        /// <param name="xml">XML格式的公钥</param>
        /// <param name="saveFile">保存文件的物理路径</param>
        /// <param name="pkcsVersion">PKCS版本 1为非 java 用 8为java用</param>
        public static string Xml2PemPublic(string xml, string saveFile)
        {
            var rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(xml);
            var p = rsa.ExportParameters(false);
            RsaKeyParameters key = new RsaKeyParameters(false, new BigInteger(1, p.Modulus), new BigInteger(1, p.Exponent));

           



            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(key);
            byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
           
            string publicKey = Convert.ToBase64String(serializedPublicBytes);


            using (var sw = new StreamWriter(saveFile))
            {
                sw.Write(publicKey);
            }
            return publicKey;
        }

        /// <summary>
        ///  XML格式私钥转PEM
        /// </summary>
        /// <param name="xml">XML格式私钥</param>
        /// <param name="saveFile">保存文件的物理路径</param>
        /// <param name="pkcsVersion">PKCS版本</param>
        public static string Xml2PemPrivate(string xml, string saveFile, int pkcsVersion=1)
        {
            var rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(xml);
            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));


            var privateKey = "";

            if (pkcsVersion == 1)
            {
                PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(key);
                byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();
                privateKey = Convert.ToBase64String(serializedPrivateBytes);

             
            }
            else if (pkcsVersion ==8)
            {
                // pkcs8 转换
                var pkcs8 = new Pkcs8Generator(key);
                 privateKey = Convert.ToBase64String(pkcs8.Generate().Content);

            }
            else
            {
                throw new InvalidOperationException("不支持的pkcsVersion");
            }


            using (var sw = new StreamWriter(saveFile))
            {
                sw.Write(privateKey);
            }

            return privateKey;
        }

        /// <summary>
        ///  格式化公钥/私钥
        /// </summary>
        /// <param name="key">生成的公钥/私钥</param>
        /// <param name="type">1:公钥 2:私钥</param>
        /// <returns>PEM格式的公钥/私钥</returns>
        //public static string Format(string key, int type)
        //{
        //    string result = string.Empty;

        //    int length = key.Length / 64;
        //    for (int i = 0; i < length; i++)
        //    {
        //        int start = i * 64;
        //        result = result + key.Substring(start, 64) + "\r\n";
        //    }

        //    result = result + key.Substring(length * 64);
        //    if (type == 1)
        //    {
        //        result = result.Insert(0, "-----BEGIN PUBLIC KEY-----\r\n");
        //        result += "\r\n-----END PUBLIC KEY-----";
        //    }
        //    if (type == 2)
        //    {
        //        result = result.Insert(0, "-----BEGIN PRIVATE KEY-----\r\n");
        //        result += "\r\n-----END PRIVATE KEY-----";
        //    }

        //    return result;
        //}
    }
}

 

posted @ 2020-07-01 17:50  小小高  阅读(206)  评论(0编辑  收藏  举报