Keystore getEntry returns NULL on Android 9

佐手、 提交于 2019-12-11 15:35:34

问题


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

来源:https://stackoverflow.com/questions/57993508/keystore-getentry-returns-null-on-android-9

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!