4

I want to generate a key and then use it to encrypt Room DB with SQLCipher, but the problem is SQLCipher requires a CharArray as a key to encrypt SQLite data. is there a way to use secretKey instead of CharArray or at least convert the secretKey to CharArray?.

My code to generate the key :

private val keyGenerator: KeyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")

    private val keyGenParameterSpec = KeyGenParameterSpec.Builder(
        KEY_ALIAS,
    KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
        .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
        .build()

        keyGenerator.init(keyGenParameterSpec)
        keyGenerator.generateKey()

    fun getKey(): SecretKey {
        val keyStore = KeyStore.getInstance("AndroidKeyStore")
        keyStore.load(null)

        val secretKeyEntry = keyStore.getEntry(KEY_ALIAS, null) as KeyStore.SecretKeyEntry
        return secretKeyEntry.secretKey
    }
Mox4
  • 41
  • 2
  • Generate a passphrase and encrypt it using a KeyStore-backed solution, such as the `androidx.security` classes like `EncryptedFile`. See [this sample app](https://gitlab.com/commonsguy/cw-room/-/tree/v0.6/ToDoGen) (covered in [this book](https://commonsware.com/Room)). – CommonsWare Nov 06 '21 at 15:12
  • @CommonsWare would it be ok to generate the passphrase with `UUID.randomUUID().toString()` and than store and retrieve it from `EncryptedSharedPreferences`? That way `EncryptedSharedPreferences` would deal with all of the encryption,decryption, key management etc.. Or this is not good since we would idealy want our passphrase to be `ByteArray` instead of `String`? – Torima Jun 08 '22 at 14:27
  • @Torima: `EncryptedSharedPreferences` probably is fine -- my sample used `EncryptedFile`. The `ByteArray` approach should be faster than a `String` and has the advantage of being able to replace the `ByteArray`'s contents with zeros once you are done with the passphrase, so the passphrase stays around in memory for less time. – CommonsWare Jun 08 '22 at 14:59

0 Answers0