java - AES 解密不正确
问题描述
我正在尝试重写我在互联网上找到的 AES 代码。试图将模式从 ECB 更改为 CBC。代码在加密或解密时没有给我任何错误,但它返回不正确的解密明文。你可以在这里看到输出。
public static String encrypt(String strToEncrypt, SecretKey secret) throws InvalidKeyException{
try{
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret); //without this line, iv = null
byte[] iv = cipher.getIV();
cipher.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(iv));
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byteArrayOutputStream.write(iv, 0, iv.length);
byte[] cipherT = cipher.doFinal(strToEncrypt.getBytes());
byteArrayOutputStream.write(cipherT, 0, cipherT.length);
cipherT = byteArrayOutputStream.toByteArray();
return Base64.getEncoder().encodeToString(cipher.doFinal(cipherT));
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public static String decrypt(String strToDecrypt, SecretKey secret) throws NoSuchAlgorithmException, NoSuchPaddingException{
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] iv = new byte[16];
byte[] CipherByte = Base64.getDecoder().decode(strToDecrypt);
iv = Arrays.copyOfRange(CipherByte, 0, iv.length);
CipherByte = Arrays.copyOfRange(CipherByte, 16, CipherByte.length);
try{
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
return new String(cipher.doFinal(CipherByte));
}catch(Exception e){
e.printStackTrace();
return null;
}
}
我尝试让 iv 全部为零,所以我不需要将它添加到密文中
byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
并在解密时读取它,但输出是相同的。我想不通,我不明白,是加密问题还是解密问题。
解决方案
推荐阅读
- azure-powershell - 在 powershell 中拆分后如何选择每个第三个实例
- assembly - 试图从 LED 开关板中的开关和输出中读取
- c++ - 具有两种类型混淆 C++ 的模板
- php - 转换为准备好的语句
- angular - NGRX/RXJS 观察者在页面刷新时未发出
- python - 列表索引超出范围,使用 sort(key=lambda) 进行索引
- go - 如何将特定字符串转换为键和值的拆分“=”并在golang中将其转换为json
- jsf - “目标无法到达,标识符‘mainBean’解析为空”JSF
- python - Python 3 Schedule 随时运行
- javascript - 是否可以编译 javascript 来保护浏览器 webapp 的源代码?