AES加密
public class AesSecurityUtils {
private static final String DEFAULT_KEY = "key";
public static final String AES_KEY = "defaultKey";
/**
* 加密
* @param strKey key
* @param strIn 明文`在这里插入代码片`
* @return 密文
*/
public static String encrypt(String strKey, String strIn) throws Exception {
SecretKeySpec keySpec = getKey(strKey);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
byte[] encrypted = cipher.doFinal(strIn.getBytes(StandardCharsets.UTF_8));
return parseByte2HexStr(encrypted);
}
/**
* 解密
* @param strKey key
* @param strIn 密文
* @return 明文
*/
public static String decrypt(String strKey, String strIn) throws Exception{
SecretKeySpec skeySpec = getKey(strKey);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5padding");
IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] encrypted = parseHexStr2Byte(strIn);
byte[] original = cipher.doFinal(Objects.requireNonNull(encrypted));
return new String(original, StandardCharsets.UTF_8);
}
private static SecretKeySpec getKey(String strKey) {
if (StringUtils.isBlank(strKey)){
strKey = DEFAULT_KEY;
}
byte[] arrTmp = strKey.getBytes();
//创建一个空的16位字节数组(默认为0)
byte[] arrB = new byte[16];
for (int i = 0; i < arrTmp.length && i < arrB.length; i++) {
arrB[i] = arrTmp[i];
}
return new SecretKeySpec(arrB, "AES");
}
/**
* 将16进制转换为二进制
* @param hexStr 16进制字符串
* @return 二进制
*/
public static byte[] parseHexStr2Byte(String hexStr){
if (StringUtils.isBlank(hexStr)){
return null;
}
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
/**
* 将二进制转换成16进制
* @return 16进制字符串
*/
public static String parseByte2HexStr(byte[] buf){
StringBuilder sb = new StringBuilder();
for (byte b : buf) {
String hex = Integer.toHexString(b & 0xFF);
if (hex.length() == 1) {
hex = "0" + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
public static void main(String[] args) throws Exception{
String act = "123";
//加密
String enAct = AesSecurityUtils.encrypt(AES_KEY, act);
System.out.println("加密:" + enAct);
//解密
String deAct = AesSecurityUtils.decrypt(AES_KEY, enAct);
System.out.println("解密:" + deAct);
}
}