当前位置:   article > 正文

将JAVA用RSA生成的加密字符串,传个接口API,实现解密(接口使用C#语言)_java rsa加密

java rsa加密

1.JAVA方法

  1. import org.apache.commons.codec.binary.Base64;
  2. import org.apache.tomcat.util.http.fileupload.IOUtils;
  3. import javax.crypto.Cipher;
  4. import java.io.ByteArrayOutputStream;
  5. import java.security.*;
  6. import java.security.interfaces.RSAPrivateKey;
  7. import java.security.interfaces.RSAPublicKey;
  8. import java.security.spec.InvalidKeySpecException;
  9. import java.security.spec.PKCS8EncodedKeySpec;
  10. import java.security.spec.X509EncodedKeySpec;
  11. import java.util.HashMap;
  12. import java.util.Map;
  13. public class RSAUtils {
  14. public static final String CHARSET = "UTF-8";
  15. public static final String RSA_ALGORITHM = "RSA"; // ALGORITHM ['ælgərɪð(ə)m] 算法的意思
  16. public static Map<String, String> createKeys(int keySize) {
  17. // 为RSA算法创建一个KeyPairGenerator对象
  18. KeyPairGenerator kpg;
  19. try {
  20. kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
  21. } catch (NoSuchAlgorithmException e) {
  22. throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]");
  23. }
  24. // 初始化KeyPairGenerator对象,密钥长度
  25. kpg.initialize(keySize);
  26. // 生成密匙对
  27. KeyPair keyPair = kpg.generateKeyPair();
  28. // 得到公钥
  29. Key publicKey = keyPair.getPublic();
  30. String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded());
  31. // 得到私钥
  32. Key privateKey = keyPair.getPrivate();
  33. String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded());
  34. // map装载公钥和私钥
  35. Map<String, String> keyPairMap = new HashMap<String, String>();
  36. keyPairMap.put("publicKey", publicKeyStr);
  37. keyPairMap.put("privateKey", privateKeyStr);
  38. // 返回map
  39. return keyPairMap;
  40. }
  41. /**
  42. * 得到公钥
  43. * @param publicKey 密钥字符串(经过base64编码)
  44. * @throws Exception
  45. */
  46. public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeySpecException {
  47. // 通过X509编码的Key指令获得公钥对象
  48. KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
  49. X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
  50. RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
  51. return key;
  52. }
  53. /**
  54. * 得到私钥
  55. * @param privateKey 密钥字符串(经过base64编码)
  56. * @throws Exception
  57. */
  58. public static RSAPrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
  59. // 通过PKCS#8编码的Key指令获得私钥对象
  60. KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
  61. PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
  62. RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
  63. return key;
  64. }
  65. /**
  66. * 公钥加密
  67. * @param data
  68. * @param publicKey
  69. * @return
  70. */
  71. public static String publicEncrypt(String data, RSAPublicKey publicKey) throws Exception {
  72. Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
  73. cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  74. return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength()));
  75. }
  76. public static String publicEncrypt(String data, String publicKey) throws Exception {
  77. try {
  78. return publicEncrypt(data, getPublicKey(publicKey));
  79. }catch (Exception e){
  80. throw new Exception("加密字符串[" + data + "]时遇到异常");
  81. }
  82. }
  83. /**
  84. * 私钥解密
  85. * @param data
  86. * @param privateKey
  87. * @return
  88. */
  89. public static String privateDecrypt(String data, RSAPrivateKey privateKey) throws Exception{
  90. Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
  91. cipher.init(Cipher.DECRYPT_MODE, privateKey);
  92. return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), privateKey.getModulus().bitLength()), CHARSET);
  93. }
  94. public static String privateDecrypt(String data, String privateKey) throws Exception {
  95. try {
  96. return privateDecrypt(data, getPrivateKey(privateKey));
  97. }catch (Exception e){
  98. e.printStackTrace();
  99. throw new Exception("解密字符串[" + data + "]时遇到异常");
  100. }
  101. }
  102. /**
  103. * 私钥加密
  104. * @param data
  105. * @param privateKey
  106. * @return
  107. */
  108. public static String privateEncrypt(String data, RSAPrivateKey privateKey) throws Exception {
  109. Cipher cipher = null;
  110. try {
  111. cipher = Cipher.getInstance(RSA_ALGORITHM);
  112. //每个Cipher初始化方法使用一个模式参数opmod,并用此模式初始化Cipher对象。此外还有其他参数,包括密钥key、包含密钥的证书certificate、算法参数params和随机源random。
  113. cipher.init(Cipher.ENCRYPT_MODE, privateKey);
  114. return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), privateKey.getModulus().bitLength()));
  115. } catch (Exception e) {
  116. throw new Exception("加密字符串[" + data + "]时遇到异常");
  117. }
  118. }
  119. /**
  120. * 公钥解密
  121. * 公钥解密
  122. * @param data
  123. * @param publicKey
  124. * @return
  125. */
  126. public static String publicDecrypt(String data, RSAPublicKey publicKey) throws Exception {
  127. try {
  128. Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
  129. cipher.init(Cipher.DECRYPT_MODE, publicKey);
  130. return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), publicKey.getModulus().bitLength()), CHARSET);
  131. } catch (Exception e) {
  132. throw new Exception("解密字符串[" + data + "]时遇到异常");
  133. }
  134. }
  135. //rsa切割解码 , ENCRYPT_MODE,加密数据 ,DECRYPT_MODE,解密数据
  136. private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize) throws Exception {
  137. int maxBlock = 0; //最大块
  138. if (opmode == Cipher.DECRYPT_MODE) {
  139. maxBlock = keySize / 8;
  140. } else {
  141. maxBlock = keySize / 8 - 11;
  142. }
  143. ByteArrayOutputStream out = new ByteArrayOutputStream();
  144. int offSet = 0;
  145. byte[] buff;
  146. int i = 0;
  147. try {
  148. while (datas.length > offSet) {
  149. if (datas.length - offSet > maxBlock) {
  150. //可以调用以下的doFinal()方法完成加密或解密数据:
  151. buff = cipher.doFinal(datas, offSet, maxBlock);
  152. } else {
  153. buff = cipher.doFinal(datas, offSet, datas.length - offSet);
  154. }
  155. out.write(buff, 0, buff.length);
  156. i++;
  157. offSet = i * maxBlock;
  158. }
  159. } catch (Exception e) {
  160. throw new Exception("加解密阀值为[" + maxBlock + "]的数据时发生异常");
  161. }
  162. byte[] resultDatas = out.toByteArray();
  163. IOUtils.closeQuietly(out);
  164. return resultDatas;
  165. }
  166. public static void main(String[] args) throws Exception {
  167. // 私钥
  168. String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAI4GE5mdRce9tQFK3fWchAyjiBIhXqKRA5E_pO4zcSSuAL0LlgZgue6NgP51H77crL2JAloG3TFbsuULwdqsI0jUnAjZmunS6UhSx21RC2XocwUWLNq6os5woHz_RAJxAHdwsKyKt87TO1YFfJV-Ym3VaAMaIkMW4BEpfan_QsN1AgMBAAECgYAaBbMBqndmqbPIkNcqcYsgZbZA3CxizP9CVc76diJ8_gTUnpLWiFKJCxRfi0ZNylE8SSZNKITOzmZw4T6bun6cScXtgKTzzTiijOVZJUp_1iAzu9hIba-jmJ_1s8KCuxve1J3PGMozDcOcFGma9yORrDReBDy5_44tFCj4_-VU4QJBAPFSXO2ass0yxEnjA4hrqZLjAYvcU-U5nv1CbxcRmtnhA3KPruflD7LqgicUlkTRB1WXqGiZ4I3k1Q9DUKTVrUMCQQCWqYmr0hIi9BcaocTNfgcF6dsIcCiPpz1Cg3DrQyapD4ziDyyRZjFlwmBnaNztiFgB0SjhDv0ipVkL8Wm1MiTnAkEAjOo4Y3KrKBGV90M9o-KiYah3FbFxt---vEqXzhO0pbe0KKhoTPdABIzVtXZbDRI2Qy_M4k_AhXrzQvde1vIDOwJAaFbzhC4Q52oaEhSUYif0nzDMwzRBsvMEZur2qcewn4aob-pIWE3oyetqrlMeJda19FQxNmQWBQdz-uRu69DVYwJAOy3rbwIXJTFWh1d6TNIqZHClO-w84dt7teYMuJ28dTty7VmGPB_g_rKetROePYbBLzuQe-xHqUKAGKw1oUHQ3A";
  169. // 公钥
  170. String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCOBhOZnUXHvbUBSt31nIQMo4gSIV6ikQORP6TuM3EkrgC9C5YGYLnujYD-dR--3Ky9iQJaBt0xW7LlC8HarCNI1JwI2Zrp0ulIUsdtUQtl6HMFFizauqLOcKB8_0QCcQB3cLCsirfO0ztWBXyVfmJt1WgDGiJDFuARKX2p_0LDdQIDAQAB";
  171. String data = "I am a good boy";
  172. System.out.println("加密前字符串:" + data);
  173. // 公钥加密 私钥解密
  174. String dataEnc = publicEncrypt(data, publicKey);
  175. System.out.println("加密后字符串: " + dataEnc);
  176. String res = privateDecrypt(dataEnc, privateKey);
  177. System.out.println("解密后字符串:" + res);
  178. }
  179. }

