美文网首页
Android security-crypto 库使用

Android security-crypto 库使用

作者: 乘风破浪的程序员 | 来源:发表于2019-09-29 18:28 被阅读0次

Android Security

Note: 只支持Android 6.0 以上

dependencies {
 def security_version = "1.0.0-alpha02"
 implementation "androidx.security:security-crypto:$security_version"
}

Work with data more securely

文件内容操作

e.g : 文件写入

 private fun writeFile(){
        val key = MasterKeys.AES256_GCM_SPEC
        val masterKeyAlias = MasterKeys.getOrCreate(key)
        val fileName = "my.txt"
        val encryptedFile = EncryptedFile.Builder(File(this.filesDir, fileName),
            this,
            masterKeyAlias,
            EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB)
            .build()
        try {
            val outPutStream = encryptedFile.openFileOutput()
            outPutStream.apply {
                write("这是一个测试输入文本内容".toByteArray(Charset.forName("UTF-8")))
                flush()
                close()
            }
        } catch (e: Exception) {
        }
    }

打开文件看到的内容:

(G�y��2SS��ݬ�FBg6��Wyb��P��4rU��{����$��a��)�(2���@�fɏ�=F�c\)Kx��O���Ŷ�?PC�TIE0ݚ�G����

e.g: 读取

private fun readFile() : String{
        val key = MasterKeys.AES256_GCM_SPEC
        val masterKeyAlias = MasterKeys.getOrCreate(key)
        val readFile = "my.txt"
        val readEncrypt = EncryptedFile.Builder(
            File(this.filesDir, readFile),
            this,
            masterKeyAlias,
            EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
        )
            .build()
        lateinit var byteStream: ByteArrayOutputStream
        var fileContent: String? = null
        try {
            val fileInputSteam = readEncrypt.openFileInput()
            try {
                byteStream = ByteArrayOutputStream()
                var nextRead = fileInputSteam.read()
                while (nextRead != -1){
                    byteStream.write(nextRead)
                    nextRead = fileInputSteam.read()
                }
                fileContent = byteStream.toString()
            } catch (e: java.lang.Exception){
            } finally {
                fileInputSteam.close()
            }
        } catch (e: Exception) {
        }
        return fileContent!!
    }

输出:

这是一个测试输入文本内容

SharedPreferences

val sharedPreferences = EncryptedSharedPreferences
    .create(
    fileName,
    masterKeyAlias,
    context,
    EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
    EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)

val sharedPrefsEditor = sharedPreferences.edit()

相关文章

网友评论

      本文标题:Android security-crypto 库使用

      本文链接:https://www.haomeiwen.com/subject/antqpctx.html