import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
* Created by child on 2016/4/9.
* <p/>
* AES 加密/解密
*/
@SuppressWarnings("restriction")
public class AESEncryptUtil {
public static String encrypt(String content, String key) throws Exception {
if (StringUtils.isBlank(content) || StringUtils.isBlank(key)) {
return null;
}
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
byte[] bytes = cipher.doFinal(content.getBytes("utf-8"));
return new BASE64Encoder().encode(bytes);
}
public static String decrypt(String content, String key) throws Exception {
if (StringUtils.isBlank(content) || StringUtils.isBlank(key)) {
return null;
}
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
byte[] bytes = new BASE64Decoder().decodeBuffer(content);
bytes = cipher.doFinal(bytes);
return new String(bytes, "utf-8");
}
public static void main(String[] args) {
try {
String content = "helloworld";
String password = "1234567891234567";
String result = encrypt(content, password);
System.out.println(result);
System.out.println(decrypt(result, password));
} catch (Exception e) {
e.printStackTrace();
}
}