C#和JAVA的RSA金鑰、公鑰轉換

weixin_33686714發表於2018-03-19

C#的祕鑰跟JAVA的金鑰區別

 
RSA對於程式本身是沒有區別的,其格式都是相同的。對於不同的程式來說,儲存使用的語法(包裝的類)會有所不同。
RSA語法和語法標準有很多,大的型別大概分為ASN.1、PKCS、X.509。

RSA語法介紹

ASN.1、PKCS是最初的,也是最主要的RSA公鑰和私鑰的語法標準,被RSA Lab所維護。
ASN.1、PKCS#1都定義了公鑰和私鑰的型別——序列化的數字。為了下一個層次的抽象(適當的包裝),現在一般使用的組合是:PKCS#8的私鑰,X.509的公鑰 。
PKCS語法主要用於私鑰,其內部標準目前有10種。目前JAVA普遍使用的是PKCS#8,用作私鑰格式。
X.509語法主要用於公鑰,廣泛使用於web瀏覽器和SLL。 
3種語法標準的公私鑰可以實現相互轉化,其核心為ASN1語法中的整數值(modulus,PublicExponent,privateExponent ),其餘的數值都可以經過計算後得出。
 
.NET使用的是標準的RSA格式,然後將其中的數字base64編碼後,生成XML進行儲存。
java中使用的是PKCS#8,、X.509的公私鑰語法,儲存的都是相應的JAVA類自動生成的base64字串。
由於儲存格式的區別,在相互轉換、讀取的時候,需要理解RSA相關的知識,才能正確使用類來轉換。
 

金鑰格式

 
java金鑰:
[java] view plain copy
 
  1. 私鑰:  
  2. MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKSZSSEdPhv77O5ocnLNGXeQ21qJDArC1+yId+9/pY5bXkZk5vCB49EpfMwNukLv6AJqofThZPNOs1t015fdEYIUnkIc2QVxRwa0xTeFP  
  3. 6N8D4WQXRWs4fNG27JK5kP45s+9KlJtx5hs7G97aMczehIWpHaO6j9inOmjlU8l62KZAgMBAAECgYEAmK3TRtMwRJb33OGnn9OeFumYfy92qxi3X6Hq1o6qDBW2qkd4bImfv+ni6AinyOVuaadt2Y+lq4  
  4. dKGcCVJzoZvPm1VKxD2y7xKa8/vEbPRiRTt0qnPq9T7UJkpDsiXf/zOMfWdjc3uA1bPnQ65RWHSJ7zAE+Gd7xnyCE5MEyijLECQQDVYqQWDqOVLZ5lJUuIfUIrhv26GvuoTX8v60+opCz4/Mdfh6JlefI  
  5. CVD6SAaYvufXBHVFY26JicNlR62ZOiBoNAkEAxXhsuEnNJNQcQHEVTPZoulbMbTV1VZIDQ1zjG8fvu8sv6IBYcR5+EsC8n3/6RkW8/iCJDzxE++VHzhoSQSoDvQJBAM6/63J/rpndAIrJ7vyJOPLJsc9/U  
  6. 3SH2gMJAT7KC9UXvuldlsixtf3xuEpplKbLjEUXbfklnZm586a+6XqPvoUCQDFotltOLARBBmihYuEE7qNhQHk63QbyJ9rdDP5Qgo2Mg4o7QuXa6VSr4QZPsUGQBX/YiDLFs8ULU3IgV9zyNEkCQADAYR8  
  7. DctYzg0eBGdcOrDA5Szc62pYrS2wk89wUxyL4FyDL3omkVMKvtu5tccy7Xht2ikJZRqefZ3dS7ASm8/4=    
  8. 公鑰:  
  9. MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCkmUkhHT4b++zuaHJyzRl3kNtaiQwKwtfsiHfvf6WOW15GZObwgePRKXzMDbpC7+gCaqH04WTzTrNbdNeX3RGCFJ5CHNkFcUcGtMU3hT+jfA+FkF0VrO  
  10. HzRtuySuZD+ObPvSpSbceYbOxve2jHM3oSFqR2juo/Ypzpo5VPJetimQIDAQAB   

