一、算法介绍
AES是对称加密算法,这种加密算法用来加密和解密的数据是相同的。
二、功能实现
代码实现及使用如下:
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.util.StringUtils;
/**
* AES加密算法工具类
* @since 2023-09-14 10:50
*
*/
public class AESUtil {
private static final String AES_ALGORITHM = "AES/ECB/PKCS5Padding";
private static final String SECRET_KEY = "5ir1k#xezi_IufR5"; // 必须是16个字符
/**
* 使用默认密钥加密
* @param plainText 明文
* @return 加密后的密文
* @throws Exception
*/
public static String encrypt(String plainText) throws Exception {
return encrypt(plainText, null);
}
/**
* 加密
* @param plainText 明文
* @param secretKey 密钥(密钥长度因为16个字符)
* @return 加密后的密文
* @throws Exception
*/
public static String encrypt(String plainText, String secretKey) throws Exception {
if(!StringUtils.hasText(secretKey))secretKey = SECRET_KEY;
SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedData = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedData);
}
/**
* 使用默认密钥解密
* @param encryptedData 密文
* @return 解密后的内容
* @throws Exception
*/
public static String decrypt(String encryptedData) throws Exception {
return decrypt(encryptedData, null);
}
/**
* 解密
* @param encryptedData 密文
* @param secretKey 密钥(密钥长度因为16个字符)
* @return 密文对应的明文
* @throws Exception
*/
public static String decrypt(String encryptedData, String secretKey) throws Exception {
if(!StringUtils.hasText(secretKey))secretKey = SECRET_KEY;
SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
return new String(decryptedData, StandardCharsets.UTF_8);
}
public static void main(String[] args) throws Exception {
//明文
String planText = "hello world!";
//SECRET_KEY 默认密钥
//加密(默认密钥加密)
String encryptedData = encrypt(planText);
System.out.println(encryptedData);
//解密(默认密钥解密)
System.out.println(decrypt(encryptedData));
}
}
如果对你有用的话,记得点赞加关注😊