How to store hardcoded encryption master key in android?

Viewed 562

I'm building an app that uses Room and I want to encrypt the db using SQLCipher which needs a master key to encrypt/decrypt the db. I don't want to get the master key from the user, I want to use 1 master key and store it on the device but as far as I know hardcoding the key is not secure. So I want a way to store the key securly on the app to use it with SQLCipher.

1 Answers

You can use this library to secure your data using android keystore system. You can generate key in your app as:

String keyAlias = BuildConfig.APPLICATION_ID;
// Create and save key
Store store = new Store(FieldForceApplication.getContext());
if (!store.hasKey(keyAlias)) {
    SecretKey key = store.generateSymmetricKey(keyAlias, null);
}

And then get key using keyAlias(In my case applicationId), you can set any string.

SecretKey key = store.getSymmetricKey(keyAlias, null);

After getting key you can encrypt or decrypt data as:

Crypto crypto = new Crypto(Options.TRANSFORMATION_SYMMETRIC);
String encryptedData = crypto.encrypt(rawText, key);

String decryptedData = crypto.decrypt(rawText, key);
Related