c#金鑰:
[csharp] view plain copy
 
  1. 私鑰:  
  2. <RSAKeyValue>    
  3. <Modulus>pJlJIR0+G/vs7mhycs0Zd5DbWokMCsLX7Ih373+ljlteRmTm8IHj0Sl8zA26Qu/oAmqh9OFk806zW3TXl90RghSeQhzZBXFHBrTFN4U/o3wPhZBdFazh80bbskrmQ/jmz70qUm3HmGzsb3tox  
  4. zN6Ehakdo7qP2Kc6aOVTyXrYpk=</Modulus>    
  5.   <Exponent>AQAB</Exponent>    
  6.   <P>1WKkFg6jlS2eZSVLiH1CK4b9uhr7qE1/L+tPqKQs+PzHX4eiZXnyAlQ+kgGmL7n1wR1RWNuiYnDZUetmTogaDQ==</P>    
  7.   <Q>xXhsuEnNJNQcQHEVTPZoulbMbTV1VZIDQ1zjG8fvu8sv6IBYcR5+EsC8n3/6RkW8/iCJDzxE++VHzhoSQSoDvQ==</Q>    
  8.   <DP>zr/rcn+umd0Aisnu/Ik48smxz39TdIfaAwkBPsoL1Re+6V2WyLG1/fG4SmmUpsuMRRdt+SWdmbnzpr7peo++hQ==</DP>    
  9.   <DQ>MWi2W04sBEEGaKFi4QTuo2FAeTrdBvIn2t0M/lCCjYyDijtC5drpVKvhBk+xQZAFf9iIMsWzxQtTciBX3PI0SQ==</DQ>    
  10.   <InverseQ>wGEfA3LWM4NHgRnXDqwwOUs3OtqWK0tsJPPcFMci+Bcgy96JpFTCr7bubXHMu14bdopCWUann2d3UuwEpvP+</InverseQ>    
  11.   <D>mK3TRtMwRJb33OGnn9OeFumYfy92qxi3X6Hq1o6qDBW2qkd4bImfv+ni6AinyOVuaadt2Y+lq4dKGcCVJzoZvPm1VKxD2y7xKa8/vEbPRiRTt0qnPq9T7UJkpDsiXf/zOMfWdjc3uA1bPnQ65RWHS  
  12. J7zAE+Gd7xnyCE5MEyijLE=</D>    
  13. </RSAKeyValue>    
  14.   
  15. 公鑰:  
  16. <RSAKeyValue>    
  17. <Modulus>pJlJIR0+G/vs7mhycs0Zd5DbWokMCsLX7Ih373+ljlteRmTm8IHj0Sl8zA26Qu/oAmqh9OFk806zW3TXl90RghSeQhzZBXFHBrTFN4U/o3wPhZBdFazh80bbskrmQ/jmz70qUm3HmGzsb3tox  
  18. zN6Ehakdo7qP2Kc6aOVTyXrYpk=</Modulus>    
  19.   <Exponent>AQAB</Exponent>    
  20. </RSAKeyValue>    


C#轉JAVA(C#程式碼)

C#中的公私鑰使用XML字串進行儲存,讀取時直接讀入字串即可。
由於C#使用的是標準的RSA格式,因此JAVA的RSAPublicKeySpec、RSAPrivateKeySpec配置類的核心引數(modulus,PublicExponent,privateExponent )都可以從對應XML中的節點值(Modulus-modulus 、Exponent-PublicExponent 、D-privateExponent )base64解碼後獲取。然後將其傳入JAVA配置類中,然後根據配置類生成相應的RSA公私鑰。

手動轉換

