I'm facing problem from 3 days. I need to save a text from EditText into SharedPreferences. This text should be saved encrypted in SharedPreference after user authenticated with fingerprint scanner. Then I need to decrypt, later, this data so I need a permanent storage mechanism for the SecretKey generated.
private SecretKey createKey(String keyName) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEY_STORE);
keyGenerator.init(new KeyGenParameterSpec.Builder(keyName,
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setKeySize(DEFAULT_KEY_SIZE)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setUserAuthenticationRequired(true)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
.build());
return keyGenerator.generateKey();
}
Problem is happen when I try to load KeyStore from file using FileInputStream:
public static SecretKey getKeyFromKeystore(Context context) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
FileInputStream fis = null;
try {
fis = context.openFileInput(KEYSTORE_FILENAME);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
// FileInputStream fis = context.openFileInput(KEYSTORE_FILENAME);
keyStore.load(fis, null);
SecretKey keyStoreKey = null;
try {
keyStoreKey = (SecretKey) keyStore.getKey(CONFIDENTIALITY_KEY, null);
} catch (KeyStoreException e) {
e.printStackTrace();
return null;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
return null;
}
return keyStoreKey;
}
I'm getting error:
java.lang.IllegalArgumentException: InputStream not supported
at android.security.keystore.AndroidKeyStoreSpi.engineLoad(AndroidKeyStoreSpi.java:930)
Without .setUserAuthenticationRequired(true) I don't have this problem but I don't think this is the right way to use fingerprint's security.
Android Keystore's storage is located outside of your app's process. Thus, you don't need to store it into or load it from a file. All you need to do is invoke keyStore.load(null) and you should be good to go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With