RSA加密之C#格式與Java格式的轉換

前言       java

         在與客戶對接過程當中,因爲對方服務端由Java編寫,而咱們這調用端是C#的。通訊數據使用RSA非對稱加密。可是Java與C#生成的密鑰格式是不同的,對方提供的是Java的公鑰,因此須要轉換格式才能夠正常使用。在網上搜到使用C#進行格式轉換的代碼,在此作一下筆錄(因爲參考文章已經寫的很好了,本文只是用於記錄,將參考代碼拷下)。c#

密鑰格式ide

        Java密鑰格式以下:ui

        私鑰:加密

   
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKSZSSEdPhv77O5ocnLNGXeQ21qJDArC1+yId+9/pY5bXkZk5vCB49EpfMwNukLv6AJqofThZPNOs1t015fdEYIUnkIc2QVxRwa0xTeFP6N8D4WQXRWs4fNG27JK5kP45s+9KlJtx5hs7G97aMczehIWpHaO6j9inOmjlU8l62KZAgMBAAECgYEAmK3TRtMwRJb33OGnn9OeFumYfy92qxi3X6Hq1o6qDBW2qkd4bImfv+ni6AinyOVuaadt2Y+lq4dKGcCVJzoZvPm1VKxD2y7xKa8/vEbPRiRTt0qnPq9T7UJkpDsiXf/zOMfWdjc3uA1bPnQ65RWHSJ7zAE+Gd7xnyCE5MEyijLECQQDVYqQWDqOVLZ5lJUuIfUIrhv26GvuoTX8v60+opCz4/Mdfh6JlefICVD6SAaYvufXBHVFY26JicNlR62ZOiBoNAkEAxXhsuEnNJNQcQHEVTPZoulbMbTV1VZIDQ1zjG8fvu8sv6IBYcR5+EsC8n3/6RkW8/iCJDzxE++VHzhoSQSoDvQJBAM6/63J/rpndAIrJ7vyJOPLJsc9/U3SH2gMJAT7KC9UXvuldlsixtf3xuEpplKbLjEUXbfklnZm586a+6XqPvoUCQDFotltOLARBBmihYuEE7qNhQHk63QbyJ9rdDP5Qgo2Mg4o7QuXa6VSr4QZPsUGQBX/YiDLFs8ULU3IgV9zyNEkCQADAYR8DctYzg0eBGdcOrDA5Szc62pYrS2wk89wUxyL4FyDL3omkVMKvtu5tccy7Xht2ikJZRqefZ3dS7ASm8/4=
View Code

         公鑰:  
spa

   
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCkmUkhHT4b++zuaHJyzRl3kNtaiQwKwtfsiHfvf6WOW15GZObwgePRKXzMDbpC7+gCaqH04WTzTrNbdNeX3RGCFJ5CHNkFcUcGtMU3hT+jfA+FkF0VrOHzRtuySuZD+ObPvSpSbceYbOxve2jHM3oSFqR2juo/Ypzpo5VPJetimQIDAQAB
View Code

         .NET密鑰格式以下:.net

        私鑰:    
3d

   
<RSAKeyValue>
  <Modulus>pJlJIR0+G/vs7mhycs0Zd5DbWokMCsLX7Ih373+ljlteRmTm8IHj0Sl8zA26Qu/oAmqh9OFk806zW3TXl90RghSeQhzZBXFHBrTFN4U/o3wPhZBdFazh80bbskrmQ/jmz70qUm3HmGzsb3toxzN6Ehakdo7qP2Kc6aOVTyXrYpk=</Modulus>
  <Exponent>AQAB</Exponent>
  <P>1WKkFg6jlS2eZSVLiH1CK4b9uhr7qE1/L+tPqKQs+PzHX4eiZXnyAlQ+kgGmL7n1wR1RWNuiYnDZUetmTogaDQ==</P>
  <Q>xXhsuEnNJNQcQHEVTPZoulbMbTV1VZIDQ1zjG8fvu8sv6IBYcR5+EsC8n3/6RkW8/iCJDzxE++VHzhoSQSoDvQ==</Q>
  <DP>zr/rcn+umd0Aisnu/Ik48smxz39TdIfaAwkBPsoL1Re+6V2WyLG1/fG4SmmUpsuMRRdt+SWdmbnzpr7peo++hQ==</DP>
  <DQ>MWi2W04sBEEGaKFi4QTuo2FAeTrdBvIn2t0M/lCCjYyDijtC5drpVKvhBk+xQZAFf9iIMsWzxQtTciBX3PI0SQ==</DQ>
  <InverseQ>wGEfA3LWM4NHgRnXDqwwOUs3OtqWK0tsJPPcFMci+Bcgy96JpFTCr7bubXHMu14bdopCWUann2d3UuwEpvP+</InverseQ>
  <D>mK3TRtMwRJb33OGnn9OeFumYfy92qxi3X6Hq1o6qDBW2qkd4bImfv+ni6AinyOVuaadt2Y+lq4dKGcCVJzoZvPm1VKxD2y7xKa8/vEbPRiRTt0qnPq9T7UJkpDsiXf/zOMfWdjc3uA1bPnQ65RWHSJ7zAE+Gd7xnyCE5MEyijLE=</D>
