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

asp.net RSA密钥之C#格式与Java格式转换(PEM格式)

时间:2020-03-07 13:04:38      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:ansi   结果   sha1   sum   ram   amp   put   base64   obj   

//商户私钥(Java格式),公钥已上传
        private static string PrivateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDETH1ziFZ70KCIqTjZvzWs/MIjrcbFptR748voH8fXDsuG2XHU+ds4f8tbuqgp4d4pW7bgwtyJOOYTuRHxh2QsNKvVpg4EZmAWBWCzIHd4J2bWQYjUq+ZwF/Ht6eY/ysQ8rkfAGXvC5pwKAQuXqqCtTR4vxLlk+1jCGbgAbL7mAporOT84m0UB1en040ZMF/MpEfTE+w+Rnk8FFEbRgpSRY08I1ri/QWcAmtk7OCvoHz7YlPtkMe/ieLQbhZe81kvHn4ZDdHC9JgdgJKo7vNo8vLs4ed6uoOWBeNeXSGYl7cG2X3xuoGtaZjDOXKN4PiQvJkyDqwMEV1HLaOK6aH+BAgMBAAECggEBAML4zmomKWAQTj7fu5C/VBNJ9LAHLzEROTDaUlcAh/dU8oT8ZROFoHagJ/ygNSRvkZwISsh+EpqOCtXREzZH15QQl2ekj5Pj4bic6Bzht1w+W0F7JmZ/YCG1Gv";

 

 

/// <summary>
        /// 生成请求时通过证书的签名
        /// </summary>
        /// <param name="sPara">请求的参数数组</param>
        /// <returns>签名结果</returns>
        public static string BuildRequestKuaiQianSignOline(Dictionary<string, string> sPara)
        {
            //把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
            string signMsg = CreateLinkStringOline(sPara);
            
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(signMsg);
            
            var privateKey = RSAPrivateKeyJava2DotNet(PrivateKey);
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(privateKey);
            RSAPKCS1SignatureFormatter f = new RSAPKCS1SignatureFormatter(rsa);
            byte[] result;
            f.SetHashAlgorithm("SHA1");
            SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();
            result = sha.ComputeHash(bytes);
            string resignMsg = System.Convert.ToBase64String(f.CreateSignature(result)).ToString();
            return resignMsg;
        }

        /// <summary>
        /// RSA私钥格式转换,java->.net
        /// </summary>
        /// <param name="privateKey">java生成的RSA私钥</param>
        /// <returns></returns>
        public static string RSAPrivateKeyJava2DotNet(string privateKey)
        {
            RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));

            return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>",
                Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()),
                Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()),
                Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()),
                Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()),
                Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()),
                Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()),
                Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()),
                Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned()));
        }

        /// <summary>
        /// RSA私钥格式转换,.net->java
        /// </summary>
        /// <param name="privateKey">.net生成的私钥</param>
        /// <returns></returns>
        public static string RSAPrivateKeyDotNet2Java(string privateKey)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(privateKey);
            BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
            BigInteger exp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
            BigInteger d = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText));
            BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText));
            BigInteger q = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText));
            BigInteger dp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText));
            BigInteger dq = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText));
            BigInteger qinv = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("InverseQ")[0].InnerText));

            RsaPrivateCrtKeyParameters privateKeyParam = new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv);

            PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam);
            byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();
            return Convert.ToBase64String(serializedPrivateBytes);
        }

        /// <summary>
        /// RSA公钥格式转换,java->.net
        /// </summary>
        /// <param name="publicKey">java生成的公钥</param>
        /// <returns></returns>
        public static string RSAPublicKeyJava2DotNet(string publicKey)
        {
            RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));
            return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>",
                Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()),
                Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned()));
        }

        /// <summary>
        /// RSA公钥格式转换,.net->java
        /// </summary>
        /// <param name="publicKey">.net生成的公钥</param>
        /// <returns></returns>
        public static string RSAPublicKeyDotNet2Java(string publicKey)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(publicKey);
            BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
            BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
            RsaKeyParameters pub = new RsaKeyParameters(false, m, p);

            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub);
            byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
            return Convert.ToBase64String(serializedPublicBytes);
        }

        /// <summary>
        /// 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
        /// </summary>
        /// <param name="sArray">需要拼接的数组</param>
        /// <returns>拼接完成以后的字符串</returns>
        public static string CreateLinkStringOline(Dictionary<string, string> dicArray)
        {
            var vDic = (from objDic in dicArray orderby objDic.Key ascending select objDic); //按各字符的ASCII码从小到大排序
            StringBuilder prestr = new StringBuilder();
            foreach (KeyValuePair<string, string> temp in vDic)
            {
                prestr.Append(temp.Key + "=" + temp.Value + "&");
            }

            //去掉最後一個&字符
            int nLen = prestr.Length;
            prestr.Remove(nLen - 1, 1);
            
            return prestr.ToString();
        }

asp.net RSA密钥之C#格式与Java格式转换(PEM格式)

标签:ansi   结果   sha1   sum   ram   amp   put   base64   obj   

原文地址:https://www.cnblogs.com/cuihongyu3503319/p/12433555.html

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