我自己实现CBC模式。我使用 AES 作为每个 CBC 块的 E 函数。
这是我的加密代码:
public static List<Byte> encrypt(List<Byte> bytes, byte[] key) throws Exception {
byte[] bytesArray = BytesConverter.toByteArray(bytes);
SecretKey secretKey = new SecretKeySpec(key, AES);
Cipher cipher = Cipher.getInstance(AES);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return BytesConverter.toByteList(cipher.update(bytesArray));
}
我使用update
是因为我不想添加 AES 垫。我自己在CBC算法开始时的最后一个块上做。
当我想解密密文块时,我使用与 Cipher.DECRYPTION_MODE 相同的函数。
public static List<Byte> decrypt(List<Byte> bytes, byte[] key) throws Exception {
byte[] bytesArray = BytesConverter.toByteArray(bytes);
SecretKey secretKey = new SecretKeySpec(key, AES);
Cipher cipher = Cipher.getInstance(AES);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return BytesConverter.toByteList(cipher.update(bytesArray));
}
问题在于,Cipher.update
在解密模式下,该encrypt
方法加密的输入返回空字节数组。
我很困惑。怎么了?