androidkotlininternal-storageandroid-internal-storage

How to write / read internal files securely


I'm trying to create a helper class that will handle reading and writing internal files in my android app using Kotlin.

Here are the links I followed in order:

  1. https://developer.android.com/guide/topics/data/data-storage
  2. https://developer.android.com/training/data-storage/files.html#WriteInternalStorage
  3. https://developer.android.com/training/data-storage/files/internal
  4. https://developer.android.com/topic/security/data

Here's my code:

package com.example.testapp

// Added
import android.content.Context
import java.io.File

// External
import androidx.security.crypto.EncryptedFile
import androidx.security.crypto.MasterKeys

@Suppress("unused")
class SystemMain {
    fun writeFile(context: Context) {
        // Although you can define your own key generation parameter specification, it's recommended that you use the value specified here.
        val keyGenParameterSpec = MasterKeys.AES256_GCM_SPEC
        val masterKeyAlias = MasterKeys.getOrCreate(keyGenParameterSpec)

        // Creates a file with this name, or replaces an existing file that has the same name. Note that the file name cannot contain path separators.
        val fileToWrite = "my_sensitive_data.txt"
        val encryptedFile = EncryptedFile.Builder(File(fileToWrite), context, masterKeyAlias, EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB).build()

        encryptedFile.bufferedWriter().use { writer ->
            writer.write("MY SUPER-SECRET INFORMATION")
        }
    }
}

Here's my build.gradle:

...
implementation "androidx.lifecycle:lifecycle-extensions:2.1.0"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.1.0"

implementation "androidx.security:security-crypto:1.0.0-alpha02"
...

The error I'm getting is here: encryptedFile.bufferedWriter()

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:

  • @InlineOnly public inline fun File.bufferedWriter(charset: Charset = ..., bufferSize: Int = ...): Buffered Writer defined in kotlin.io
  • @InlineOnly public inline fun OutputStream.bufferedWriter(charset: Charset = ...): BufferedWriter defined in kotlin.io

Am I missing a reference somewhere? Am I using the incorrect references? Has the code changed and the documentation on the links are outdated?

I'm very new at this. Any advice / help will be appreciated.


Solution

  • After looking at definitions and declarations; I've found this:

    encryptedFile.openFileOutput().bufferedWriter().use {writer ->
        writer.write("MY SUPER-SECRET INFORMATION")
    }
    

    Not sure how well this will work, but there's no error.

    Hope this helps someone else.