Let me explain shortly. I have this encryptor in python:
It uses PyCrypto library.
from Crypto import Random
from Crypto.Cipher import AES
from Crypto.Util import Counter
iv = Random.new().read(8)
encryptor = AES.new(
CRYPTOGRAPHY_KEY, // 32 bytes
AES.MODE_CTR,
counter=Counter.new(64, prefix=iv),
)
and I want to have a decryptor for it in java.
I wrote this code but it raises java.security.InvalidAlgorithmParameterException: Wrong IV length: must be 16 bytes long
.
SecretKeySpec key = new SecretKeySpec(KEY, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
P.S. I should mention that I'm not an experienced Java developer.
Update. The problem was with initialization vector. Special thanks to @Andy for his time.
Solution:
byte[] nonceAndCounter = new byte[16];
System.arraycopy(iv, 0, nonceAndCounter, 0, 8);
nonceAndCounter[15] = (byte) 1; // PyCrypto's default initial value is 1
IvParameterSpec ivSpec = new IvParameterSpec(nonceAndCounter);