问题
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