Solution 1 :
For CBC mode you should call
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
NoPadding
options means that apply no padding. This is useful if
- Your data is always multiple of the AES block size, i.e. 128k
- You will do your padding, probably developing a new one.
If you are talking about ECB mode, that doesn’t need IV and don’t use ECB. It is insecure. If you really need then call it without an IV.
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
If your Android target matches prefer GCM mode instead of ECB or CBC. That is a modern encryption mode; Authenticated Encryption (with Associated Data). You will get Confidentiality, authentication, and integrity.
Problem :
I know a lot of these questions were asked. but in my case the error is:
java.security.InvalidAlgorithmParameterException: expected IV length of 0
I’m trying AES 128 CBC mode
code:
byte[] iv = new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00};
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] decryptedBytes = cipher.doFinal(encrypted);
return decryptedBytes;
If I change init vector to something like this as error suggested:
byte[] iv = new byte[]{};
I’m receiving error :
java.security.InvalidAlgorithmParameterException: expected IV length of 16
Comments
Comment posted by Fajar Khan
Changed as suggested but now throwing this error: javax.crypto.BadPaddingException: EVP_CipherFinal_ex
Comment posted by Fajar Khan
Also my data will be always 128 bit, 128-bit key and IV
Comment posted by Fajar Khan
encyption is done by NFC based card reader (I’m using this for card auth). I will receive 16-byte encrypted data with the key.
Comment posted by Fajar Khan
As per doc ‘encrypted/decrypted using AES 128 CBC with an IV with value 00h’
Comment posted by Fajar Khan
I have NDA signed for the doc. I cant share link or its copy. but it doesn’t say nopadding or AES/CBC/nopadding. what I posted before was the full text mentioned from doc.