【问题标题】:How to write / read internal files securely如何安全地写入/读取内部文件
【发布时间】:2020-02-18 13:53:42
【问题描述】:

我正在尝试创建一个帮助程序类,该类将使用 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 public inline fun File.bufferedWriter(charset: Charset = ..., bufferSize: Int = ...): kotlin.io 中定义的缓冲写入器
  • @InlineOnly public inline fun OutputStream.bufferedWriter(charset: Charset = ...): kotlin.io 中定义的BufferedWriter

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

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

【问题讨论】:

标签: android kotlin internal-storage android-internal-storage


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2010-12-21
    • 2018-06-08
    • 2019-07-02
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    • 2015-03-04
    • 2016-05-07
    • 2015-12-10
    相关资源
    最近更新 更多