AESEncryptUtil.java 2.0 KB

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