package com.ponux.test;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AES {
public static byte[] encrypt(String content, String keyWord) {
try {
if (keyWord == null) {
System.out.print("Key为空null");
return null;
}
if (keyWord.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = keyWord.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//算法/模式/补码方式
IvParameterSpec iv = new IvParameterSpec(new byte[16]);//使用CBC模式,需要一个向量iv,可增加加密算法的强度
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(content.getBytes());
return encrypted;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static byte[] decrypt(byte[] content, String keyWord) {
try {
// 判断Key是否正确
if (keyWord == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (keyWord.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = keyWord.getBytes(); // "ASCII"
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(new byte[16]);
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original = cipher.doFinal(content);
return original;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws Exception {
String cKey = "1234567890123456";
// 需要加密的字串
String cSrc = "Email : arix04@xxx.com";
System.out.println(cSrc);
// 加密
byte[] encrypted = AES.encrypt(cSrc, cKey);
System.out.println("加密后 " + encrypted);
// 解密
byte[] origin = AES.decrypt(encrypted, cKey);
System.out.println("解密后 " + new String(origin));
}
}