gpt4 book ai didi

java - 如何实现加密的共享偏好设置

转载 作者:行者123 更新时间:2023-12-01 16:26:07 24 4
gpt4 key购买 nike

如何使用https://developer.android.google.cn/reference/androidx/security/crypto/EncryptedSharedPreferences在我的android java应用程序中实现加密的共享首选项?我不知道如何实现,有人可以帮忙吗?

最佳答案

我使用的代码与 @Chirag 编写的代码类似,但在对 Android Studio 4.0 项目应用新的更新后,我收到一条警告,指出 MasterKeys 类已弃用。

所以我找到了this answer它成功了。这是 fragment 中的代码。如果您想在 MainActivity 中使用它,请将 getContext() 更改为 this

 MasterKey getMasterKey() {
try {
KeyGenParameterSpec spec = new KeyGenParameterSpec.Builder(
"_androidx_security_master_key_",
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(256)
.build();

return new MasterKey.Builder(getContext())
.setKeyGenParameterSpec(spec)
.build();
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Error on getting master key", e);
}
return null;
}

private SharedPreferences getEncryptedSharedPreferences() {
try {
return EncryptedSharedPreferences.create(
Objects.requireNonNull(getContext()),
"Your preference file name",
getMasterKey(), // calling the method above for creating MasterKey
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
);
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Error on getting encrypted shared preferences", e);
}
return null;
}

然后你可以像这样使用上面的内容:

   public void someFunction(){
SharedPreferences sharedPreferences = getEncryptedSharedPreferences();
//Used to add new entries and save changes
SharedPreferences.Editor editor = sharedPreferences.edit();

//To add entry to your shared preferences file
editor.putString("Name", "Value");
editor.putBoolean("Name", false);
//Apply changes and commit
editor.apply();
editor.commit();

//To clear all keys from your shared preferences file
editor.clear().apply();

//To get a value from your shared preferences file
String returnedValue = sharedPreferences.getString("Name", "Default value if null is returned or the key doesn't exist");
}

关于java - 如何实现加密的共享偏好设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62144168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com