共享密钥加密 公开密钥加密_如何迁移到加密的共享首选项

共享密钥加密 公开密钥加密

秘密指南 (THE SECRET GUIDE)

The Android framework provides us with SharedPreferences, which is a great way to store a small collection of key-value data. When working with sensitive data, however, it’s important to understand that SharedPreferences stores data as plain text. We should encrypt sensitive data to prevent it from being hacked. How can we do so?

Android框架为我们提供了SharedPreferences ,这是存储少量键值数据的好方法。 但是,在处理敏感数据时,重要的是要了解SharedPreferences将数据存储为纯文本。 我们应该加密敏感数据以防止其被黑客入侵。 我们该怎么做?

The Security library comes to the rescue!

安全库可助您一臂之力!

The Security library, part of Android Jetpack, provides an implementation of the security best practices related to reading and writing data, as well as key creation and verification.

安全性库是Android Jetpack的一部分,提供了与读写数据以及密钥创建和验证有关的安全性最佳实践的实现。

In this article, I’ll share with you how to migrate your existing Shared Preferences to EncryptedSharedPreferences. Stay tuned:)

在本文中,我将与您分享如何迁移现有的共享首选项 EncryptedSharedPreferences 。 敬请关注:)

建立 (Setup)

To get started with the AndroidX Security library, add the following dependency to your module-level build.gradle file.

要开始使用AndroidX安全性库,请将以下依赖项添加到模块级build.gradle文件中。

dependencies {
implementation "androidx.security:security-crypto:1.0.0-rc01"
}

In order to use this library, you will need to set minSdkVersion to 23+

为了使用此库,您需要将minSdkVersion设置为23+

android { defaultConfig {
minSdkVersion 23
}
}

However, in case your application is targeting devices below minSdkVersion 23, do not apply this change and add the following line to your AndroidManifest.xml:

但是,如果您的应用程序针对的是minSdkVersion 23以下的设备,请不要应用此更改,并将以下行添加到您的AndroidManifest.xml中:

<uses-sdk tools:overrideLibrary="androidx.security"/>

编码时间! (Coding-Time!)

SharedPreferencesManager (SharedPreferencesManager)

Interface with all the SharedPreferences APIs supported.

与所有支持的SharedPreferences API的接口。

interface SharedPreferencesManager {


    fun <T : Any?> set(key: String, value: T)


    fun getString(key: String, defaultValue: String?): String?


    fun getInt(key: String, defaultValue: Int): Int


    fun getBoolean(key: String, defaultValue: Boolean): Boolean


    fun getLong(key: String, defaultValue: Long): Long


    fun getFloat(key: String, defaultValue: Float): Float


    fun contains(key: String): Boolean


    fun remove(key: String)


    fun clear()
}

SharedPreferencesManagerImpl (SharedPreferencesManagerImpl)

Handling the creation of the EncryptedSharedPreferences in case SDK version is ≥ 23, otherwise we will keep using the original non-encrypted SharedPreferences.

如果SDK版本≥23,则处理EncryptedSharedPreferences的创建,否则我们将继续使用原始的非加密SharedPreferences。

class SharedPreferencesManagerImpl(val context: Context) : SharedPreferencesManager {


    private val notEncryptedPreferencesName = "not_encrypted_preferences_filename"
    private val encryptedPreferencesName = "encrypted_preferences_filename"


    private var prefs: SharedPreferences


    init {


        val nonEncryptedPreferences: SharedPreferences = context.getSharedPreferences(notEncryptedPreferencesName, Context.MODE_PRIVATE)


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            prefs = initializeEncryptedSharedPreferencesManager()
            if (nonEncryptedPreferences.all.isNotEmpty()) {
                // migrate non encrypted shared preferences
                // to encrypted shared preferences and clear them once finished.
                nonEncryptedPreferences.copyTo(prefs)
                nonEncryptedPreferences.clear()
            }
        } else {
            prefs = nonEncryptedPreferences
        }
    }


    private fun initializeEncryptedSharedPreferencesManager(): SharedPreferences {
        val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
        return EncryptedSharedPreferences.create(
                encryptedPreferencesName,
                masterKeyAlias,
                context,
                EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
                EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
        )
    }


    override fun <T : Any?> set(key: String, value: T) {
        prefs.set(key, value)
    }


    override fun getString(key: String, defaultValue: String?): String? {
        val value = getValue(key, defaultValue)
        return value as String?
    }


    override fun getInt(key: String, defaultValue: Int): Int {
        val value = getValue(key, defaultValue)
        return value as Int
    }


    override fun getBoolean(key: String, defaultValue: Boolean): Boolean {
        val value = getValue(key, defaultValue)
        return value as Boolean
    }


    override fun getLong(key: String, defaultValue: Long): Long {
        val value = getValue(key, defaultValue)
        return value as Long
    }


    override fun getFloat(key: String, defaultValue: Float): Float {
        val value = getValue(key, defaultValue)
        return value as Float
    }


    private fun getValue(key: String, defaultValue: Any?): Any? {
        var value = prefs.all[key]
        value = value ?: defaultValue
        return value
    }


    override fun contains(key: String): Boolean {
        return prefs.contains(key)
    }


    override fun remove(key: String) {
        prefs.remove(key)
    }


    override fun clear() {
        prefs.clear()
    }
}

SharedPreferencesUtils (SharedPreferencesUtils)

These methods in SharedPreferencesUtils class, extend the SharedPreferences class to give more abilities.

SharedPreferencesUtils类中的这些方法扩展了SharedPreferences类,以提供更多功能。

fun SharedPreferences.copyTo(dest: SharedPreferences) {
    for (entry in all.entries) {
        val key = entry.key
        val value: Any? = entry.value
        dest.set(key, value)
    }
}


inline fun SharedPreferences.edit(operation: (SharedPreferences.Editor) -> Unit) {
    val editor = this.edit()
    operation(editor)
    editor.apply()
}


fun SharedPreferences.set(key: String, value: Any?) {
    when (value) {
        is String? -> edit { it.putString(key, value) }
        is Int -> edit { it.putInt(key, value.toInt()) }
        is Boolean -> edit { it.putBoolean(key, value) }
        is Float -> edit { it.putFloat(key, value.toFloat()) }
        is Long -> edit { it.putLong(key, value.toLong()) }
        else -> {
            Logger.logError(TAG, "Unsupported Type: $value")
        }
    }
}


fun SharedPreferences.clear() {
    edit() { it.clear() }
}


fun SharedPreferences.remove(key: String) {
    edit { it.remove(key) }
}

摘要 (Summary)

Android’s SharedPreferences is a useful tool to store key-value data and when that data is sensitive, it’s a good idea to encrypt it. The recent AndroidX Security library is a welcome addition that provides us with a simple and easy-to-use interface to do so.

Android的SharedPreferences是存储键值数据的有用工具,当该数据是敏感数据时,最好对它进行加密。 最新的AndroidX安全性库是受欢迎的补充,它为我们提供了一个简单易用的界面。

That’s all! I hope you liked this article.

就这样! 希望您喜欢这篇文章。

翻译自: https://medium.com/att-israel/how-to-migrate-to-encrypted-shared-preferences-cc4105c03518

共享密钥加密 公开密钥加密

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值