AES(Advanced Encryption Standard)是一种对称加密算法,能够实现数据的加密和解密。它可以用来保护数据的机密性,主要用于互联网传输中的数据安全保护。
AES加密算法有三种密钥长度可供选择:128位、192位和256位,其中密钥长度为128位的被广泛使用。加密和解密过程中使用相同的密钥,因此称为对称加密算法。
AES算法的加密过程如下:
将明文(原始数据)按照一定的分组方式进行分组。
对每个分组进行一系列的变换操作,包括字节代换、行移位、列混淆和轮密钥加等操作。
重复上述变换操作,直到达到指定的轮数为止。
最后,输出经过变换的分组作为密文。
AES算法的解密过程与加密过程相反:
将密文按照相同的分组方式进行分组。
对每个分组进行逆变换操作,包括逆字节代换、逆行移位、逆列混淆和轮密钥加等操作。
重复上述逆变换操作,直到达到指定的轮数为止。
最后,输出经过逆变换的分组作为明文。
AES算法的安全性较高,是目前使用最广泛的加密算法之一,被广泛应用于网络通信、数据存储等领域。
AES 加密解密代码
private final static String KEY = "abcdefghij1234567890";
/**
* AES加密
*
* @param data 需要加密的数据
* @return 加密字符串 加密失败返回null
*/
public static String encrypt(String data) {
if (StringUtils.isBlank(data)) {
return null;
}
try {
byte[] iv = KEY.substring(0, 12).getBytes(StandardCharsets.UTF_8);
byte[] contentBytes = data.getBytes(StandardCharsets.UTF_8);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec params = new GCMParameterSpec(128, iv);
SecretKeySpec keyspec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), "AES");
cipher.init(Cipher.ENCRYPT_MODE, keyspec, params);
byte[] encryptData = cipher.doFinal(contentBytes);
return Base64.getEncoder().encodeToString(encryptData);
} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException |
BadPaddingException | InvalidAlgorithmParameterException e) {
throw new BaseException("-999", e.getMessage());
}
}
/**
* AES解密
*
* @param data 需要解密的数据
* @return 解密字符串 解密失败返回null
*/
public static String decrypt(String data) {
if (StringUtils.isBlank(data)) {
return null;
}
try {
byte[] content = Base64.getDecoder().decode(data);
byte[] iv = KEY.substring(0, 12).getBytes(StandardCharsets.UTF_8);
GCMParameterSpec params = new GCMParameterSpec(128, iv);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), "AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec, params);
byte[] decryptData = cipher.doFinal(content);
return new String(decryptData, StandardCharsets.UTF_8);
} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
| InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
throw new BaseException("-999", e.getMessage());
}
}
密钥KEY根据自己业务定义。