import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.UUID;
/**
* @author chunyang.leng
* @date 2021-11-05 11:18 上午
*/
public class AesUtils {
/**
* 密钥长度必须为16位
*/
private static final String PASSWORD = "0123456789123456";
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
/**
* AES加密字符串
*
* @param message 需要被加密的字符串
* @return base64 密文
*/
public static String encrypt(String message) throws Exception {
if (message == null ){
return null;
}
// AES专用密钥
SecretKeySpec secretKey = new SecretKeySpec(PASSWORD.getBytes(), ALGORITHM);
// 创建密码器
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
byte[] byteContent = message.getBytes(StandardCharsets.UTF_8);
// 初始化为加密模式的密码器
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
// 加密后的byte数据
byte[] bytes = cipher.doFinal(byteContent);
// 转base64
return Base64.getEncoder().encodeToString(bytes);
}
/**
* 解密AES加密过的字符串
*
* @param encryptMessage AES加密过过的内容
* @return 明文
*/
public static String decrypt(String encryptMessage)throws Exception {
if (encryptMessage == null){
return null;
}
byte[] decodeArray = Base64.getDecoder().decode(encryptMessage);
// AES专用密钥
SecretKeySpec secretKey = new SecretKeySpec(PASSWORD.getBytes(), ALGORITHM);
// 创建密码器
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
// 初始化为解密模式的密码器
cipher.init(Cipher.DECRYPT_MODE, secretKey);
// 明文数组
byte[] bytes = cipher.doFinal(decodeArray);
return new String(bytes, StandardCharsets.UTF_8);
}
public static void main(String[] args) throws Exception {
boolean b = true;
for (int i = 0; i < 50 ; i++) {
String uuid = UUID.randomUUID().toString();
System.out.println("uuid=====>" + uuid);
String encrypt = encrypt(uuid);
System.out.println("encrypt=====>" + encrypt);
String decrypt = decrypt(encrypt);
System.out.println("decrypt=====>" + decrypt);
b &= decrypt.equals(uuid);
}
System.out.println("final =====>" + b);
}
}
JAVA使用AES实现对称加密
最新推荐文章于 2024-05-31 11:57:18 发布