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



我正在尝试创建一个帮助程序类,该类将使用 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()

未解析的引用。以下候选人均不适用 由于接收器类型不匹配:

  • @InlineOnly 公共内联乐趣 File.bufferedWriter(charset: Charset = ..., bufferSize: Int = ...(: 在 kotlin.io 中定义的缓冲编写器
  • @InlineOnly 公共内联乐趣 OutputStream.bufferedWriter(charset: Charset = ...(:在 kotlin.io 中定义的 BufferedWriter

我在某处缺少参考吗?我是否使用了不正确的引用?代码是否已更改,链接上的文档是否已过时?

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

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

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

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

希望这对其他人有所帮助。

最新更新