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

//商户私钥(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();
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
RSA加密算法是一种非对称加密算法,公钥加密,私钥解密。在C#Java中,都内置了RSA加密算法的实现,但是在使用过程中,由于两个语言的实现细节不同,会导致在C#Java之间进行RSA加密的时候出现格式不兼容的问题。 为了解决这个问题,我们可以使用以下方法将C#格式RSA公钥/私钥换为Java格式RSA公钥/私钥: 1. 将C#RSA公钥/私钥换为XML格式的字符串。 C#中,可以使用以下方法将RSA公钥/私钥换为XML格式的字符串: ```csharp string publicKeyXml = rsa.ToXmlString(false); // 公钥 string privateKeyXml = rsa.ToXmlString(true); // 私钥 ``` 2. 将XML格式的字符串换为Java中的BigInteger类型。 Java中,可以使用以下方法将XML格式的字符串换为BigInteger类型: ```java BigInteger modulus = new BigInteger(1, Base64.getDecoder().decode(modulusString)); BigInteger exponent = new BigInteger(1, Base64.getDecoder().decode(exponentString)); ``` 其中,modulusString和exponentString分别是XML格式的字符串中的Modulus和Exponent节点的值,使用Base64解码后为BigInteger类型。 3. 使用BigInteger类型创建Java中的RSAPublicKey/RSAPrivateKey对象。 Java中,可以使用以下方法创建RSAPublicKey/RSAPrivateKey对象: ```java RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(modulus, exponent); RSAPublicKey publicKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(publicKeySpec); RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(modulus, exponent); RSAPrivateKey privateKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(privateKeySpec); ``` 其中,modulus和exponent是从XML格式的字符串中解析得到的BigInteger类型的值。 通过以上步骤,我们就可以将C#格式RSA公钥/私钥换为Java格式RSA公钥/私钥了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值