Javaアプリケーションでjavacard 2.2.1で作成されたAESKeyを使用しようとしています 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);
データを暗号化する方法:
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);
その後、rnd を Java アプリに送信し、それを使用してキーを作成しようとします。
SecretKeySpec secretKeySpec = new SecretKeySpec(symKeyData, "AES");
SymKeyData == rnd であることはわかっています。このSecretKeyを使用して何かを暗号化できますが、復号化するとエラーが発生します:「与えられた最終ブロックが適切に埋め込まれていません」
Cipher cipherAes = Cipher.getInstance("AES");
cipherAes.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decryptedBytes = cipherAes.doFinal(challengeEncrypted);
確認したところ、challengeEncrypted が適切な長さです (48)。
Cipher cipherAes = Cipher.getInstance("AES/CBC/NoPadding");
しかし、成功しません。例外:「間違ったキー」
見つけた解決策
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);