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

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

时间: 2024-10-13 19:33:07

asp.net RSA密钥之C#格式与Java格式转换(PEM格式)的相关文章

Java日期转换SimpleDateFormat格式大全(转)

24小时制时间显示: public class Datetime { public static void main(String args[]){ java.util.Date current=new java.util.Date(); java.text.SimpleDateFormat sdf=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String c=sdf.format(current); System.ou

fastJson java后台转换json格式数据

什么事JSON? JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式. 易于人阅读和编写.同时也易于机器解析和生成. 它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一个子集. JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等

java批量转换图片格式

废话不多直接上代码,代码其实也不多.... package com.qiao.testImage; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; public class imageChange { public

.NET与JAVA RSA密钥格式转换

一.该篇内容用于记录.net和Java之间,RSA公密钥的转换 using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; using Org.BouncyCastle.Pkcs; using Org.BouncyCastle.Security; using Org.BouncyC

RSA密钥之C#格式与Java格式转换

前言 最近由于项目需求,服务端由c#编写,客户端由java编写.通信数据使用RSA非对称加密.但是java和c#生成的密钥格式是不一样的,所以需要转换格式才可以正常使用.网上搜到使用java进行格式转换的代码(如:http://blog.csdn.net/road2010/article/details/40071881 ),本文将给出一种c#的实现方法. 密钥格式 java密钥格式如下: 私钥: MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBA

JAVA,NET RSA密钥格式转换

JAVA和NET RSA密钥格式相互转换(公钥,私钥) 不多说直接上代码,需要引用开源类库BouncyCastle.Crypto.dll 也可以在这里下载http://downloads.bouncycastle.org/csharp/bccrypto-net-1.7-bin.zip 以下为转化代码 1 using System; 2 using System.Xml; 3 using Org.BouncyCastle.Asn1.Pkcs; 4 using Org.BouncyCastle.As

.NET Core RSA密钥的xml、pkcs1、pkcs8格式转换和JavaScript、Java等语言进行对接

众所周知在.NET下的RSA类所生成的密钥为Xml格式,而其他语言比如java一般使用pkcs8格式的密钥,JavaScript一般使用pkcs1格式.我们在开发过程中很可能遇到需要与其他语言开发的api进行对接,如果遇到RSA加密解密,我们肯定需要保证key是相同的,才能保证数据的正确处理,我们肯定需要对密钥进行转换,下面我将我自己的使用经验分享给大家. pkcs1和pkcs8的操作借助了开源项目bouncycastle RSAUtil 项目 RSAUtil 项目是.NET Core下RSA算

全面解决.Net与Java互通时的RSA加解密问题,使用PEM格式的密钥文件

一.缘由 RSA是一种常用的非对称加密算法.所以有时需要在不用编程语言中分别使用RSA的加密.解密.例如用Java做后台服务端,用C#开发桌面的客户端软件时.由于 .Net.Java 的RSA类库存在很多细节区别,尤其是它们支持的密钥格式不同.导致容易出现“我加密的数据对方不能解密,对方加密的数据我不能解密,但是自身是可以正常加密解密”等情况.虽然网上已经有很多文章讨论 .Net与Java互通的RSA加解密,但是存在不够全面.需要第三方dll.方案复杂 等问题.于是我仔细研究了这一课题,得到了一

Windows下RSA密钥生成工具openssl

点击下载 1. 生成原始 RSA私钥文件 private_key.pem openssl genrsa -out private_key.pem 1024 2. 将原始 RSA私钥转换为 pkcs8格式 openssl pkcs8 -topk8 -inform PEM -in private_key.pem -outform PEM -nocrypt -out rsa_private_key.pem 3. 生成 RSA公钥 rsa_public_key.pem openssl rsa -in p