Keystore getEntry returns NULL on Android 9
Asked Answered
E

0

8

cI have encrypted and decrypted a login password which is stored in the Android Keystore. On Android 9, I observed that the app crashes when trying to decrypt the password(I am not able to reproduce it but people having Pixel 3 are one of the devices with crash). Below is how I am decrypting the password from the keystore.

private static final String TRANSFORMATION = "AES/GCM/NoPadding";
private static final String ANDROID_KEY_STORE = "AndroidKeyStore";

private KeyStore keyStore;

public Decryptor() throws CertificateException, NoSuchAlgorithmException, KeyStoreException,
        IOException {
    initKeyStore();
}

private void initKeyStore() throws KeyStoreException, CertificateException,
        NoSuchAlgorithmException, IOException {
    keyStore = KeyStore.getInstance(ANDROID_KEY_STORE);
    keyStore.load(null);
}

@TargetApi(19)
public String decryptData(final String alias, final byte[] encryptedData, final byte[] encryptionIv)
        throws UnrecoverableEntryException, NoSuchAlgorithmException, KeyStoreException,
        NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IOException,
        BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException {

    final Cipher cipher = Cipher.getInstance(TRANSFORMATION);
    final GCMParameterSpec spec = new GCMParameterSpec(128, encryptionIv);
    cipher.init(Cipher.DECRYPT_MODE, getSecretKey(alias), spec);

    return new String(cipher.doFinal(encryptedData), "UTF-8");
}

private SecretKey getSecretKey(final String alias) throws NoSuchAlgorithmException,
        UnrecoverableEntryException, KeyStoreException {
    return ((KeyStore.SecretKeyEntry) keyStore.getEntry(alias, null)).getSecretKey();
}

The Keystore.getEntry(alias, null) seems to be returning NULL. Not sure why this is happening.

Fatal Exception: java.lang.NullPointerException
Attempt to invoke virtual method 'javax.crypto.SecretKey java.security.KeyStore$SecretKeyEntry.getSecretKey()' on a null object reference
Eldon answered 18/9, 2019 at 13:5 Comment(2)
hey How did you resolved this issue, I am getting the same NPE now for Mate 20 Pro(HUAWEI) device .Euboea
I get the same error on Nexus 5XUpraise

© 2022 - 2024 — McMap. All rights reserved.