/**
* AES-128/GCM + BASE64算法加密
*
* @param content
* @param secretKey
* @return
*/
private static String aesEncrypt(String content, String secretKey) {
try {
byte[] hexStr = HexUtils.fromHexString(secretKey);
//加密算法:AES/GCM/PKCS5Padding
Cipher cipher = Cipher.getInstance("AES/GCM/PKCS5Padding");
SecretKeySpec skeySpec = new SecretKeySpec(hexStr, "AES");
//随机生成iv 12位
byte[] iv = new byte[12];
SecureRandom.getInstance("SHA1PRNG").nextBytes(iv);
//数据加密, AES-GCM-128
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new GCMParameterSpec(128, iv));
byte[] encrypted = cipher.doFinal(content.getBytes()); //数据加密
//iv+加密数据 拼接 iv在前,加密数据在后
ByteBuffer byteBuffer = ByteBuffer.allocate(iv.length + encrypted.length);
byteBuffer.put(iv);
byteBuffer.put(encrypted);
byte[] cipherMessage = byteBuffer.array();
//转换为Base64 Base64算法有多种变体, 这里使用的是java.util.Base64
return Base64.getEncoder().encodeToString(cipherMessage);
} catch (Exception e) {
log.error("content:" + content, e);
}
return null;
}
AES-128/GCM + BASE64算法加密
最新推荐文章于 2024-05-13 17:04:37 发布