AESUtil.java 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. package com.crm.rely.backend.util;
  2. import com.crm.rely.backend.core.constant.Constants;
  3. import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
  4. import org.springframework.util.StringUtils;
  5. import javax.crypto.Cipher;
  6. import javax.crypto.KeyGenerator;
  7. import javax.crypto.SecretKey;
  8. import javax.crypto.spec.GCMParameterSpec;
  9. import javax.crypto.spec.SecretKeySpec;
  10. import java.nio.charset.StandardCharsets;
  11. import java.security.SecureRandom;
  12. import java.util.Arrays;
  13. public class AESUtil {
  14. private static final String KEY_ALGORITHM = "AES";
  15. private static final String KEY_GCM_NO_PADDING_ALGORITHM = "AES/GCM/NoPadding";
  16. private static final String SHA1PRNG = "SHA1PRNG";
  17. private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray();
  18. /**
  19. * AES 加密操作
  20. *
  21. * @param content 待加密内容
  22. * @return 返回Base64转码后的加密数据
  23. */
  24. public static String encrypt(String content) {
  25. return AESUtil.encrypt(content, Constants.AES_KEY);
  26. }
  27. public static String encrypt(String content, String secureKey) {
  28. return AESUtil.encrypt(content, secureKey, AESUtil.KEY_ALGORITHM);
  29. }
  30. public static String encrypt(String content, String secureKey, String algorithm) {
  31. return AESUtil.encrypt(content, secureKey, algorithm, AESUtil.SHA1PRNG);
  32. }
  33. public static String encrypt(String content, String secureKey, String algorithm, String srAlgorithm) {
  34. try {
  35. if ((StringUtils.isEmpty(content)) ||
  36. (StringUtils.isEmpty(secureKey))) {
  37. return null;
  38. }
  39. KeyGenerator kgen = KeyGenerator.getInstance(algorithm);
  40. SecureRandom secureRandom = SecureRandom.getInstance(srAlgorithm);
  41. secureRandom.setSeed(secureKey.getBytes());
  42. kgen.init(128, secureRandom);
  43. SecretKey secretKey = kgen.generateKey();
  44. byte[] enCodeFormat = secretKey.getEncoded();
  45. SecretKeySpec key = new SecretKeySpec(enCodeFormat, algorithm);
  46. Cipher cipher = Cipher.getInstance(algorithm);
  47. byte[] byteContent = content.getBytes("utf-8");
  48. cipher.init(1, key);
  49. byte[] result = cipher.doFinal(byteContent);
  50. return AESUtil.encodeBASE64(result);
  51. } catch (Exception ex) {
  52. // Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
  53. }
  54. return null;
  55. }
  56. public static String decrypt(String content, String secureKey) {
  57. return AESUtil.decrypt(content, secureKey, AESUtil.KEY_ALGORITHM);
  58. }
  59. public static String decrypt(String content, String secureKey, String algorithm) {
  60. return AESUtil.decrypt(content, secureKey, algorithm, AESUtil.SHA1PRNG);
  61. }
  62. public static String decrypt(String content, String secureKey, String algorithm, String srAlgorithm) {
  63. try {
  64. if ((StringUtils.isEmpty(content)) || (StringUtils.isEmpty(secureKey))) {
  65. return null;
  66. }
  67. KeyGenerator kgen = KeyGenerator.getInstance(algorithm);
  68. SecureRandom secureRandom = SecureRandom.getInstance(srAlgorithm);
  69. secureRandom.setSeed(secureKey.getBytes());
  70. kgen.init(128, secureRandom);
  71. SecretKey secretKey = kgen.generateKey();
  72. byte[] enCodeFormat = secretKey.getEncoded();
  73. SecretKeySpec key = new SecretKeySpec(enCodeFormat, algorithm);
  74. Cipher cipher = Cipher.getInstance(algorithm);
  75. cipher.init(2, key);
  76. byte[] base64Dec = Base64.decode(content);
  77. byte[] result = cipher.doFinal(base64Dec);
  78. return new String(result);
  79. } catch (Exception ex) {
  80. // Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
  81. }
  82. return null;
  83. }
  84. /**
  85. * AES 解密操作
  86. *
  87. * @param content
  88. * @return
  89. */
  90. public static String decrypt(String content) {
  91. return AESUtil.decrypt(content, Constants.AES_KEY);
  92. }
  93. public static String encodeBASE64(byte[] content)
  94. throws Exception {
  95. if ((content == null) || (content.length == 0)) {
  96. return null;
  97. }
  98. try {
  99. return Base64.encode(content);
  100. } catch (Exception ex) {
  101. // Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
  102. }
  103. return null;
  104. }
  105. public static String encryptPayload(String payload, String key) throws Exception {
  106. SecureRandom r = new SecureRandom();
  107. byte[] ivBytes = new byte[16];
  108. r.nextBytes(ivBytes);
  109. byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
  110. byte[] inputBytes = payload.getBytes(StandardCharsets.UTF_8);
  111. byte[] encryptedBytes = AESUtil.encryptDataWithAes(inputBytes, keyBytes, ivBytes);
  112. byte[] cipherTextBytes = Arrays.copyOfRange(encryptedBytes, 0, payload.length());
  113. byte[] authTagBytes = Arrays.copyOfRange(encryptedBytes, payload.length(), encryptedBytes.length);
  114. String ivHex = AESUtil.bytesToHex(ivBytes);
  115. String encryptedHex = AESUtil.bytesToHex(cipherTextBytes);
  116. String authTagHex = AESUtil.bytesToHex(authTagBytes);
  117. String result = new StringBuilder()
  118. .append(ivHex)
  119. .append(":")
  120. .append(encryptedHex)
  121. .append(":")
  122. .append(authTagHex)
  123. .toString();
  124. return result;
  125. }
  126. private static String bytesToHex(byte[] bytes) {
  127. char[] hexChars = new char[bytes.length * 2];
  128. for (int j = 0; j < bytes.length; j++) {
  129. int v = bytes[j] & 0xFF;
  130. hexChars[j * 2] = AESUtil.HEX_ARRAY[v >>> 4];
  131. hexChars[j * 2 + 1] = AESUtil.HEX_ARRAY[v & 0x0F];
  132. }
  133. return new String(hexChars);
  134. }
  135. private static byte[] encryptDataWithAes(byte[] plainText, byte[] aesKey, byte[] aesIv) throws Exception {
  136. GCMParameterSpec gcmSpec = new GCMParameterSpec(128, aesIv);
  137. Cipher cipher = Cipher.getInstance(AESUtil.KEY_GCM_NO_PADDING_ALGORITHM);
  138. SecretKeySpec secretKeySpec = new SecretKeySpec(aesKey, AESUtil.KEY_ALGORITHM);
  139. cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, gcmSpec);
  140. byte[] cipherText = cipher.doFinal(plainText);
  141. return cipherText;
  142. }
  143. public static void main(String[] args) throws Exception {
  144. // String content = "hello,您好";
  145. //
  146. // System.out.println("content:" + content);
  147. // String s1 = AESUtil.encrypt(content, Constants.AES_KEY);
  148. // System.out.println("s1:" + s1);
  149. // System.out.println("s2:" + AESUtil.decrypt(s1, Constants.AES_KEY));
  150. // System.out.println(encrypt("b36232e2356b4f549d8ba65ec203b075!@#WEB"));
  151. // System.out.println(decrypt("SDHmpqX6SSMKYLEpeUu9ivYd0CLJfcMRqn5cmL1X3WsP2WtHK7Fw3Fma82SSEs3b"));
  152. // String customId = "20926";
  153. // String en = encrypt(customId);
  154. // System.out.println(en);
  155. // System.out.println(decrypt(en));
  156. // System.out.println(AESUtil.encrypt("123", "gvwt4pujpR5atJueUAFBTiM5Con3obhE"));
  157. // System.out.println(AESUtil.encrypt("123", "gvwt4pujpR5atJueUAFBTiM5Con3obhE",
  158. // AESUtil.KEY_ALGORITHM, AESUtil.SHA1PRNG));
  159. // System.out.println(AESUtil.encrypt("123", "gvwt4pujpR5atJueUAFBTiM5Con3obhE"));
  160. // System.out.println(AESUtil.encryptPayload("123", "gvwt4pujpR5atJueUAFBTiM5Con3obhE"));
  161. // System.out.println(AESUtil.getSha512Hash("1,0,10"));
  162. }
  163. }