Security Library

Offerings

Key management

Classes included in Security library

Include in Project

implementation("androidx.security:security-crypto:1.1.0-alpha06")

Read / Write Files Using EncryptedFile

To know where to place the file, either know exactly which directory you can reach from the code and place it there. Or print the output of context.filesDir and place the file there using Android Studio’s Device Explorer feature. I tried to place the file in res/raw but could not get a reference to it properly from code.

Even though you just placed the file somewhere, you cannot read it using EncryptedFile yet because it’s still unencrypted, it’s just text. First encrypt the file and then read the encrypted file. You will get a No matching key found for the ciphertext in the stream exception otherwise.

Generate Key

This will generate a symmetric key. Same one used for writing must be used for reading. This key will be stored in the Android Keystore system.

private fun getMasterKey(context: Context) {
	MasterKey.Builder(context)
	    .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
	    .build()
}

Write to File

fun writeFile(context: Context) {
    val fileToWrite = File(context.filesDir, "my_secret_file.txt")

    val encryptedFile = EncryptedFile.Builder(
        context,
        fileToWrite,
        [getMasterKey(context),](<https://odaym.notion.site/Security-36635e265a8c480483db93ca53eeb8db>)
        EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
    ).build()

    // File cannot exist before using openFileOutput()
    if (fileToWrite.exists()) {
        fileToWrite.delete()
    }

    val fileContent = "MY SUPER-SECRET INFORMATION".toByteArray(Charsets.UTF_8)
    encryptedFile.openFileOutput().apply {
        write(fileContent)
        flush()
        close()
    }
}