我自己實現CBC模式。我使用AES作爲每個CBC塊的E函數。AES。 javax.crypto.Cipher返回解密模式下的空數組
這裏是我的加密代碼:
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 algorythm開始時的最後一塊。
當我想解密cyphertext塊時,我使用與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
方法加密輸入空字節數組。
我很困惑。怎麼了?
請注意,由於裝箱,「列表」將消耗比字節數組多16倍的內存。 –
SLaks
2014-10-05 19:45:16
@SLaks依賴於'BytesConverter.toByteList'的實現,但我認爲LinkedList或ArrayList被使用,並且在這些情況下你肯定是正確的。而且幾乎沒有理由使用'List'。如果需要包裝器,請查看'java.nio.ByteBuffer'。 – 2014-10-05 20:24:54
@owlstead我只需要子列表。這就是我使用List的原因。 – 2014-10-05 20:43:27