这里是JAVA生成秘钥的方法以及加密解密的方法

因为我要直接把JAVA生成的RSA加密字符串直接传给接口API接口,来实现使用公钥解密,所以同样的要使用到C#语言对应的RSA加密解密方法类(注:因为我这边只需要加密和解密,所以我没有在类里写生成密钥的方法,如若需要,可自行百度

  1. using Org.BouncyCastle.Crypto;
  2. using Org.BouncyCastle.Security;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Security.Cryptography;
  8. using System.Text;
  9. using System.Web;
  10. namespace ZHIHUI.WebSite.utils
  11. {
  12. public class RSACryption
  13. {
  14. /// <summary>
  15. /// RSA加密 将公钥导入到RSA对象中,准备加密
  16. /// </summary>
  17. /// <param name="publicKey">公钥</param>
  18. /// <param name="encryptstring">待加密的字符串</param>
  19. public static string RsaEncrypt(string publicKey, string encryptstring)
  20. {
  21. using (var rsaProvider = new RSACryptoServiceProvider())
  22. {
  23. var inputBytes = Encoding.UTF8.GetBytes(encryptstring);//有含义的字符串转化为字节流
  24. rsaProvider.FromXmlString(publicKey);//载入公钥
  25. int bufferSize = (rsaProvider.KeySize / 8) - 11;//单块最大长度
  26. var buffer = new byte[bufferSize];
  27. using (MemoryStream inputStream = new MemoryStream(inputBytes), outputStream = new MemoryStream())
  28. {
  29. while (true)
  30. { //分段加密
  31. int readSize = inputStream.Read(buffer, 0, bufferSize);
  32. if (readSize <= 0)
  33. {
  34. break;
  35. }
  36. var temp = new byte[readSize];
  37. Array.Copy(buffer, 0, temp, 0, readSize);
  38. var encryptedBytes = rsaProvider.Encrypt(temp, false);
  39. outputStream.Write(encryptedBytes, 0, encryptedBytes.Length);
  40. }
  41. return Convert.ToBase64String(outputStream.ToArray());//转化为字节流方便传输
  42. }
  43. }
  44. }
  45. /// <summary>
  46. /// RSA解密 载入私钥,解密数据
  47. /// </summary>
  48. /// <param name="privateKey">私钥</param>
  49. /// <param name="decryptstring">待解密的字符串</param>
  50. public static string RsaDecrypt(string privateKey, string decryptstring)
  51. {
  52. using (var rsaProvider = new RSACryptoServiceProvider())
  53. {
  54. rsaProvider.FromXmlString(privateKey); //载入私钥
  55. //去除字符串中的多余字符,并替换特殊字符,以便能够正确地进行 Base64 解码
  56. string dummyData = decryptstring.Trim().Replace("%", "").Replace(",", "").Replace(" ", "+");
  57. //特殊字符转换为标准的 Base64 字符,以便能够正确地进行解码操作
  58. string standardBase64String = dummyData.Replace('-', '+').Replace('_', '/');
  59. // 修正长度
  60. while (standardBase64String.Length % 4 != 0)
  61. {
  62. standardBase64String += "=";
  63. }
  64. var encryptedBytes = Convert.FromBase64String(standardBase64String); //将传入的字符串转化为字节流
  65. // var outputStream = new MemoryStream(encryptedBytes);
  66. var bufferSize = rsaProvider.KeySize / 8;
  67. var buffer = new byte[bufferSize];
  68. using (MemoryStream inputStream = new MemoryStream(encryptedBytes), outputStream = new MemoryStream())
  69. {
  70. while (true)
  71. {
  72. int readSize = inputStream.Read(buffer, 0, bufferSize);
  73. if (readSize <= 0)
  74. {
  75. break;
  76. }
  77. var temp = new byte[readSize];
  78. Array.Copy(buffer, 0, temp, 0, readSize);
  79. var decryptedBytes = rsaProvider.Decrypt(temp, false);
  80. outputStream.Write(decryptedBytes, 0, decryptedBytes.Length);
  81. }
  82. return Encoding.UTF8.GetString(outputStream.ToArray()); //转化为字符串
  83. }
  84. }
  85. }
  86. /// <summary>
  87. /// RSA私钥加密
  88. /// </summary>
  89. /// <param name="privateKey">私钥</param>
  90. /// <param name="encryptstring">待加密的字符串</param>
  91. public static string RsaPrivateEncrypt(string privateKey, string encryptstring)
  92. {
  93. var rsaProvider = new RSACryptoServiceProvider();
  94. rsaProvider.FromXmlString(privateKey);//载入私钥
  95. var inputBytes = Convert.FromBase64String(encryptstring);//有含义的字符串转化为字节流
  96. int bufferSize = (rsaProvider.KeySize / 8) - 11;//单块最大长度
  97. var buffer = new byte[bufferSize];
  98. using (MemoryStream inputStream = new MemoryStream(inputBytes), outputStream = new MemoryStream())
  99. {
  100. while (true)
  101. {
  102. //分段加密
  103. int readSize = inputStream.Read(buffer, 0, bufferSize);
  104. if (readSize <= 0)
  105. {
  106. break;
  107. }
  108. var temp = new byte[readSize];
  109. Array.Copy(buffer, 0, temp, 0, readSize);
  110. var encryptedBytes = RsaPrivateEncrypt(privateKey, temp);
  111. outputStream.Write(encryptedBytes, 0, encryptedBytes.Length);
  112. }
  113. return Convert.ToBase64String(outputStream.ToArray());//转化为字节流方便传输
  114. }
  115. }
  116. /// <summary>
  117. /// RSA公钥解密
  118. /// </summary>
  119. /// <param name="publicKey">公钥</param>
  120. /// <param name="decryptstring">待解密的字符串</param>
  121. public static string RsaPublicDecrypt(string publicKey, string decryptstring)
  122. {
  123. var rsaProvider = new RSACryptoServiceProvider();
  124. rsaProvider.FromXmlString(publicKey); //载入私钥
  125. var encryptedBytes = Convert.FromBase64String(decryptstring); //将传入的字符串转化为字节流
  126. var bufferSize = rsaProvider.KeySize / 8;
  127. var buffer = new byte[bufferSize];
  128. using (MemoryStream inputStream = new MemoryStream(encryptedBytes), outputStream = new MemoryStream())
  129. {
  130. while (true)
  131. {
  132. int readSize = inputStream.Read(buffer, 0, bufferSize);
  133. if (readSize <= 0)
  134. {
  135. break;
  136. }
  137. var temp = new byte[readSize];
  138. Array.Copy(buffer, 0, temp, 0, readSize);
  139. var decryptedBytes = decryptByPublicKey(publicKey, temp);
  140. outputStream.Write(decryptedBytes, 0, decryptedBytes.Length);
  141. }
  142. return Convert.ToBase64String(outputStream.ToArray());
  143. }
  144. }
  145. /// <summary>
  146. /// 私钥加密
  147. /// 这个方法只能加密 私钥长度/8 -11 个字符,分段加密的代码要自己处理了。
  148. /// </summary>
  149. /// <param name="privateKey">密钥</param>
  150. /// <param name="data">要加密的数据</param>
  151. /// <returns></returns>
  152. public static byte[] RsaPrivateEncrypt(string privateKey, byte[] data)
  153. {
  154. string xmlPrivateKey = privateKey;
  155. //加载私钥
  156. RSACryptoServiceProvider privateRsa = new RSACryptoServiceProvider();
  157. privateRsa.FromXmlString(xmlPrivateKey);
  158. //转换密钥
  159. AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetKeyPair(privateRsa);
  160. //IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");// 参数与Java中加密解密的参数一致
  161. IBufferedCipher c = CipherUtilities.GetCipher("RSA");
  162. c.Init(true, keyPair.Private); //第一个参数为true表示加密,为false表示解密;第二个参数表示密钥
  163. byte[] DataToEncrypt = data;
  164. byte[] outBytes = c.DoFinal(DataToEncrypt);//加密
  165. return outBytes;
  166. }
  167. /// <summary>
  168. /// 用公钥解密
  169. /// 这个方法只能加密 私钥长度/8 -11 个字符,分段加密的代码要自己处理了。
  170. /// </summary>
  171. /// <param name="data"></param>
  172. /// <param name="key"></param>
  173. /// <returns></returns>
  174. public static byte[] decryptByPublicKey(string publicKey, byte[] data)
  175. {
  176. string xmlPublicKey = publicKey;
  177. RSACryptoServiceProvider publicRsa = new RSACryptoServiceProvider();
  178. publicRsa.FromXmlString(xmlPublicKey);
  179. AsymmetricKeyParameter keyPair = DotNetUtilities.GetRsaPublicKey(publicRsa);
  180. //转换密钥
  181. // AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetRsaKeyPair(publicRsa);
  182. //IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");// 参数与Java中加密解密的参数一致
  183. IBufferedCipher c = CipherUtilities.GetCipher("RSA");
  184. c.Init(false, keyPair); //第一个参数为true表示加密,为false表示解密;第二个参数表示密钥
  185. byte[] DataToEncrypt = data;
  186. byte[] outBytes = c.DoFinal(DataToEncrypt);//解密
  187. return outBytes;
  188. }
  189. }
  190. }

