Search code examples
javaandroidencryptionaestee

Android: Check if Key is in Secure Hardware


For my application, I create an AES key and want to check whether said key is stored inside the Secure Hardware. I googled and found an example for RSA, but figured it shouldn't matter. Below is the RSA example I found:

final KeyGenerator keyGenerator = KeyGenerator
        .getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");

final KeyGenParameterSpec keyGenParameterSpec = new KeyGenParameterSpec.Builder("key_alias",
        KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
        .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
        .build();

keyGenerator.init(keyGenParameterSpec);
final SecretKey secretKey = keyGenerator.generateKey();

final Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);

KeyFactory keyFactory = KeyFactory.getInstance(secretKey.getAlgorithm(), "AndroidKeyStore");
KeyInfo keyInfo = keyFactory.getKeySpec(secretKey, KeyInfo.class);
keyInfo.isInsideSecureHardware();

However, the very first line returns a no such algorithm: AES for provider AndroidKeyStore exception. But shouldn't it be possible to check if an AES key is inside the secure hardware for AES as well?

Theoretically I could use asymmetric encryption, since it is only a small snippet of data I want to en/decrypt but I would still prefer if I could use symmetric encryption.

Do you guys have an idea?

Edit: Added further implementation details.


Solution

  • In order to get KeyInfo for a symmetric key, the following code is needed:

    SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(secretKey.getAlgorithm(), "AndroidKeyStore");
    KeyInfo keyInfo = (KeyInfo) secretKeyFactory.getKeySpec(secretKey, KeyInfo.class);