I have an app that generates a key for encryption/decryption and it is working just fine. I store my key in KeyStore and IV as first 12B in encrypted file saved on external storage. When I want to decrypt the file, I get the file from external storage (hence I get IV) and key from KeyStore, and I am able to get original content. My second application App2 can access file in external storage (hence it can get IV), but it can't get key from App1 KeyStore. I was reading about KeyChain and it says in official documentation it is not app private (Use the KeyChain API when you want system-wide credentials). Can I somehow store my key in this KeyChain or somewhere else so my App2 can get it (with some user approval or something similar). Here is the code I used to create and store key in App1.
private static SecretKey createAndStoreKey() {
KeyGenerator keyGen;
try {
// Generate 256-bit key
keyGen = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEY_STORE_NAME);
final KeyGenParameterSpec keyGenParameterSpec = new KeyGenParameterSpec.Builder(KEY_ALIAS,
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.build();
keyGen.init(keyGenParameterSpec);
SecretKey secretKey = keyGen.generateKey();
if(secretKey != null)
return secretKey;
else
return null;
}
catch (NoSuchProviderException e){
e.printStackTrace();
return null;
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
catch (InvalidAlgorithmParameterException e){
e.printStackTrace();
return null;
}
}
Thank you all for the help.
Keystore
's access by defining a sharedUserId in your apps manifest (you need also to sign the apps with the same certificate). But I haven't tried it and tbh it doesn't seem the best solution. – Brahmaputra