AESEncryptUtil.java 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package com.izouma.nineth.utils;
  2. import javax.crypto.Cipher;
  3. import javax.crypto.KeyGenerator;
  4. import javax.crypto.SecretKey;
  5. import javax.crypto.spec.SecretKeySpec;
  6. import java.security.SecureRandom;
  7. /**
  8. * <p>AES加密处理工具类</p>
  9. *
  10. * @author licoy.cn
  11. * @version 2018/9/5
  12. */
  13. public class AESEncryptUtil {
  14. private final static String password = "xRvGxVMeIbuQxICtstQCPjtyNuBluyyC";
  15. /**
  16. * AES加密
  17. *
  18. * @param content 字符串内容
  19. */
  20. public static String encrypt(String content) throws Exception {
  21. return aes(content, Cipher.ENCRYPT_MODE);
  22. }
  23. /**
  24. * AES解密
  25. *
  26. * @param content 字符串内容
  27. */
  28. public static String decrypt(String content) throws Exception {
  29. return aes(content, Cipher.DECRYPT_MODE);
  30. }
  31. /**
  32. * AES加密/解密 公共方法
  33. *
  34. * @param content 字符串
  35. * @param type 加密:{@link Cipher#ENCRYPT_MODE},解密:{@link Cipher#DECRYPT_MODE}
  36. */
  37. private static String aes(String content, int type) throws Exception {
  38. KeyGenerator generator = KeyGenerator.getInstance("AES");
  39. SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
  40. random.setSeed(password.getBytes());
  41. generator.init(128, random);
  42. SecretKey secretKey = generator.generateKey();
  43. byte[] enCodeFormat = secretKey.getEncoded();
  44. SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
  45. Cipher cipher = Cipher.getInstance("AES");
  46. cipher.init(type, key);
  47. if (type == Cipher.ENCRYPT_MODE) {
  48. byte[] byteContent = content.getBytes("utf-8");
  49. return Hex2Util.parseByte2HexStr(cipher.doFinal(byteContent));
  50. } else {
  51. byte[] byteContent = Hex2Util.parseHexStr2Byte(content);
  52. return new String(cipher.doFinal(byteContent));
  53. }
  54. }
  55. }