AESUtil.java 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package com.idea.util;
  2. import javax.crypto.Cipher;
  3. import javax.crypto.spec.IvParameterSpec;
  4. import javax.crypto.spec.SecretKeySpec;
  5. import java.nio.charset.StandardCharsets;
  6. import java.security.MessageDigest;
  7. import java.util.Base64;
  8. public class AESUtil {
  9. public static String decryptKey(String tokenId, String pw) throws Exception {
  10. // MD5加密
  11. byte[] md5Byte =MessageDigest.getInstance("MD5").digest(tokenId.getBytes());
  12. // 转为16进制字符串
  13. String hexStr = bytesToHex(md5Byte);
  14. // 截取
  15. String aesKey = hexStr.substring(8, 24);
  16. // AES解密,返回结果
  17. return decrypt(pw, aesKey, aesKey);
  18. }
  19. private static String bytesToHex(byte[] bytes) {
  20. StringBuilder sb = new StringBuilder(bytes.length * 2);
  21. for (int i = 0; i < bytes.length; i++) {
  22. sb.append(Character.toUpperCase(Character.forDigit((bytes[i] >> 4) & 0x0F, 16)));
  23. sb.append(Character.toUpperCase(Character.forDigit(bytes[i] & 0x0F, 16)));
  24. }
  25. return sb.toString();
  26. }
  27. private static String decrypt(String pw, String aesKey, String viPara) throws Exception {
  28. IvParameterSpec zeroIv = new IvParameterSpec(viPara.getBytes());
  29. SecretKeySpec key = new SecretKeySpec(aesKey.getBytes(), "AES");
  30. Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  31. cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
  32. return new String(cipher.doFinal(Base64.getDecoder().decode(pw)), StandardCharsets.UTF_8);
  33. }
  34. }