如何安全地写入/读取内部文件

How to write / read internal files securely

我正在尝试创建一个助手 class,它将使用 Kotlin 处理我的 android 应用程序中的内部文件读写。

以下是我按顺序访​​问的链接:

  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

这是我的代码:

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")
        }
    }
}

这是我的 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"
...

我得到的错误在这里: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

我是不是在某处遗漏了参考资料?我使用的参考资料不正确吗?代码是否已更改且链接上的文档已过时?

我对此很陌生。任何建议/帮助将不胜感激。

查看定义和声明后;我发现了这个:

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

不确定这将如何工作,但没有错误。

希望这对其他人有帮助。