[csharp] view plain copy
 
  1. void Convert()  
  2. {  
  3.        //公鑰  
  4.         byte[] m = Base64.decodeBase64("mX/9zl8rflH5pLaP5P1Qd/9wXwNBSx7OpLlYDnGr7wD0njiDfPSUkgf9oF5NcvZwl24qdJ1SLmrgUtnr+yeXBNZNKaan1xXKISHdlHvbW5G8nJCJW6CuaHMkVw3Y7kwaIIlUdv09vxfjj0AoabttjbtF1kqETzbQ6fK3EN6sY5U=");  
  5.         byte[] e = Base64.decodeBase64("AQAB");  
  6.         BigInteger b1 = new BigInteger(1, m);  
  7.         BigInteger b2 = new BigInteger(1, e);  
  8.         //私鑰  
  9.         byte[] m1 = Base64.decodeBase64("3RgqP5YOYUXft8YOlDphyaCoof27MSfTD2eVCFVXB5hatrls1fSUcmUuWuGV970sS6KQZZtyWHQ5970sCzKFlq82He8Uoe0JM3axBvd6PbSGjulUJr62qNW5hgkIEfxSRYl8AQsbbusFtks4obfepsfE02cLmmZepnZAdIOWifE=");  
  10.         byte[] e1 = Base64.decodeBase64("QcSZdLbHakolxX4GAjPnuNmwsBdRIsss7o0qeQMh02GPwoEgDfkmW20bv+8Q9FPypEEkYQU/m25ffAFq453QvLegYYi8OvWN+dvgchQRdeb22d+s6xYGGN9DRcPFRE48INde8FBHf/lzVgToV75h1H7g+jB4hLmLeuIuHsB43/0=");  
  11.         BigInteger b11 = new BigInteger(1, m1);  
  12.         BigInteger b21 = new BigInteger(1, e1);  
  13.         //公鑰  
  14.         KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
  15.         RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);  
  16.         RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);  
  17.         //私鑰  
  18.         RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(b11, b21);  
  19.         RSAPrivateKey priKey = (RSAPrivateKey) keyFactory.generatePrivate(priKeySpec);  
  20. }  


BouncyCastle Crypto轉換

格式轉換要用到一個開源加密庫Bouncy Castle Crypto APIs,

官網地址:http://www.bouncycastle.org/csharp/
具體實現程式碼如下:

 

[csharp] view plain copy
 
  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. }    

JAVA轉C#(java程式碼)

