Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyStore vs KeyChain

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.

like image 913
Mediha Avatar asked Feb 15 '18 13:02

Mediha


1 Answers

Use the KeyChain API when you want system-wide credentials. When an app requests the use of any credential through the KeyChain API, users get to choose, through a system-provided UI, which of the installed credentials an app can access. This allows several apps to use the same set of credentials with user consent.

Use the Android Keystore provider to let an individual app store its own credentials that only the app itself can access. This provides a way for apps to manage credentials that are usable only by itself while providing the same security benefits that the KeyChain API provides for system-wide credentials. This method requires no user interaction to select the credentials. refrence

like image 195
Anice Jahanjoo Avatar answered Oct 30 '22 17:10

Anice Jahanjoo