RSAUtils.java 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. package com.ruoyi.app.utils;
  2. import org.apache.commons.codec.binary.Base64;
  3. import javax.crypto.Cipher;
  4. import java.io.ByteArrayOutputStream;
  5. import java.io.IOException;
  6. import java.security.*;
  7. import java.security.interfaces.RSAKey;
  8. import java.security.interfaces.RSAPrivateKey;
  9. import java.security.interfaces.RSAPublicKey;
  10. import java.security.spec.InvalidKeySpecException;
  11. import java.security.spec.PKCS8EncodedKeySpec;
  12. import java.security.spec.X509EncodedKeySpec;
  13. import java.util.HashMap;
  14. import java.util.Map;
  15. public class RSAUtils {
  16. public static final String CHARSET = "UTF-8";
  17. public static final String RSA_ALGORITHM = "RSA";
  18. public static Map<String, String> createKeys(int keySize) {
  19. //为RSA算法创建一个KeyPairGenerator对象
  20. KeyPairGenerator kpg;
  21. try {
  22. kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
  23. } catch (NoSuchAlgorithmException e) {
  24. throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]");
  25. }
  26. //初始化KeyPairGenerator对象,密钥长度
  27. kpg.initialize(keySize);
  28. //生成密匙对
  29. KeyPair keyPair = kpg.generateKeyPair();
  30. //得到公钥
  31. Key publicKey = keyPair.getPublic();
  32. String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded());
  33. //得到私钥
  34. Key privateKey = keyPair.getPrivate();
  35. String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded());
  36. Map<String, String> keyPairMap = new HashMap<String, String>();
  37. keyPairMap.put("publicKey", publicKeyStr);
  38. keyPairMap.put("privateKey", privateKeyStr);
  39. return keyPairMap;
  40. }
  41. /**
  42. * 得到公钥
  43. *
  44. * @param publicKey 密钥字符串(经过base64编码)
  45. * @throws Exception
  46. */
  47. public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
  48. //通过X509编码的Key指令获得公钥对象
  49. KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
  50. X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
  51. RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
  52. return key;
  53. }
  54. /**
  55. * 得到私钥
  56. *
  57. * @param privateKey 密钥字符串(经过base64编码)
  58. * @throws Exception
  59. */
  60. public static RSAPrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
  61. //通过PKCS#8编码的Key指令获得私钥对象
  62. KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
  63. PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
  64. RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
  65. return key;
  66. }
  67. public static byte[] encrypt(byte[] data, Key key) throws Exception {
  68. Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
  69. cipher.init(Cipher.ENCRYPT_MODE, key);
  70. return rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data
  71. , ((RSAKey) key).getModulus().bitLength());
  72. }
  73. public static byte[] decrypt(byte[] data, Key key) throws Exception {
  74. Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
  75. cipher.init(Cipher.DECRYPT_MODE, key);
  76. return rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, data, ((RSAKey) key)
  77. .getModulus()
  78. .bitLength());
  79. }
  80. private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize) {
  81. int maxBlock;
  82. if (opmode == Cipher.DECRYPT_MODE) {
  83. maxBlock = keySize / 8;
  84. } else {
  85. maxBlock = keySize / 8 - 11;
  86. }
  87. ByteArrayOutputStream out = new ByteArrayOutputStream();
  88. int offSet = 0;
  89. byte[] buff;
  90. int i = 0;
  91. try {
  92. while (datas.length > offSet) {
  93. if (datas.length - offSet > maxBlock) {
  94. buff = cipher.doFinal(datas, offSet, maxBlock);
  95. } else {
  96. buff = cipher.doFinal(datas, offSet, datas.length - offSet);
  97. }
  98. out.write(buff, 0, buff.length);
  99. i++;
  100. offSet = i * maxBlock;
  101. }
  102. } catch (Exception e) {
  103. throw new RuntimeException("加解密阀值为[" + maxBlock + "]的数据时发生异常", e);
  104. }
  105. byte[] resultDatas = out.toByteArray();
  106. try {
  107. out.close();
  108. } catch (IOException e) {
  109. throw new RuntimeException("关闭流失败", e);
  110. }
  111. return resultDatas;
  112. }
  113. public static String DoRSASha256(String input, RSAPrivateKey privateKey) throws Exception {
  114. // MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
  115. // messageDigest.update(input.getBytes(CHARSET));
  116. // byte[] digested = messageDigest.digest();
  117. Signature signature = Signature.getInstance("SHA256withRSA");
  118. signature.initSign(privateKey);
  119. signature.update(input.getBytes(CHARSET));
  120. return Base64.encodeBase64String(signature.sign());
  121. }
  122. public static boolean VerifyRSASha256(String input, String sign, RSAPublicKey publicKey) throws Exception {
  123. Signature signature = Signature.getInstance("SHA256withRSA");
  124. signature.initVerify(publicKey);
  125. signature.update(input.getBytes(CHARSET));
  126. return signature.verify(Base64.decodeBase64(sign));
  127. }
  128. }