5

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
    }
3
  • Generate a passphrase and encrypt it using a KeyStore-backed solution, such as the androidx.security classes like EncryptedFile. See this sample app (covered in this book). Commented Nov 6, 2021 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? Commented Jun 8, 2022 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. Commented Jun 8, 2022 at 14:59

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.