使用 EncryptedSharedPreferences 给出错误协议消息包含无效标签(零)

问题描述 投票:0回答:1

在真实设备上执行此代码时

String masterKeyAlias = masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);
SharedPreferences settings = EncryptedSharedPreferences.create(
                    "encrypted_preferences",
                    masterKeyAlias,
                    myAppContext,
                    EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
                    EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
            );

我收到以下异常:

com.google.crypto.tink.shaded.protobuf.InvalidProtocolBufferException:协议消息包含无效标签(零)。

MasterKeyAlias 的值为“androidx_security_master_key”。

是某些参数值导致问题还是其他原因?android

android androidx encrypted-shared-preference
1个回答
0
投票
评论中的

@Mark 是正确的,设置 android:allowBackup="false"android:dataExtractionRules="false" 将防止许多崩溃。但在某些情况下,用户仍然遇到了这个问题。 我的解决方法是在加密共享首选项初始化期间捕获任何异常,并在 catch 块中清除共享首选项并尝试重新创建加密共享首选项。

private var makingSharedPrefAttempts = 0

fun makeSecuritySharedPreferences(context: Context): SharedPreferences {
try {
    makingSharedPrefAttempts++

    val masterKeyAlias: String = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
    return EncryptedSharedPreferences.create(
        "your_key",
        masterKeyAlias,
        context,
        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
    )
} catch (e: Exception) {
    if (makingSharedPrefAttempts > 1) throw e

    context.getSharedPreferences(
        "your_key",
        Context.MODE_PRIVATE
    ).edit().clear().apply()

    return makeSecuritySharedPreferences(context)
}}
© www.soinside.com 2019 - 2024. All rights reserved.