- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
背景
在我使用的一个应用程序中,我将重要的东西( token )存储到 EncryptedSharedPreferences 中(取自 here 和 here ):
/** a hardware-encrypted based shared preference (for the values).
* Note that it is a bit slow, so it's better to always use it in a background thread.
* Also, avoid having it being backed-up in the manifest, as it's hardware based and will become useless: https://stackoverflow.com/a/63795282/878126*/
object SecuredSharedPreferences {
private var cachedDefaultSharedPreferences: SharedPreferences? = null
/**warning: using this function can take some time (249 ms on Pixel 4, for example). Very recommended to avoid calling it on UI thread */
@WorkerThread
fun getDefaultSecuredSharedPreferences(context: Context): SharedPreferences {
if (cachedDefaultSharedPreferences != null)
return cachedDefaultSharedPreferences!!
synchronized(this) {
if (cachedDefaultSharedPreferences != null)
return cachedDefaultSharedPreferences!!
cachedDefaultSharedPreferences = getSecuredSharedPreferences(context, context.packageName + "_secured_preferences")
}
return cachedDefaultSharedPreferences!!
}
@WorkerThread
private fun getSecuredSharedPreferences(context: Context, fileName: String): SharedPreferences {
val masterKey = MasterKey.Builder(context, MasterKey.DEFAULT_MASTER_KEY_ALIAS).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build()
return EncryptedSharedPreferences.create(context, fileName, masterKey,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
}
}
毕业典礼:
implementation 'androidx.security:security-crypto:1.1.0-alpha03'
问题
MasterKey.Builder
GeneralSecurityException
行: Fatal Exception: java.security.GeneralSecurityException: Keystore operation failed
at androidx.security.crypto.MasterKeys.generateKey(MasterKeys.java:146)
at androidx.security.crypto.MasterKeys.getOrCreate(MasterKeys.java:97)
at androidx.security.crypto.MasterKey$Builder.buildOnM(MasterKey.java:357)
at androidx.security.crypto.MasterKey$Builder.build(MasterKey.java:314)
...
Caused by java.security.ProviderException: Keystore operation failed
at android.security.keystore.AndroidKeyStoreKeyGeneratorSpi.engineGenerateKey(AndroidKeyStoreKeyGeneratorSpi.java:372)
at javax.crypto.KeyGenerator.generateKey(KeyGenerator.java:612)
at androidx.security.crypto.MasterKeys.generateKey(MasterKeys.java:142)
at androidx.security.crypto.MasterKeys.getOrCreate(MasterKeys.java:97)
at androidx.security.crypto.MasterKey$Builder.buildOnM(MasterKey.java:357)
at androidx.security.crypto.MasterKey$Builder.build(MasterKey.java:314)
EncryptedSharedPreferences.create
KeyStoreException
行,并且更频繁地出现并为更多用户提供:Fatal Exception: java.security.KeyStoreException: the master key android-keystore://_androidx_security_master_key_ exists but is unusable
at com.google.crypto.tink.integration.android.AndroidKeysetManager$Builder.readOrGenerateNewMasterKey(AndroidKeysetManager.java:275)
at com.google.crypto.tink.integration.android.AndroidKeysetManager$Builder.build(AndroidKeysetManager.java:236)
at androidx.security.crypto.EncryptedSharedPreferences.create(EncryptedSharedPreferences.java:155)
at androidx.security.crypto.EncryptedSharedPreferences.create(EncryptedSharedPreferences.java:120)
...
Caused by java.security.UnrecoverableKeyException: Failed to obtain information about key
at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStoreSecretKeyFromKeystore(AndroidKeyStoreProvider.java:282)
at android.security.keystore.AndroidKeyStoreSpi.engineGetKey(AndroidKeyStoreSpi.java:98)
at java.security.KeyStore.getKey(KeyStore.java:825)
at com.google.crypto.tink.integration.android.AndroidKeystoreAesGcm.<init>(AndroidKeystoreAesGcm.java:58)
at com.google.crypto.tink.integration.android.AndroidKeystoreKmsClient.getAead(AndroidKeystoreKmsClient.java:164)
at com.google.crypto.tink.integration.android.AndroidKeysetManager$Builder.readOrGenerateNewMasterKey(AndroidKeysetManager.java:267)
at com.google.crypto.tink.integration.android.AndroidKeysetManager$Builder.build(AndroidKeysetManager.java:236)
at androidx.security.crypto.EncryptedSharedPreferences.create(EncryptedSharedPreferences.java:155)
at androidx.security.crypto.EncryptedSharedPreferences.create(EncryptedSharedPreferences.java:120)
编辑:似乎还有更多类型的异常(exception):
Fatal Exception: com.google.crypto.tink.shaded.protobuf.InvalidProtocolBufferException: Protocol message contained an invalid tag (zero).
at com.google.crypto.tink.shaded.protobuf.GeneratedMessageLite.parsePartialFrom(GeneratedMessageLite.java:1566)
at com.google.crypto.tink.shaded.protobuf.GeneratedMessageLite.parseFrom(GeneratedMessageLite.java:1663)
at com.google.crypto.tink.proto.Keyset.parseFrom(Keyset.java:957)
at com.google.crypto.tink.integration.android.SharedPrefKeysetReader.read(SharedPrefKeysetReader.java:84)
at com.google.crypto.tink.CleartextKeysetHandle.read(CleartextKeysetHandle.java:58)
at com.google.crypto.tink.integration.android.AndroidKeysetManager$Builder.read(AndroidKeysetManager.java:328)
at com.google.crypto.tink.integration.android.AndroidKeysetManager$Builder.readOrGenerateNewKeyset(AndroidKeysetManager.java:287)
at com.google.crypto.tink.integration.android.AndroidKeysetManager$Builder.build(AndroidKeysetManager.java:238)
at androidx.security.crypto.EncryptedSharedPreferences.create(EncryptedSharedPreferences.java:160)
at androidx.security.crypto.EncryptedSharedPreferences.create(EncryptedSharedPreferences.java:120)
Fatal Exception: java.lang.NullPointerException: Attempt to invoke interface method 'android.security.keymaster.OperationResult android.security.IKeystoreService.begin(android.os.IBinder, java.lang.String, int, boolean, android.security.keymaster.KeymasterArguments, byte[], int)' on a null object reference
at android.security.KeyStore.begin(KeyStore.java:501)
at android.security.keystore.AndroidKeyStoreCipherSpiBase.ensureKeystoreOperationInitialized(AndroidKeyStoreCipherSpiBase.java:248)
at android.security.keystore.AndroidKeyStoreCipherSpiBase.engineInit(AndroidKeyStoreCipherSpiBase.java:109)
at javax.crypto.Cipher.tryTransformWithProvider(Cipher.java:2977)
at javax.crypto.Cipher.tryCombinations(Cipher.java:2884)
at javax.crypto.Cipher$SpiAndProviderUpdater.updateAndGetSpiAndProvider(Cipher.java:2789)
at javax.crypto.Cipher.chooseProvider(Cipher.java:956)
at javax.crypto.Cipher.init(Cipher.java:1199)
at javax.crypto.Cipher.init(Cipher.java:1143)
at com.google.crypto.tink.integration.android.AndroidKeystoreAesGcm.encryptInternal(AndroidKeystoreAesGcm.java:84)
at com.google.crypto.tink.integration.android.AndroidKeystoreAesGcm.encrypt(AndroidKeystoreAesGcm.java:72)
at com.google.crypto.tink.integration.android.AndroidKeystoreKmsClient.validateAead(AndroidKeystoreKmsClient.java:248)
at com.google.crypto.tink.integration.android.AndroidKeystoreKmsClient.getAead(AndroidKeystoreKmsClient.java:165)
at com.google.crypto.tink.integration.android.AndroidKeysetManager$Builder.readOrGenerateNewMasterKey(AndroidKeysetManager.java:267)
at com.google.crypto.tink.integration.android.AndroidKeysetManager$Builder.build(AndroidKeysetManager.java:236)
at androidx.security.crypto.EncryptedSharedPreferences.create(EncryptedSharedPreferences.java:155)
at androidx.security.crypto.EncryptedSharedPreferences.create(EncryptedSharedPreferences.java:120)
我试过的
wrap the initialization of EncryptedSharedPreferences with "clear all data if fails" and bite the bullet
.还建议它可能与拥有
android:allowBackup
有关。被禁用(确实如此)。
android:allowBackup
相关?被禁用?
最佳答案
在使用 Jetpack Security EncryptedSharedPreferences(甚至是稳定的)之前要小心这个 Activity 故障,它主要来自外来设备 - https://issuetracker.google.com/issues/176215143?pli=1
唯一肮脏的解决方法是 - https://github.com/google/tink/issues/535#issuecomment-912661574
一旦找到友好的解决方案,我将更新答案。这是解决方法 -
/**
* A builder for creating an encrypted shared preference class.
*/
private const val KEYSTORE_PROVIDER = "AndroidKeyStore"
private const val SHARED_PREFS_FILENAME = "TVPrefs"
@KoinApiExtension
class EncryptedSharedPreferenceBuilder(var context: Context) : KoinComponent {
private val reporter: Reporter by inject()
private val masterKeyAlias =
MasterKey.Builder(context).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build()
fun build(): SharedPreferences {
return try {
createSharedPreferences()
} catch (gsException: GeneralSecurityException) {
reporter.logException(gsException)
Timber.d("EncryptedSharedPref: Error occurred while create shared pref=$gsException")
// There's not much point in keeping data you can't decrypt anymore,
// delete & re-create; user has to start from scratch
deleteSharedPreferences()
createSharedPreferences()
}
}
private fun createSharedPreferences() = EncryptedSharedPreferences.create(
context,
SHARED_PREFS_FILENAME,
masterKeyAlias,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
// Clearing getSharedPreferences using default Preference wrapper.
// This is to work around any key-mismatches that may happen.
fun clearSharedPreference() {
context.getSharedPreferences(SHARED_PREFS_FILENAME, Context.MODE_PRIVATE).edit().clear()
.apply()
}
// Workaround [https://github.com/google/tink/issues/535#issuecomment-912170221]
// Issue Tracker - https://issuetracker.google.com/issues/176215143?pli=1
private fun deleteSharedPreferences() {
try {
val sharedPrefsFile =
File("${context.filesDir.parent}/shared_prefs/$SHARED_PREFS_FILENAME.xml")
// Clear the encrypted prefs
clearSharedPreference()
// Delete the encrypted prefs file
if (sharedPrefsFile.exists()) {
val deleted = sharedPrefsFile.delete()
Timber.d("EncryptedSharedPref: Shared pref file deleted=$deleted; path=${sharedPrefsFile.absolutePath}")
} else {
Timber.d("EncryptedSharedPref: Shared pref file non-existent; path=${sharedPrefsFile.absolutePath}")
}
// Delete the master key
val keyStore = KeyStore.getInstance(KEYSTORE_PROVIDER)
keyStore.load(null)
keyStore.deleteEntry(MasterKey.DEFAULT_MASTER_KEY_ALIAS)
} catch (e: Exception) {
Timber.d("EncryptedSharedPref: Error occurred while trying to reset shared pref=$e")
}
}
}
关于android - 使用 EncryptedSharedPreferences 获取 KeyStoreException 和 GeneralSecurityException,我该如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65463893/
Android 最近发布了 EncryptedSharedPreferences,它自动加密 SharedPreferences 键/值数据。虽然这很好,但我发现我可以简单地挂接到 API 调用并检索
我正在使用 EncryptedSharedPreferences 来存储加密数据。 val biometricManager = BiometricManager.from(this) val has
我正在使用新的 EncryptedSharedPreferences以谷歌推荐的方式上课: private fun securePrefs(context: Context): SharedPrefe
第一个 Activity try { masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC); shar
我使用 androidx.security:security-crypto:1.0.0-alpha02 lib 中的 EncryptedSharedPreferences 来存储一些 token 。如
如何在 Encrypted sharedpreferences 中使用 key 别名? 以下是我的加密共享偏好 KeyGenParameterSpec spec = new KeyGenParamet
使用前加密共享首选项 我的应用程序在 中运行良好发布模式与 (minifyEnabled = true),添加 security library 后 (版本 1.0.0-rc01)我的应用程序在打开时
我正在使用 EncryptedSharedPreferences在本地存储用户信息(如果您不熟悉,请参阅 this)。我已经使用备份规则实现了 AutoBackUp。我备份了首选项,清除了我的应用程序
我是android开发的新手。 目前,我想加密一个名为 Shared Preference 的自定义并与 PreferenceScreen 集成但未能这样做。我正在使用依赖项: androidx.se
所以我正在尝试创建加密共享首选项,如 dev android 端所示:https://developer.android.com/reference/androidx/security/crypto/
在阅读了大量文章和 stackoverflow 帖子后,我找不到使用的具体理由 EncryptedSharedPreferences 或 EncryptedFile 与使用它们的非加密对应部分相比。
背景 在我使用的一个应用程序中,我将重要的东西( token )存储到 EncryptedSharedPreferences 中(取自 here 和 here ): /** a hardware-en
我决定使用 AndroidX 安全库中的新 EncryptedSharedPreferences。由于该应用程序支持 API 21 及更高版本,我决定尝试这个新的 v1.1.0-alpha02 版本,
我是一名优秀的程序员,十分优秀!