Java AES 解密方法:验证 Base64 编码并返回 DeviceEntity 对象
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class DeviceEntityDecrypter {
private static final String INIT_VECTOR = "your_init_vector";
private static final String KEY = "your_key";
public static DeviceEntity decrypt(String encryptedString) {
if (!Base64.isBase64(encryptedString)) {
return null;
}
IvParameterSpec iv = new IvParameterSpec(INIT_VECTOR.getBytes(StandardCharsets.UTF_8));
SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), "AES");
Cipher cipher = null;
try {
cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
return null;
}
try {
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
} catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
return null;
}
byte[] decodedBytes;
try {
decodedBytes = Base64.getDecoder().decode(encryptedString);
} catch (IllegalArgumentException e) {
return null;
}
String combinedString = new String(decodedBytes, StandardCharsets.UTF_8);
String[] parts = combinedString.split(":");
if (parts.length != 3) {
return null;
}
long id;
try {
id = Long.parseLong(parts[1]);
} catch (NumberFormatException e) {
return null;
}
String inputString = parts[2];
DeviceEntity deviceEntity = new DeviceEntity();
deviceEntity.setDeviceId(id);
deviceEntity.setQrCode(inputString);
return deviceEntity;
}
}
代码说明:
- 验证 Base64 编码: 使用
Base64.isBase64(encryptedString)检查传入的加密字符串是否符合 Base64 编码规范。如果不符合,则直接返回null。 - 解密操作: 使用 AES/CBC/PKCS5PADDING 算法解密 Base64 编码的字符串。
- 解析解密结果: 将解密后的字符串按照
:分割,解析出设备 ID 和二维码信息,并将其封装到DeviceEntity对象中。 - 错误处理: 对所有可能出现的异常进行捕获,并返回
null。
注意事项:
- 确保
INIT_VECTOR和KEY的值是正确的,且是安全存储的。 - 考虑使用更安全的加密方式,例如使用随机生成的 IV 和密钥。
- 避免在代码中直接使用硬编码的敏感信息,建议使用配置文件或环境变量存储敏感信息。
原文地址: https://www.cveoy.top/t/topic/Kth 著作权归作者所有。请勿转载和采集!