1. public class AESUtil {
    2. public static String Encrypt(String sSrc, String sKey) throws Exception {
    3. if (sKey == null) {
    4. System.out.print("Key为空null");
    5. return null;
    6. }
    7. // 判断Key是否为16位
    8. if (sKey.length() != 16) {
    9. System.out.print("Key长度不是16位");
    10. return null;
    11. }
    12. byte[] raw = sKey.getBytes("utf-8");
    13. SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    14. Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
    15. cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    16. byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
    17. return new Base64().encodeToString(encrypted);//此处使用BASE64做转码功能,同时能起到2次加密的作用。
    18. }
    19. // 解密
    20. public static String Decrypt(String sSrc, String sKey) throws Exception {
    21. try {
    22. // 判断Key是否正确
    23. if (sKey == null) {
    24. System.out.print("Key为空null");
    25. return null;
    26. }
    27. // 判断Key是否为16位
    28. if (sKey.length() != 16) {
    29. System.out.print("Key长度不是16位");
    30. return null;
    31. }
    32. byte[] raw = sKey.getBytes("utf-8");
    33. SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    34. Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    35. cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    36. byte[] encrypted1 = new Base64().decode(sSrc);//先用base64解密
    37. try {
    38. byte[] original = cipher.doFinal(encrypted1);
    39. String originalString = new String(original, "utf-8");
    40. return originalString;
    41. } catch (Exception e) {
    42. System.out.println(e.toString());
    43. return null;
    44. }
    45. } catch (Exception ex) {
    46. System.out.println(ex.toString());
    47. return null;
    48. }
    49. }
    50. public static void main(String[] args) throws Exception {
    51. /*
    52. * 此处使用AES-128-ECB加密模式,key需要为16位。
    53. */
    54. String cKey = "1234567812345678";
    55. // 需要加密的字串
    56. String cSrc = "是哈哈哈哈";
    57. // 加密
    58. String enString = AESUtil.Encrypt(cSrc, cKey);
    59. System.out.println("加密后的字串是:" + enString);
    60. // 解密
    61. String DeString = AESUtil.Decrypt(enString, cKey);
    62. System.out.println("解密后的字串是:" + DeString);
    63. }
    64. }