3DES with AndroidKeyStore StrongBoxBacked crashes with Attempt to get length of null array when Cipher.init is called

376 Views Asked by At

I trying to insert 3DES key into AndroidKeyStore with setIsStrongBoxBacked(true) and then encrypt and decrypt some text. I understand that normal AndroidKeyStore dont support 3DES, but Hardware security module support Triple DES according this document https://developer.android.com/training/articles/keystore#HardwareSecurityModule

this is my test code:

        KeyGenerator kg = KeyGenerator.getInstance("DESede");
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        keyStore.setEntry(
                "TestAlias",
                new KeyStore.SecretKeyEntry(kg.generateKey()),
                new KeyProtection.Builder(KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                        .setIsStrongBoxBacked(true)
                        .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
                        .build());
        SecretKey key = (SecretKey) keyStore.getKey("TestAlias", null);
        Cipher c = Cipher.getInstance("DESede/CBC/PKCS7Padding");
        c.init(Cipher.ENCRYPT_MODE, key);
        IvParameterSpec paramSpec = new IvParameterSpec(c.getIV());
        byte[] encrypted = c.doFinal("hello, world".getBytes());
        c = Cipher.getInstance("DESede/CBC/PKCS7Padding");
        c.init(Cipher.DECRYPT_MODE, key, paramSpec);
        String decrypted = new String(c.doFinal(encrypted));

But it always crash on line c.init(Cipher.ENCRYPT_MODE, key); with

java.lang.NullPointerException: Attempt to get length of null array at com.android.org.bouncycastle.crypto.params.KeyParameter.(KeyParameter.java:17) at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineInit(BaseBlockCipher.java:787) at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineInit(BaseBlockCipher.java:1153) at javax.crypto.Cipher.tryTransformWithProvider(Cipher.java:2985) at javax.crypto.Cipher.tryCombinations(Cipher.java:2892) at javax.crypto.Cipher$SpiAndProviderUpdater.updateAndGetSpiAndProvider(Cipher.java:2797) at javax.crypto.Cipher.chooseProvider(Cipher.java:774) at javax.crypto.Cipher.init(Cipher.java:1144) at javax.crypto.Cipher.init(Cipher.java:1085) ....

I already tested AES instead 3DES and it complet without problems.

Testing on Pixel 6 with strongbox support.

1

There are 1 best solutions below

6
Vikram Gaur On

Was create key successful? Also, it seems that the code you’re using does not have BouncyCastle but the logs have bouncycastle. Am I missing something?

It is possible that you’re using previously created key with wrong provider later on.