下面是我的接口调用方式:

  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Configuration;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Http;
  9. using System.Security.Cryptography;
  10. using System.Text;
  11. using System.Web.Http;
  12. using ZHIHUI.WebSite.utils;
  13. namespace ZHIHUI.WebAPI.Controllers
  14. {
  15. public class UserMessageController : ApiController
  16. {
  17. [HttpPost]
  18. public string GetUserMessage(HttpRequestMessage request)
  19. {
  20. DateTime time = DateTime.Now;
  21. try
  22. {
  23. var stream = request.Content.ReadAsStreamAsync().Result;
  24. var reader = new StreamReader(stream);
  25. string RSAString = reader.ReadToEnd();
  26. string privteKey = "您的私钥";
  27. //获取RSA加密后的字符串
  28. //string RSAString = Convert.ToString(obj.RSAString);
  29. //将获取到的私钥由java格式转换为net格式
  30. string privtkey = RSAUtil.RSAPrivateKeyJavaToDotNet(privteKey);
  31. //解密后的字符串
  32. string Data = RSACryption.RsaDecrypt(privtkey, RSAString );
  33. try
  34. {
  35. UserResult res = JsonConvert.DeserializeObject<UserResult>(Data);
  36. }
  37. catch (Exception)
  38. {
  39. throw;
  40. }
  41. return JsonConvert.SerializeObject(new { code = 200});
  42. }
  43. catch (Exception e)
  44. {
  45. return JsonConvert.SerializeObject(new { code = -1, msg = "Error", error = e.Message });
  46. }
  47. }
  48. }
  49. }

