Storing files locally is a common task for mobile applications. Files that are stored unencrypted can be read out and modified by an attacker with physical access to the device. Access to sensitive data can be harmful for the user of the application, for example when the device gets stolen.

Ask Yourself Whether

There is a risk if you answered yes to any of those questions.

Recommended Secure Coding Practices

It’s recommended to password-encrypt local files that contain sensitive information. The class EncryptedFile can be used to easily encrypt files.

Sensitive Code Example

val targetFile = File(activity.filesDir, "data.txt")
targetFile.writeText(fileContent)  // Sensitive

Compliant Solution

val mainKey = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)

val encryptedFile = EncryptedFile.Builder(
    File(activity.filesDir, "data.txt"),
    activity,
    mainKey,
    EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
).build()

encryptedFile.openFileOutput().apply {
    write(fileContent)
    flush()
    close()
}

See