AES_CBC加密,填充方式为:AES/CBC/PKCS5Padding
因为是CBC方式,所以需要有加密向量
使用方式:
加密:encrypt("234234");
解密:decrypt("123123");
/**
* 使用AES解密字符串,返回原始字符串.
*/
private static String aesDecrypt(byte[] input, byte[] key, byte[] iv) {
byte[] decryptResult = aes(input, key, iv, Cipher.DECRYPT_MODE);
return new String(decryptResult);
}
/**
* 加密手机号,返回32位的16进制
*
* @param mobile
* @return
*/
public static String encrypt(String mobile) {
byte[] encrypted = aes(mobile.getBytes(), hexDecode(AES_KEY), hexDecode(AES_IV), Cipher.ENCRYPT_MODE);
return bytesToHex(encrypted);
}
/**
* 使用AES解密字符串,返回原始字符串.
*/
public static String decrypt(String decryptMobile) {
byte[] args1 = hexDecode(decryptMobile);
byte[] decryptResult = aes(args1, hexDecode(AES_KEY), hexDecode(AES_IV), Cipher.DECRYPT_MODE);
return new String(decryptResult);
}
private static byte[] aes(byte[] input, byte[] key, byte[] iv, int mode) {
try {
SecretKey secretKey = new SecretKeySpec(key, AES);
IvParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance(AES_CBC);
cipher.init(mode, secretKey, ivSpec);
return cipher.doFinal(input);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
/**
* Hex解码.
*/
private static byte[] hexDecode(String input) {
try {
return Hex.decodeHex(input.toCharArray());
} catch (DecoderException e) {
throw new IllegalStateException("Hex Decoder exception", e);
}
}
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);
}