C#和JAVA的RSA密钥、公钥转换

时间:2022-01-25 10:23:44

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密钥:
  1. 私钥:
  2. MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKSZSSEdPhv77O5ocnLNGXeQ21qJDArC1+yId+9/pY5bXkZk5vCB49EpfMwNukLv6AJqofThZPNOs1t015fdEYIUnkIc2QVxRwa0xTeFP
  3. 6N8D4WQXRWs4fNG27JK5kP45s+9KlJtx5hs7G97aMczehIWpHaO6j9inOmjlU8l62KZAgMBAAECgYEAmK3TRtMwRJb33OGnn9OeFumYfy92qxi3X6Hq1o6qDBW2qkd4bImfv+ni6AinyOVuaadt2Y+lq4
  4. dKGcCVJzoZvPm1VKxD2y7xKa8/vEbPRiRTt0qnPq9T7UJkpDsiXf/zOMfWdjc3uA1bPnQ65RWHSJ7zAE+Gd7xnyCE5MEyijLECQQDVYqQWDqOVLZ5lJUuIfUIrhv26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8n3/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. <RSAKeyValue>
  16. <Modulus>pJlJIR0+G/vs7mhycs0Zd5DbWokMCsLX7Ih373+ljlteRmTm8IHj0Sl8zA26Qu/oAmqh9OFk806zW3TXl90RghSeQhzZBXFHBrTFN4U/o3wPhZBdFazh80bbskrmQ/jmz70qUm3HmGzsb3tox
  17. zN6Ehakdo7qP2Kc6aOVTyXrYpk=</Modulus>
  18. <Exponent>AQAB</Exponent>
  19. </RSAKeyValue>

C#转JAVA(C#代码)

C#中的公私钥使用XML字符串进行存储,读取时直接读入字符串即可。
由于C#使用的是标准的RSA格式,因此JAVA的RSAPublicKeySpec、RSAPrivateKeySpec配置类的核心参数(modulus,PublicExponent,privateExponent )都可以从对应XML中的节点值(Modulus-modulus 、Exponent-PublicExponent 、D-privateExponent )base64解码后获取。然后将其传入JAVA配置类中,然后根据配置类生成相应的RSA公私钥。

手动转换

  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/具体实现代码如下:

  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();
  75. doc.LoadXml(publicKey);
  76. BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
  77. BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
  78. RsaKeyParameters pub = new RsaKeyParameters(false, m, p);
  79. SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub);
  80. byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
  81. return Convert.ToBase64String(serializedPublicBytes);
  82. }
  83. }

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中的转换代码如下:

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