1.加密
String格式的 key 、 iv 和 原文 使用getBytes转成字节数组即可
public static byte[] encrypt(byte[] key, byte[] iv, byte[] input) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
return encrypt(key, iv, input, 0, input.length);
}
public static byte[] encrypt(byte[] key, byte[] iv, byte[] input, int offset, int len) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
checkKeyLen(key);
SecretKey secretKey = new SecretKeySpec(key, "AES");
IvParameterSpec ivParamSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParamSpec);
return cipher.doFinal(input, offset, len);
}
加密结果转成HEX格式字符串方法:
private final static char[] CS = "0123456789ABCDEF".toCharArray();
/**
* 字节数组转换为HEX格式字符串.
*
* @param bs
* @return
*/
public static String bytesToHex(byte[] bs) {
char[] cs = new char[bs.length * 2];
int io = 0;
for (int n : bs) {
cs[io++] = CS[(n >> 4) & 0xF];
cs[io++] = CS[(n >> 0) & 0xF];
}
return new String(cs);
}
2.解密
String类型的 key 和 iv 使用getBytes转成字节数据即可, 密文需要使用hexToBytes方法转成字节数组
public static byte[] decrypt(byte[] key, byte[] iv, byte[] input) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
return decrypt(key, iv, input, 0, input.length);
}
public static byte[] decrypt(byte[] key, byte[] iv, byte[] input, int offset, int len) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
checkKeyLen(key);
SecretKey secretKey = new SecretKeySpec(key, "AES");
IvParameterSpec ivParamSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParamSpec);
return cipher.doFinal(input, offset, len);
}
解密前,密文需要使用hexToBytes方法转换成字节数组,方法如下:
/**
* HEX
*
* @param s
* @return
*/
public static byte[] hexToBytes(String s) {
s = s.toUpperCase();
int len = s.length() / 2;
int ii = 0;
byte[] bs = new byte[len];
char c;
int h;
for (int i = 0; i < len; i++) {
c = s.charAt(ii++);
if (c <= '9') {
h = c - '0';
} else {
h = c - 'A' + 10;
}
h <<= 4;
c = s.charAt(ii++);
if (c <= '9') {
h |= c - '0';
} else {
h |= c - 'A' + 10;
}
bs[i] = (byte) h;
}
return bs;
}