0

I am trying to use AES encryption in the Android KeyStore - key generation and encryption is working fine, but the encryption doesnt. I use following code to gerenate the key:

    KeyGenerator keyGenerator = KeyGenerator.getInstance(
                KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
        keyGenerator.init(
                new KeyGenParameterSpec.Builder(keyAlias, keyUsage)
                        .setKeySize(256)
                        .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
                        .setIsStrongBoxBacked(false)
                        .build());
        keyTeeAES = keyGenerator.generateKey();

And following code for encryption and decryption

 Cipher cipher;

 cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
 cipher.init(Cipher.ENCRYPT_MODE, keyTeeAES);
 cipherCreatedAES = cipher.doFinal(data);

 IvParameterSpec ivParameterSpec = new IvParameterSpec(cipher.getIV());
 cipher.init(Cipher.DECRYPT_MODE, keyTeeAES, ivParameterSpec);
 cipher.doFinal(cipherCreatedAES);

I get following error doing the decryption, apparently I get a NullPointerException in

IvParameterSpec ivParameterSpec = new IvParameterSpec(cipher.getIV());

W/System.err: java.lang.NullPointerException: Attempt to get length of null array
    at javax.crypto.spec.IvParameterSpec.<init>(IvParameterSpec.java:53)
    at com.example.securecomputingtest.CryptographyTee.useKeysAES(CryptographyTee.java:347)
    at com.example.securecomputingtest.MainActivity$2.onClick(MainActivity.java:150)
    at android.view.View.performClick(View.java:7259)
    at android.view.View.performClickInternal(View.java:7236)
    at android.view.View.access$3600(View.java:801)
    at android.view.View$PerformClick.run(View.java:27892)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7356)
    at java.lang.reflect.Method.invoke(Native Method)

I also tried following Why does my AES encryption throws an InvalidKeyException? - but didnt work either

Jonas
  • 1

1 Answers1

0

I resolved it now by disabling randomized encryption in the KeyGenParameterSpec by

.setRandomizedEncryptionRequired(false)

and set a fixed IV, it works now, although this solution might not be optimal.

Jonas
  • 1