I am trying to use a AESKey, made on javacard 2.2.1 in a java application How i make the AESKEY:
RandomData randomData = RandomData.getInstance(RandomData.ALG_PSEUDO_RANDOM);
byte[] rnd = JCSystem.makeTransientByteArray((short)16, JCSystem.CLEAR_ON_RESET);
randomData.generateData(rnd, (short)0, (short)rnd.length);
AESKey symKey = (AESKey) KeyBuilder.buildKey (KeyBuilder.TYPE_AES, KeyBuilder.LENGTH_AES_128, false);
symKey.setKey(rnd, (short)0);
How i encrypt data:
Cipher symCipher = Cipher.getInstance(Cipher.ALG_AES_BLOCK_128_CBC_NOPAD, false);
symCipher.init(symKey, Cipher.MODE_ENCRYPT);
byte[] encryptedC= new byte[48];
symCipher.doFinal(c, (short)0, (short)c.length, encryptedC, (short)0);
After that i send rnd to my java app and try to make a key with it.
SecretKeySpec secretKeySpec = new SecretKeySpec(symKeyData, "AES");
I know that SymKeyData == rnd. I can use this SecretKey to encrypt something but when i decrypt i get an error: "Given final block not properly padded"
Cipher cipherAes = Cipher.getInstance("AES");
cipherAes.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decryptedBytes = cipherAes.doFinal(challengeEncrypted);
I checked and challengeEncrypted is the good length.(48) Tried it with:
Cipher cipherAes = Cipher.getInstance("AES/CBC/NoPadding");
But no succes, exception: "wrong key"
FOUND SOLUTION
byte[] ivdata = new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
IvParameterSpec spec = new IvParameterSpec(ivdata);
symetricKeyFromCard = new SecretKeySpec(symKeyData, "AES");
Cipher cipherAes = Cipher.getInstance("AES/CBC/NoPadding");
cipherAes.init(Cipher.DECRYPT_MODE, symetricKeyFromCard, spec);
byte[] decryptedBytes = cipherAes.doFinal(challengeEncrypted);