Keystore getEntry 在 Android 9 上返回 NULL

use*_*865 8 security encryption android android-keystore android-9.0-pie

c 我已经加密和解密了存储在 Android Keystore 中的登录密码。在 Android 9 上,我观察到应用程序在尝试解密密码时崩溃(我无法重现它,但拥有 Pixel 3 的人是崩溃的设备之一)。下面是我从密钥库解密密码的方法。

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();
}
Run Code Online (Sandbox Code Playgroud)

Keystore.getEntry(alias, null) 似乎返回 NULL。不知道为什么会这样。

Fatal Exception: java.lang.NullPointerException
Attempt to invoke virtual method 'javax.crypto.SecretKey java.security.KeyStore$SecretKeyEntry.getSecretKey()' on a null object reference
Run Code Online (Sandbox Code Playgroud)