JAVA,NET RSA密钥格式转换

简介: JAVA和NET RSA密钥格式相互转换(公钥,私钥) 做了一个小项目遇到java和.net非对称加密问题,java的公钥和私钥就直接是一个字符串的形式展示的,但是.net是以xml简单包裹形式展示的,这样就会出现秘钥不一致的情况,导致java和.

JAVA和NET RSA密钥格式相互转换(公钥,私钥)

做了一个小项目遇到java和.net非对称加密问题,java的公钥和私钥就直接是一个字符串的形式展示的,但是.net是以xml简单包裹形式展示的,这样就会出现秘钥不一致的情况,导致java和.net加密与解密出现障碍,

首先,我们来看一下java端的私钥和公钥的样子:

私钥:

MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBAL6VJN4ZkfZA3aPPgKC3xaqT/yZT5FOlQ5TGg6heVqDVEHHVLH1E+HEEmWmuTv2ngz9pZbzy9KWkJpV59W1dgNHSSk575VjUAv0BhZXFSH0lng2mZ2Q5/2dVxKsASjJ2bQiEGUD8LO5KpaLlfQpo3ANovBZvUtHw5exegnyXyZbDAgMBAAECgYEAr7YEWr1KhLcDYg9jMUqd9QokOSspnTEGoPlx016/EeO/GKSJMynOwSyTYQszisvRxzoecdmyU7GHXVMnQ2Ds7WvbcuNkIRWmxFa4nTkk2zNF6KByvvFwLiW4LQXF6B+uV7+ZNqvfhCoD/j2wki8jfWkuuAaKnTda/axHMi+zRYECQQD73iC2GjZyur4amJQPK6d+kDlJ0dYyyUvQa0vd6mfoPnQDOIqayBaueSwWIpLI/L7eUuP9CDFryQtdBvWqD/dBAkEAwbWcrybn0eaxiPZacZLZXzXO8g12hYoXT1h0DTLvy1rnVUOspNfKZcBZMjPxT4+QEknoTShSnSbJ5sHitfZxAwJBANMlU2z2KqEh1k77jFvvb9oVVEGDbTtkL2+JE6/1W6iB+sXcd63sgb9Ai+n+j+l4oRZGjSTJ4oyGnUUemYI5IkECQQCA9JNrcv4PGYIFCOPrCfTV0m+Dan0Fp4mfE+amRsumWEz60UOktdeS53s51aSG767czgDtJLPi1MjCaz6vHnHbAkEA4NxLLg6UCAoCpXMgqqZHWMgbMwNNFr9diCWP/tZ5OJmWYHgn7zfqMXa/RNaethjdG1biIkj5h7qm6XDBBqGuxw==

公钥:

MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+lSTeGZH2QN2jz4Cgt8Wqk/8mU+RTpUOUxoOoXlag1RBx1Sx9RPhxBJlprk79p4M/aWW88vSlpCaVefVtXYDR0kpOe+VY1AL9AYWVxUh9JZ4NpmdkOf9nVcSrAEoydm0IhBlA/CzuSqWi5X0KaNwDaLwWb1LR8OXsXoJ8l8mWwwIDAQAB

我们再来看一下.net端的私钥和公钥的样子:
私钥:

<RSAKeyValue><Modulus>vpUk3hmR9kDdo8+AoLfFqpP/JlPkU6VDlMaDqF5WoNUQcdUsfUT4cQSZaa5O/aeDP2llvPL0paQmlXn1bV2A0dJKTnvlWNQC/QGFlcVIfSWeDaZnZDn/Z1XEqwBKMnZtCIQZQPws7kqlouV9CmjcA2i8Fm9S0fDl7F6CfJfJlsM=</Modulus><Exponent>AQAB</Exponent><P>+94gtho2crq+GpiUDyunfpA5SdHWMslL0GtL3epn6D50AziKmsgWrnksFiKSyPy+3lLj/Qgxa8kLXQb1qg/3QQ==</P><Q>wbWcrybn0eaxiPZacZLZXzXO8g12hYoXT1h0DTLvy1rnVUOspNfKZcBZMjPxT4+QEknoTShSnSbJ5sHitfZxAw==</Q><DP>0yVTbPYqoSHWTvuMW+9v2hVUQYNtO2Qvb4kTr/VbqIH6xdx3reyBv0CL6f6P6XihFkaNJMnijIadRR6ZgjkiQQ==</DP><DQ>gPSTa3L+DxmCBQjj6wn01dJvg2p9BaeJnxPmpkbLplhM+tFDpLXXkud7OdWkhu+u3M4A7SSz4tTIwms+rx5x2w==</DQ><InverseQ>4NxLLg6UCAoCpXMgqqZHWMgbMwNNFr9diCWP/tZ5OJmWYHgn7zfqMXa/RNaethjdG1biIkj5h7qm6XDBBqGuxw==</InverseQ><D>r7YEWr1KhLcDYg9jMUqd9QokOSspnTEGoPlx016/EeO/GKSJMynOwSyTYQszisvRxzoecdmyU7GHXVMnQ2Ds7WvbcuNkIRWmxFa4nTkk2zNF6KByvvFwLiW4LQXF6B+uV7+ZNqvfhCoD/j2wki8jfWkuuAaKnTda/axHMi+zRYE=</D></RSAKeyValue>

公钥:

<RSAKeyValue><Modulus>vpUk3hmR9kDdo8+AoLfFqpP/JlPkU6VDlMaDqF5WoNUQcdUsfUT4cQSZaa5O/aeDP2llvPL0paQmlXn1bV2A0dJKTnvlWNQC/QGFlcVIfSWeDaZnZDn/Z1XEqwBKMnZtCIQZQPws7kqlouV9CmjcA2i8Fm9S0fDl7F6CfJfJlsM=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>

