package com.xiong;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class AESUtil {
private static String TRANSFORMAT = "AES/ECB/PKCS5Padding"; // jdk默认只支持PKCS5Padding填充
private String key = "B@#deCC%ejk569^5";
public AESUtil(String key) {
this.key = key;
}
public static void main(String[] args) throws Exception {
AESUtil aesUtil = new AESUtil("B@#deCC%ejk569^5B@#deCC%ejk569^e");
String xiong = aesUtil.encrypt("{\"mobile\": \"15680935251\"}");
String decrypt = aesUtil.decrypt(xiong);
System.out.println(decrypt);
System.out.println(xiong);
}
public String encrypt(String sSrc) throws Exception { // 加密
SecretKeySpec skeySpec = new SecretKeySpec(this.key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance(TRANSFORMAT);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(sSrc.getBytes("UTF-8"));
return new BASE64Encoder().encode(encrypted);
}
public String decrypt(String sSrc) // 解密
throws Exception {
if ((sSrc == null) || (sSrc.length() == 0)) {
return "";
}
SecretKeySpec skeySpec = new SecretKeySpec(this.key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance(TRANSFORMAT);
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] encrypted = new BASE64Decoder().decodeBuffer(sSrc);
byte[] original = cipher.doFinal(encrypted);
return new String(original, "UTF-8");
}
}