在解析秘钥时,需要将秘钥转换成C#所需要的格式

  1. using Org.BouncyCastle.Asn1.Pkcs;
  2. using Org.BouncyCastle.Asn1.X509;
  3. using Org.BouncyCastle.Crypto;
  4. using Org.BouncyCastle.Crypto.Parameters;
  5. using Org.BouncyCastle.Math;
  6. using Org.BouncyCastle.Pkcs;
  7. using Org.BouncyCastle.Security;
  8. using Org.BouncyCastle.X509;
  9. using System;
  10. using System.IO;
  11. using System.Security.Cryptography;
  12. using System.Text;
  13. using System.Xml;
  14. /// <summary>
  15. /// C# Rsa加密(私钥加密、公钥解密、密钥格式转换、支持超大长度分段加密)
  16. /// </summary>
  17. public class RSAUtil
  18. {
  19. /// <summary>
  20. /// 生成公钥与私钥方法
  21. /// </summary>
  22. /// <returns></returns>
  23. public static string[] CreateKey(KeyType keyType, KeySize keySize)
  24. {
  25. try
  26. {
  27. string[] sKeys = new string[2];
  28. RSACryptoServiceProvider rsa = new RSACryptoServiceProvider((int)keySize);
  29. switch (keyType)
  30. {
  31. case KeyType.XML:
  32. {
  33. //私钥
  34. sKeys[0] = rsa.ToXmlString(true);
  35. //公钥
  36. sKeys[1] = rsa.ToXmlString(false);
  37. }
  38. break;
  39. case KeyType.PKS8:
  40. {
  41. sKeys[0] = rsa.ToXmlString(true);
  42. //公钥
  43. sKeys[1] = rsa.ToXmlString(false);
  44. //JAVA私钥
  45. sKeys[0] = RSAPrivateKeyDotNet2Java(sKeys[0]);
  46. //JAVA公钥
  47. sKeys[1] = RSAPublicKeyDotNet2Java(sKeys[1]);
  48. }
  49. break;
  50. default:
  51. break;
  52. }
  53. return sKeys;
  54. }
  55. catch (Exception)
  56. {
  57. return null;
  58. }
  59. }
  60. /// <summary>
  61. /// 密钥类型
  62. /// </summary>
  63. public enum KeyType
  64. {
  65. /// <summary>
  66. /// xml类型
  67. /// </summary>
  68. XML,
  69. /// <summary>
  70. /// pks8类型
  71. /// </summary>
  72. PKS8
  73. }
  74. /// <summary>
  75. /// 密钥尺寸(一般都是1024位的)
  76. /// </summary>
  77. public enum KeySize
  78. {
  79. SMALL = 1024,
  80. BIG = 2048
  81. }
  82. /// <summary>
  83. /// RSA私钥格式转换,.net->java
  84. /// </summary>
  85. /// <param name="privateKey">.net生成的私钥</param>
  86. /// <returns></returns>
  87. public static string RSAPrivateKeyDotNet2Java(string privateKey)
  88. {
  89. XmlDocument doc = new XmlDocument();
  90. doc.LoadXml(privateKey);
  91. BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
  92. BigInteger exp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
  93. BigInteger d = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText));
  94. BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText));
  95. BigInteger q = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText));
  96. BigInteger dp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText));
  97. BigInteger dq = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText));
  98. BigInteger qinv = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("InverseQ")[0].InnerText));
  99. RsaPrivateCrtKeyParameters privateKeyParam = new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv);
  100. PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam);
  101. byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();
  102. return Convert.ToBase64String(serializedPrivateBytes);
  103. }
  104. /// <summary>
  105. /// RSA公钥格式转换,.net->java
  106. /// </summary>
  107. /// <param name="publicKey">.net生成的公钥</param>
  108. /// <returns></returns>
  109. public static string RSAPublicKeyDotNet2Java(string publicKey)
  110. {
  111. XmlDocument doc = new XmlDocument();
  112. doc.LoadXml(publicKey);
  113. BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
  114. BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
  115. RsaKeyParameters pub = new RsaKeyParameters(false, m, p);
  116. SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub);
  117. byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
  118. return Convert.ToBase64String(serializedPublicBytes);
  119. }
  120. /// <summary>
  121. /// RSA私钥格式转换,java->.net
  122. /// </summary>
  123. /// <param name="privateKey">java生成的RSA私钥</param>
  124. /// <returns></returns>
  125. public static string RSAPrivateKeyJavaToDotNet(string privateKey)
  126. {
  127. RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));
  128. 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>",
  129. Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()),
  130. Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()),
  131. Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()),
  132. Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()),
  133. Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()),
  134. Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()),
  135. Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()),
  136. Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned()));
  137. }
  138. /// <summary>
  139. /// RSA公钥格式转换,java->.net
  140. /// </summary>
  141. /// <param name="publicKey">java生成的公钥</param>
  142. /// <returns></returns>
  143. public static string RSAPublicKeyJavaToDotNet(string publicKey)
  144. {
  145. RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));
  146. return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>",
  147. Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()),
  148. Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned()));
  149. }
  150. /// <summary>
  151. /// 最大加密长度
  152. /// </summary>
  153. private const int MAX_ENCRYPT_BLOCK = 245;
  154. /// <summary>
  155. /// 最大解密长度
  156. /// </summary>
  157. private const int MAX_DECRYPT_BLOCK = 256;
  158. /// <summary>
  159. /// 用私钥给数据进行RSA加密
  160. /// </summary>
  161. /// <param name="xmlPrivateKey"></param>
  162. /// <param name="strEncryptString"></param>
  163. /// <returns></returns>
  164. public static string PrivateKeyEncrypt(string xmlPrivateKey, string strEncryptString)
  165. {
  166. //加载私钥
  167. RSACryptoServiceProvider privateRsa = new RSACryptoServiceProvider();
  168. privateRsa.FromXmlString(xmlPrivateKey);
  169. //转换密钥
  170. AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetKeyPair(privateRsa);
  171. IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding"); //使用RSA/ECB/PKCS1Padding格式
  172. c.Init(true, keyPair.Private);//第一个参数为true表示加密,为false表示解密;第二个参数表示密钥
  173. byte[] dataToEncrypt = Encoding.UTF8.GetBytes(strEncryptString);//获取字节
  174. byte[] cache;
  175. int time = 0;//次数
  176. int inputLen = dataToEncrypt.Length;
  177. int offSet = 0;
  178. MemoryStream outStream = new MemoryStream();
  179. while (inputLen - offSet > 0)
  180. {
  181. if (inputLen - offSet > MAX_ENCRYPT_BLOCK)
  182. {
  183. cache = c.DoFinal(dataToEncrypt, offSet, MAX_ENCRYPT_BLOCK);
  184. }
  185. else
  186. {
  187. cache = c.DoFinal(dataToEncrypt, offSet, inputLen - offSet);
  188. }
  189. //写入
  190. outStream.Write(cache, 0, cache.Length);
  191. time++;
  192. offSet = time * MAX_ENCRYPT_BLOCK;
  193. }
  194. byte[] resData = outStream.ToArray();
  195. string strBase64 = Convert.ToBase64String(resData);
  196. outStream.Close();
  197. return strBase64;
  198. }
  199. /// <summary>
  200. /// 用公钥给数据进行RSA解密
  201. /// </summary>
  202. /// <param name="xmlPublicKey"> 公钥(XML格式字符串) </param>
  203. /// <param name="strDecryptString"> 要解密数据 </param>
  204. /// <returns> 解密后的数据 </returns>
  205. public static string PublicKeyDecrypt(string xmlPublicKey, string strDecryptString)
  206. {
  207. //加载公钥
  208. RSACryptoServiceProvider publicRsa = new RSACryptoServiceProvider();
  209. publicRsa.FromXmlString(xmlPublicKey);
  210. RSAParameters rp = publicRsa.ExportParameters(false);
  211. //转换密钥
  212. AsymmetricKeyParameter pbk = DotNetUtilities.GetRsaPublicKey(rp);
  213. IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");
  214. //第一个参数为true表示加密,为false表示解密;第二个参数表示密钥
  215. c.Init(false, pbk);
  216. byte[] DataToDecrypt = Convert.FromBase64String(strDecryptString);
  217. byte[] cache;
  218. int time = 0;//次数
  219. int inputLen = DataToDecrypt.Length;
  220. int offSet = 0;
  221. MemoryStream outStream = new MemoryStream();
  222. while (inputLen - offSet > 0)
  223. {
  224. if (inputLen - offSet > MAX_DECRYPT_BLOCK)
  225. {
  226. cache = c.DoFinal(DataToDecrypt, offSet, MAX_DECRYPT_BLOCK);
  227. }
  228. else
  229. {
  230. cache = c.DoFinal(DataToDecrypt, offSet, inputLen - offSet);
  231. }
  232. //写入
  233. outStream.Write(cache, 0, cache.Length);
  234. time++;
  235. offSet = time * MAX_DECRYPT_BLOCK;
  236. }
  237. byte[] resData = outStream.ToArray();
  238. string strDec = Encoding.UTF8.GetString(resData);
  239. return strDec;
  240. }
  241. /// <summary>
  242. /// 签名
  243. /// </summary>
  244. /// <param name="str">需签名的数据</param>
  245. /// <returns>签名后的值</returns>
  246. public static string Sign(string str, string privateKey, SignAlgType signAlgType)
  247. {
  248. //根据需要加签时的哈希算法转化成对应的hash字符节
  249. byte[] bt = Encoding.GetEncoding("utf-8").GetBytes(str);
  250. byte[] rgbHash = null;
  251. switch (signAlgType)
  252. {
  253. case SignAlgType.SHA256:
  254. {
  255. SHA256CryptoServiceProvider csp = new SHA256CryptoServiceProvider();
  256. rgbHash = csp.ComputeHash(bt);
  257. }
  258. break;
  259. case SignAlgType.MD5:
  260. {
  261. MD5CryptoServiceProvider csp = new MD5CryptoServiceProvider();
  262. rgbHash = csp.ComputeHash(bt);
  263. }
  264. break;
  265. case SignAlgType.SHA1:
  266. {
  267. SHA1 csp = new SHA1CryptoServiceProvider();
  268. rgbHash = csp.ComputeHash(bt);
  269. }
  270. break;
  271. default:
  272. break;
  273. }
  274. RSACryptoServiceProvider key = new RSACryptoServiceProvider();
  275. key.FromXmlString(privateKey);
  276. RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(key);
  277. formatter.SetHashAlgorithm(signAlgType.ToString());//此处是你需要加签的hash算法,需要和上边你计算的hash值的算法一致,不然会报错。
  278. byte[] inArray = formatter.CreateSignature(rgbHash);
  279. return Convert.ToBase64String(inArray);
  280. }
  281. /// <summary>
  282. /// 签名验证
  283. /// </summary>
  284. /// <param name="str">待验证的字符串</param>
  285. /// <param name="sign">加签之后的字符串</param>
  286. /// <returns>签名是否符合</returns>
  287. public static bool Verify(string str, string sign, string publicKey, SignAlgType signAlgType)
  288. {
  289. byte[] bt = Encoding.GetEncoding("utf-8").GetBytes(str);
  290. byte[] rgbHash = null;
  291. switch (signAlgType)
  292. {
  293. case SignAlgType.SHA256:
  294. {
  295. SHA256CryptoServiceProvider csp = new SHA256CryptoServiceProvider();
  296. rgbHash = csp.ComputeHash(bt);
  297. }
  298. break;
  299. case SignAlgType.MD5:
  300. {
  301. MD5CryptoServiceProvider csp = new MD5CryptoServiceProvider();
  302. rgbHash = csp.ComputeHash(bt);
  303. }
  304. break;
  305. case SignAlgType.SHA1:
  306. {
  307. SHA1 csp = new SHA1CryptoServiceProvider();
  308. rgbHash = csp.ComputeHash(bt);
  309. }
  310. break;
  311. default:
  312. break;
  313. }
  314. RSACryptoServiceProvider key = new RSACryptoServiceProvider();
  315. key.FromXmlString(publicKey);
  316. RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(key);
  317. deformatter.SetHashAlgorithm(signAlgType.ToString());
  318. byte[] rgbSignature = Convert.FromBase64String(sign);
  319. if (deformatter.VerifySignature(rgbHash, rgbSignature))
  320. return true;
  321. return false;
  322. }
  323. /// <summary>
  324. /// 签名算法类型
  325. /// </summary>
  326. public enum SignAlgType
  327. {
  328. /// <summary>
  329. /// sha256
  330. /// </summary>
  331. SHA256,
  332. /// <summary>
  333. /// md5
  334. /// </summary>
  335. MD5,
  336. /// <summary>
  337. /// sha1
  338. /// </summary>
  339. SHA1
  340. }
  341. }

因为我在转换的时候遇到过问题,所以把问题整理一下,以供大家参考:

1.返回的字符串非法

我们可以清晰的知道该字符串不能够解析的原因是因为里面含有非法字符,所以我们要是解决这个问题,可以把那些非法字符给替换成base-64编码所需要的字符串

红色标记的代码就是用来修改字符串为正确的base-64编码,如果传的字符过长,需要修正他 的长度,以上便是所需代码,代码如有侵权,请联系我

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/525077
推荐阅读
相关标签
  

闽ICP备14008679号