</RSAKeyValue>
View Code

         公鑰:code

   
<RSAKeyValue>
  <Modulus>pJlJIR0+G/vs7mhycs0Zd5DbWokMCsLX7Ih373+ljlteRmTm8IHj0Sl8zA26Qu/oAmqh9OFk806zW3TXl90RghSeQhzZBXFHBrTFN4U/o3wPhZBdFazh80bbskrmQ/jmz70qUm3HmGzsb3toxzN6Ehakdo7qP2Kc6aOVTyXrYpk=</Modulus>
  <Exponent>AQAB</Exponent>
</RSAKeyValue>
View Code

轉換實現代碼(c#)orm

       格式轉換要用到一個開源加密庫Bouncy Castle Crypto APIs,官網地址: http://www.bouncycastle.org/csharp/

        具體代碼以下:

   
 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  
11 /// <summary>
12 /// RSA密鑰格式轉換
13 /// </summary>
14 public class RSAKeyConvert
15 {
16     /// <summary>
17     /// RSA私鑰格式轉換,java->.net
18     /// </summary>
19     /// <param name="privateKey">java生成的RSA私鑰</param>
20     /// <returns></returns>
21     public static string RSAPrivateKeyJava2DotNet(string privateKey)
22     {
23         RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));
24  
25         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>",
26             Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()),
27             Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()),
28             Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()),
29             Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()),
30             Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()),
31             Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()),
32             Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()),
33             Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned()));
34     }
35  
36     /// <summary>
37     /// RSA私鑰格式轉換,.net->java
38     /// </summary>
39     /// <param name="privateKey">.net生成的私鑰</param>
40     /// <returns></returns>
41     public static string RSAPrivateKeyDotNet2Java(string privateKey)
42     {
43         XmlDocument doc = new XmlDocument();
44         doc.LoadXml(privateKey);
45         BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
46         BigInteger exp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
47         BigInteger d = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText));
48         BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText));
49         BigInteger q = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText));
50         BigInteger dp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText));
51         BigInteger dq = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText));
52         BigInteger qinv = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("InverseQ")[0].InnerText));
53  
54         RsaPrivateCrtKeyParameters privateKeyParam = new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv);
55  
56         PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam);
57         byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();
58         return Convert.ToBase64String(serializedPrivateBytes);
59     }
60  
61     /// <summary>
62     /// RSA公鑰格式轉換,java->.net
63     /// </summary>
64     /// <param name="publicKey">java生成的公鑰</param>
65     /// <returns></returns>
66     public static string RSAPublicKeyJava2DotNet(string publicKey)
67     {
68         RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));
69         return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>",
70             Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()),
71             Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned()));
72     }
73  
74     /// <summary>
75     /// RSA公鑰格式轉換,.net->java
76     /// </summary>
77     /// <param name="publicKey">.net生成的公鑰</param>
78     /// <returns></returns>
79     public static string RSAPublicKeyDotNet2Java(string publicKey)
80     {
81         XmlDocument doc = new XmlDocument();
82         doc.LoadXml(publicKey);
83         BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
84         BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
85         RsaKeyParameters pub = new RsaKeyParameters(false, m, p);
86  
87         SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub);
88         byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
89         return Convert.ToBase64String(serializedPublicBytes);
90     }
91 }
View Code

 

        因爲我只須要加密,我只須要使用C#將Java格式的公鑰轉換成.NET的格式的,而後進行加密,加密代碼以下:

   
 1 using System;
 2 using System.IO;
 3 using System.Security.Cryptography;
 4 using System.Text;
 5 using Org.BouncyCastle.Crypto.Parameters;
 6 using Org.BouncyCastle.Security;
 7 
 8 
 9 public class EncodeMessage
10  {
11         public static string GetRsaEncode(string publicKeyBase64Str, string text)
12         {
13             var publicKey = RsaPublicKeyJavaToDotNet(publicKeyBase64Str);
14             RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
15             rsa.FromXmlString(publicKey);
16             var cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(text), false);
17             return Convert.ToBase64String(cipherbytes);
18         }
19 }
View Code
相關文章
相關標籤/搜索