Java AES 解密字符串,处理 Base64 解码异常
这段代码使用 AES 算法对字符串进行解密操作。如果在解密过程中出现任何错误,都会返回 null。
在这个特定的异常中,报错是 java.lang.IllegalArgumentException: Last unit does not have enough valid bits,这通常发生在使用 Base64 进行解码时。这可能是因为加密字符串不是有效的 Base64 字符串导致的。
要解决此问题,可以检查传入的加密字符串是否正确并符合 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[] original = new byte[0];
try {
original = cipher.doFinal(Base64.getDecoder().decode(encryptedString));
} catch (IllegalBlockSizeException | BadPaddingException e) {
return null;
}
String combinedString = new String(original);
String[] parts = combinedString.split(':');
long id = Long.parseLong(parts[1]);
String inputString = parts[2];
DeviceEntity deviceEntity = new DeviceEntity();
deviceEntity.setDeviceId(id);
deviceEntity.setQrCode(inputString);
return deviceEntity;
}
原文地址: https://www.cveoy.top/t/topic/KwB 著作权归作者所有。请勿转载和采集!