一下给出java和.net互相转化代码


 

不多说直接上代码,需要引用开源类库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.Asn1.X509;
 5 using Org.BouncyCastle.Crypto.Parameters;
 6 using Org.BouncyCastle.Math;
 7 using Org.BouncyCastle.Pkcs;
 8 using Org.BouncyCastle.Security;
 9 using Org.BouncyCastle.X509;
10 /// <summary>
11 /// RSA密钥格式转换
12 /// </summary>
13 public class RSAKeyConvert
14 {
15     /// <summary>    
16     /// RSA私钥格式转换,java->.net    
17     /// </summary>    
18     /// <param name="privateKey">java生成的RSA私钥</param>    
19     /// <returns></returns>   
20     public static string RSAPrivateKeyJava2DotNet(string privateKey)
21     {
22         RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));
23         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>",
24         Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()),
25         Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()),
26         Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()),
27         Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()),
28         Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()),
29         Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()),
30         Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()),
31          Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned()));
32     }
33     /// <summary>    
34     /// RSA私钥格式转换,.net->java    
35     /// </summary>    
36     /// <param name="privateKey">.net生成的私钥</param>    
37     /// <returns></returns>   
38     public static string RSAPrivateKeyDotNet2Java(string privateKey)
39     {
40         XmlDocument doc = new XmlDocument();
41         doc.LoadXml(privateKey);
42         BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
43         BigInteger exp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
44         BigInteger d = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText));
45         BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText));
46         BigInteger q = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText));
47         BigInteger dp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText));
48         BigInteger dq = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText));
49         BigInteger qinv = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("InverseQ")[0].InnerText));
50         RsaPrivateCrtKeyParameters privateKeyParam = new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv);
51         PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam);
52         byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();
53         return Convert.ToBase64String(serializedPrivateBytes);
54     }
55     /// <summary>    
56     /// RSA公钥格式转换,java->.net    
57     /// </summary>    
58     /// <param name="publicKey">java生成的公钥</param>    
59     /// <returns></returns>    
60     public static string RSAPublicKeyJava2DotNet(string publicKey)
61     {
62         RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));
63         return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>",
64             Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()),
65             Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned()));
66     }
67     /// <summary>    
68     /// RSA公钥格式转换,.net->java    
69     /// </summary>    
70     /// <param name="publicKey">.net生成的公钥</param>    
71     /// <returns></returns>   
72     public static string RSAPublicKeyDotNet2Java(string publicKey)
73     {
74         XmlDocument doc = new XmlDocument(); doc.LoadXml(publicKey);
75         BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
76         BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
77         RsaKeyParameters pub = new RsaKeyParameters(false, m, p);
78         SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub);
79         byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
80         return Convert.ToBase64String(serializedPublicBytes);
81     }
82 }

 

 

相关文章
|
7月前
|
Java C# 开发者
【干货】Java开发者快速上手.NET指南
【干货】Java开发者快速上手.NET指南
|
7月前
|
算法 安全 Java
Java 实现 RSA 非对称加密算法-加解密和签名验签
Java 实现 RSA 非对称加密算法-加解密和签名验签
302 0
|
1月前
|
Java 网络安全 Maven
Exception in thread "main" java.lang.NoSuchMethodError: okhttp3.OkHttpClient$Builder.sslSocketFactory(Ljavax/net/ssl/SSLSocketFactory;Ljavax/net/ssl/X509TrustManager;)Lokhttp3/OkHttpClient$Builder; 问题处理
【10月更文挑战第26天】Exception in thread "main" java.lang.NoSuchMethodError: okhttp3.OkHttpClient$Builder.sslSocketFactory(Ljavax/net/ssl/SSLSocketFactory;Ljavax/net/ssl/X509TrustManager;)Lokhttp3/OkHttpClient$Builder; 问题处理
45 2
|
5月前
|
网络协议 Java Apache
【Java】已解决java.net.HttpRetryException异常
【Java】已解决java.net.HttpRetryException异常
144 0
|
5月前
|
网络协议 Java
【Java】已解决java.net.UnknownHostException异常
【Java】已解决java.net.UnknownHostException异常
1115 0
|
4月前
|
算法 Java 测试技术
java 访问ingress https报错javax.net.ssl.SSLHandshakeException: Received fatal alert: protocol_version
java 访问ingress https报错javax.net.ssl.SSLHandshakeException: Received fatal alert: protocol_version
|
4月前
|
Java 开发工具 Spring
【Azure Spring Cloud】使用azure-spring-boot-starter-storage来上传文件报错: java.net.UnknownHostException: xxxxxxxx.blob.core.windows.net: Name or service not known
【Azure Spring Cloud】使用azure-spring-boot-starter-storage来上传文件报错: java.net.UnknownHostException: xxxxxxxx.blob.core.windows.net: Name or service not known
|
5月前
|
开发框架 安全 Java
.net和java有什么样的区别?
Java和.NET在本质、编程语言、生态系统与工具、跨平台性、应用领域、性能与效率以及安全性与可靠性等方面都存在明显的区别。选择哪个平台取决于具体的需求、技术栈和目标平台。
330 7
|
6月前
|
网络协议 Java 程序员
TCP/IP协议栈是网络通信基础,Java的`java.net`包提供工具,使开发者能利用TCP/IP创建网络应用
【6月更文挑战第23天】 **TCP/IP协议栈是网络通信基础,它包含应用层(HTTP, FTP等)、传输层(TCP, UDP)、网络层(IP)、数据链路层(帧, MAC地址)和物理层(硬件信号)。Java的`java.net`包提供工具,使开发者能利用TCP/IP创建网络应用,如Socket和ServerSocket用于客户端和服务器通信。**
58 3
|
6月前
|
Java C# 数据安全/隐私保护