如何使用https://developer.android.google.cn/reference/androidx/security/crypto/EncryptedSharedPreferences在我的android java应用程序中实现加密的sharepreferences?我不知道如何实现它,任何人都可以提供帮助?
答案 0 :(得分:1)
我使用的代码类似于@Chirag编写的代码,但是在将新更新应用于Android Studio 4.0项目之后,我收到警告,提示MasterKeys
类已弃用。
因此,我找到了this answer,它成功了。这是片段中的代码。如果要在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");
}
答案 1 :(得分:0)
根据文档示例,您可以像这样初始化EncryptedSharedPreferences
。
public SharedPreferences getEncryptedSharedPreferences(){
String masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);
SharedPreferences sharedPreferences = EncryptedSharedPreferences.create(
"secret_shared_prefs_file",
masterKeyAlias,
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
);
return sharedPreferences;
}
保存数据
getEncryptedSharedPreferences().edit()
.putString("key", value)
.apply()
获取数据
getEncryptedSharedPreferences().getString("key", "defaultValue");
确保您的应用程序API版本为23+,并且需要添加此依赖项
implementation "androidx.security:security-crypto:1.0.0-alpha02" //Use latest version