1. package com.xiong;
    2. import sun.misc.BASE64Decoder;
    3. import sun.misc.BASE64Encoder;
    4. import javax.crypto.Cipher;
    5. import javax.crypto.spec.SecretKeySpec;
    6. public class AESUtil {
    7. private static String TRANSFORMAT = "AES/ECB/PKCS5Padding"; // jdk默认只支持PKCS5Padding填充
    8. private String key = "B@#deCC%ejk569^5";
    9. public AESUtil(String key) {
    10. this.key = key;
    11. }
    12. public static void main(String[] args) throws Exception {
    13. AESUtil aesUtil = new AESUtil("B@#deCC%ejk569^5B@#deCC%ejk569^e");
    14. String xiong = aesUtil.encrypt("{\"mobile\": \"15680935251\"}");
    15. String decrypt = aesUtil.decrypt(xiong);
    16. System.out.println(decrypt);
    17. System.out.println(xiong);
    18. }
    19. public String encrypt(String sSrc) throws Exception { // 加密
    20. SecretKeySpec skeySpec = new SecretKeySpec(this.key.getBytes(), "AES");
    21. Cipher cipher = Cipher.getInstance(TRANSFORMAT);
    22. cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    23. byte[] encrypted = cipher.doFinal(sSrc.getBytes("UTF-8"));
    24. return new BASE64Encoder().encode(encrypted);
    25. }
    26. public String decrypt(String sSrc) // 解密
    27. throws Exception {
    28. if ((sSrc == null) || (sSrc.length() == 0)) {
    29. return "";
    30. }
    31. SecretKeySpec skeySpec = new SecretKeySpec(this.key.getBytes(), "AES");
    32. Cipher cipher = Cipher.getInstance(TRANSFORMAT);
    33. cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    34. byte[] encrypted = new BASE64Decoder().decodeBuffer(sSrc);
    35. byte[] original = cipher.doFinal(encrypted);
    36. return new String(original, "UTF-8");
    37. }
    38. }