首页 > 解决方案 > 如何在 Android 中弃用 MasterKeys 后创建 masterKey

问题描述

我正在使用以下代码在我的应用程序中存储一些加密的信息。

    val masterKey = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)

    val sharedPreferences = EncryptedSharedPreferences.create(
        "secret_shared_prefs",
        masterKey,
        this,
        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
    )

由于 Android 中不推荐使用 MasterKeys 类,我应该使用 MasterKey 类,但我不知道什么是正确的方法来定义相同的掌握。

有人可以显示与可用的 MasterKey 和 MasterKey.Builder 类的完全匹配吗?

下面的解决方案是这样工作的:

val spec = KeyGenParameterSpec.Builder(
        "_androidx_security_master_key_",
        KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
    )
        .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
        .setKeySize(256)
        .build()

    val masterKey: MasterKey = MasterKey.Builder(this)
        .setKeyGenParameterSpec(spec)
        .build()

    val sharedPreferences = EncryptedSharedPreferences.create(
        this,
        "secret_shared_prefs",
        masterKey, // masterKey created above
        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM);

标签: kotlinencrypted-shared-preference

解决方案


试试这个


MasterKey masterKey = new MasterKey.Builder(context, MasterKey.DEFAULT_MASTER_KEY_ALIAS)
        .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
        .build();

SharedPreferences sharedPreferences = EncryptedSharedPreferences.create(
        context,
        SHARED_PREF_NAME,
        masterKey,
        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM);

推荐阅读