JAVA中的公私鑰使用base64進行儲存,解碼成位元組陣列後,首先需要生成相應的配置物件(PKCS#8,、X.509 ),根據配置物件生成RSA公私鑰。

私鑰
C#使用的是標準的RSA格式,PKCS#1語法中包含了標準RSA格式私鑰中的所有整數值。配置物件需要生成PKCS#1語法的RSA物件(RSAPrivateCrtKey),獲取物件屬性,自行構造私鑰XML。
就算不會JAVA的新手都可以轉換的,只需要把以下的程式碼新增進eclipse中就可以了,具體的怎麼建java工程就自己去查一下。
把一對金鑰轉成C#中格式的金鑰在JAVA中的轉換程式碼如下:

 

 

[java] view plain copy
 
  1. package com;    
  2.     
  3. import java.security.KeyFactory;    
  4. import java.security.PublicKey;    
  5. import java.security.interfaces.RSAPrivateCrtKey;    
  6. import java.security.interfaces.RSAPublicKey;    
  7. import java.security.spec.PKCS8EncodedKeySpec;    
  8. import java.security.spec.X509EncodedKeySpec;    
  9. import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;    
  10.      
  11. public class test {    
  12.     
  13.     public static void main(String[] args) {    
  14.             
  15.         String tes = "MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBAL8z2QlXCL6w7rvY0Gbl8ARtQSXY+pEW5hlUHlmspqHt4k8/SkoF796gDqk4yyOcoWhkZWLPPugK35Mn7V+m5Jyfu8C0gVKOfWOA8A0T4hxV2ThAoMUq7QtB2K6s9AoumrxDfAkMBbsXEHYwfD/hxr/3DQ3lUvSFB6BnhiHEOyzpAgMBAAECgYEAol/9qRjorEjF9XEjSr9rHddKxEGIST8RGeF+BNnCiTHkRziQdlykYIO876jzmsKhsG3STB+EZLsXM3ls9RZefcsPF5mLOCSOCow3DikfCtAy4hntsU9JwpuYE0V4A+Sgfd24fatqbu+JxE2nvpSbAPczDOgBFPNfYBkhMiuZ/iECQQDzUeq7lFcIE4uWhRGveVFjNAGuSsW+q9GOwO7tS5YwuAIQ2M+XgYGRFo8xMC6V/9SfqJtmSU1zk72pMlYufIqHAkEAySqkcKbWuobq5I9KSQISq2qCuGKtj/iUFho4PCD1YxhnQ7gcHA4OpS1dRFjtXJYQPTX9be+mmypsCFIyofE5DwJBAPGZ20wahTh9v9Lbmq3z9n5ce3bGxAcJsHDg3d09eooxi8uSnL5BV5frII+k2f0TI9rMnlE4Y/FpN5+zXaOXAi0CQQCs3Aqfjo23jJWtPv/LSo+2YnjfblPMAgNmFrO532xc8axSgZMN/HpTL28UewHD7GMZ5hnWbPcSIFrir5c4luq7AkEAi90WdnZVPxtSTqkkLYbnh4Ro2WhdwRjkfyBxBZZx8hfaM6MfLPi3A0rw9DPOSB4M/BMchtEh3bXuI7bue2tG+A==";    
  16.         byte[] temp = b64decode(tes);    
  17.         String ver = getRSAPrivateKeyAsNetFormat(temp);// 轉換私鑰    
  18.             
  19.         String tes1 = "MIGfMA0GCSqGSIb4DQEBAQUAA4GNADCBiQKBgQC/M9kJVwi+sO672NBm5fAEbUEl2PqRFuYZVB5ZrKah7eJPP0pKBe/eoA6pOMsjnKFoZGVizz7oCt+TJ+1fpuScn7vAtIFSjn1jgPANE+IcVdk4QKDFKu0LQdiurPQKLpq8Q3wJDAW7FxB2MHw/4ca/9w0N5VL0hQegZ4YhxDss6QIDAQAB";    
  20.         byte[] temp1 = b64decode(tes1);    
  21.         String ver1 = getRSAPublicKeyAsNetFormat(temp1);// 轉換公鑰    
  22.         System.out.println(ver);    
  23.         System.out.println(ver1);    
  24.     }    
  25.     
  26.     private static String getRSAPrivateKeyAsNetFormat(byte[] encodedPrivkey) {    
  27.         try {    
  28.             StringBuffer buff = new StringBuffer(1024);    
  29.     
  30.             PKCS8EncodedKeySpec pvkKeySpec = new PKCS8EncodedKeySpec(    
  31.                     encodedPrivkey);    
  32.             KeyFactory keyFactory = KeyFactory.getInstance("RSA");    
  33.             RSAPrivateCrtKey pvkKey = (RSAPrivateCrtKey) keyFactory    
  34.                     .generatePrivate(pvkKeySpec);    
  35.     
  36.             buff.append("<RSAKeyValue>");    
  37.             buff.append("<Modulus>"    
  38.                             + b64encode(removeMSZero(pvkKey.getModulus()    
  39.                                     .toByteArray())) + "</Modulus>");    
  40.     
  41.             buff.append("<Exponent>"    
  42.                     + b64encode(removeMSZero(pvkKey.getPublicExponent()    
  43.                             .toByteArray())) + "</Exponent>");    
  44.     
  45.             buff.append("<P>"    
  46.                     + b64encode(removeMSZero(pvkKey.getPrimeP().toByteArray()))    
  47.                     + "</P>");    
  48.     
  49.             buff.append("<Q>"    
  50.                     + b64encode(removeMSZero(pvkKey.getPrimeQ().toByteArray()))    
  51.                     + "</Q>");    
  52.     
  53.             buff.append("<DP>"    
  54.                     + b64encode(removeMSZero(pvkKey.getPrimeExponentP()    
  55.                             .toByteArray())) + "</DP>");    
  56.     
  57.             buff.append("<DQ>"    
  58.                     + b64encode(removeMSZero(pvkKey.getPrimeExponentQ()    
  59.                             .toByteArray())) + "</DQ>");    
  60.     
  61.             buff.append("<InverseQ>"    
  62.                     + b64encode(removeMSZero(pvkKey.getCrtCoefficient()    
  63.                             .toByteArray())) + "</InverseQ>");    
  64.     
  65.             buff.append("<D>"    
  66.                     + b64encode(removeMSZero(pvkKey.getPrivateExponent()    
  67.                             .toByteArray())) + "</D>");    
  68.             buff.append("</RSAKeyValue>");    
  69.     
  70.             return buff.toString().replaceAll("[ \t\n\r]", "");    
  71.         } catch (Exception e) {    
  72.             System.err.println(e);    
  73.             return null;    
  74.         }    
  75.     }    
  76.     
  77.     private static String getRSAPublicKeyAsNetFormat(byte[] encodedPrivkey) {    
  78.         try {    
  79.             StringBuffer buff = new StringBuffer(1024);    
  80.     
  81.             PKCS8EncodedKeySpec pvkKeySpec = new PKCS8EncodedKeySpec(    
  82.                     encodedPrivkey);    
  83.             KeyFactory keyFactory = KeyFactory.getInstance("RSA");    
  84.             RSAPublicKey pukKey = (RSAPublicKey) keyFactory    
  85.                     .generatePublic(new X509EncodedKeySpec(encodedPrivkey));    
  86.                  
  87.             buff.append("<RSAKeyValue>");    
  88.             buff.append("<Modulus>"    
  89.                             + b64encode(removeMSZero(pukKey.getModulus()    
  90.                                     .toByteArray())) + "</Modulus>");    
  91.             buff.append("<Exponent>"    
  92.                     + b64encode(removeMSZero(pukKey.getPublicExponent()    
  93.                             .toByteArray())) + "</Exponent>");    
  94.             buff.append("</RSAKeyValue>");    
  95.             return buff.toString().replaceAll("[ \t\n\r]", "");    
  96.         } catch (Exception e) {    
  97.             System.err.println(e);    
  98.             return null;    
  99.         }    
  100.     }    
  101.     
  102.     public static String encodePublicKeyToXml(PublicKey key) {    
  103.         if (!RSAPublicKey.class.isInstance(key)) {    
  104.             return null;    
  105.         }    
  106.         RSAPublicKey pubKey = (RSAPublicKey) key;    
  107.         StringBuilder sb = new StringBuilder();    
  108.     
  109.         sb.append("<RSAKeyValue>");    
  110.         sb.append("<Modulus>").append(    
  111.                 Base64.encode(pubKey.getModulus().toByteArray())).append(    
  112.                 "</Modulus>");    
  113.         sb.append("<Exponent>").append(    
  114.                 Base64.encode(pubKey.getPublicExponent().toByteArray()))    
  115.                 .append("</Exponent>");    
  116.         sb.append("</RSAKeyValue>");    
  117.         return sb.toString();    
  118.     }    
  119.     
  120.     private static byte[] removeMSZero(byte[] data) {    
  121.         byte[] data1;    
  122.         int len = data.length;    
  123.         if (data[0] == 0) {    
  124.             data1 = new byte[data.length - 1];    
  125.             System.arraycopy(data, 1, data1, 0, len - 1);    
  126.         } else    
  127.             data1 = data;    
  128.     
  129.         return data1;    
  130.     }    
  131.     
  132.     private static String b64encode(byte[] data) {    
  133.         String b64str = new String(Base64.encode(data));    
  134.         return b64str;    
  135.     }    
  136.     
  137.     private static byte[] b64decode(String data) {    
  138.         byte[] decodeData = Base64.decode(data);    
  139.         return decodeData;    
  140.     }    
  141. }    


 

相關文章