Java AES 解密字符串并验证 Base64 编码 - 提高代码安全性和健壮性
public static DeviceEntity decrypt(String encryptedString){
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[] encryptedBytes = Base64.getDecoder().decode(encryptedString);
if (!Base64.isBase64(encryptedBytes)) {
return null; // 返回null,传入的加密字符串不符合Base64编码规范
}
byte[] original = new byte[0];
try {
original = cipher.doFinal(encryptedBytes);
} catch (IllegalBlockSizeException | BadPaddingException e) {
return null;
}
String combinedString = new String(original);
String[] parts = combinedString.split(':');
if (parts.length != 3) {
return null; // 返回null,传入的加密字符串格式不正确
}
long id;
try {
id = Long.parseLong(parts[1]);
} catch (NumberFormatException e) {
return null; // 返回null,传入的加密字符串中的id无法转换为long类型
}
String inputString = parts[2];
DeviceEntity deviceEntity = new DeviceEntity();
deviceEntity.setDeviceId(id);
deviceEntity.setQrCode(inputString);
return deviceEntity;
}
修改后的代码会检查传入的加密字符串是否符合Base64编码规范,以及加密字符串的格式是否正确。如果不符合规范或格式不正确,将返回null。
原文地址: https://www.cveoy.top/t/topic/Kus 著作权归作者所有。请勿转载和采集!