待完善
public class AES {
/*
* 加密用的Key 可以用26个字母和数字组成 使用AES-128-CBC加密模式,key需要为16位。
*/
private static final String key="KNr2u9q7pV8ZgDfB";
private static final String iv ="0102030405060708";
/**
* @author miracle.qu
* @Description AES算法加密明文
* @param data 明文
* @return 密文
*/
public static String encryptAES(String data) throws Exception {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
int blockSize = cipher.getBlockSize();
byte[] dataBytes = data.getBytes();
int plaintextLength = dataBytes.length;
if (plaintextLength % blockSize != 0) {
plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
}
byte[] plaintext = new byte[plaintextLength];
System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); // CBC模式,需要一个向量iv,可增加加密算法的强度
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
// byte[] encrypted = cipher.doFinal(plaintext);
byte[] encrypted = cipher.doFinal(dataBytes);
return new BASE64Encoder().encode(encrypted); // BASE64做转码。
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) throws Exception {
System.out.println(encryptAES("TU4Bhswf+ezuzeyko9WzYN9nPsBUwg0WXsm7X6nXQQa1ssKXzFndddg5D9rrw4P1/rc7PfYeI2OFFgseTap+8uedMg5tVM/a8F5US6qDtLY="));
}
}