Skip to content

Instantly share code, notes, and snippets.

@s3va
Created July 24, 2020 00:00
Show Gist options
  • Save s3va/bf048ef7b3eb1ba568c0071ad2deea8d to your computer and use it in GitHub Desktop.
Save s3va/bf048ef7b3eb1ba568c0071ad2deea8d to your computer and use it in GitHub Desktop.
EncryptedSharedPreferences
final String userNameShPr="userNameShPr";
final String passwordShPr="passWordShPr";
final String checkBoxShPr="checkBoxShPr";
final String SHARED_PREFERENCES_FNAME = "secret_shared_prefs";
MasterKey masterKey = new
MasterKey.Builder(this,MasterKey.DEFAULT_MASTER_KEY_ALIAS).
setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build();
SharedPreferences sharedPreferences = EncryptedSharedPreferences
.create(
this,
SHARED_PREFERENCES_FNAME,
masterKey,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
);
if(sharedPreferences.getBoolean(checkBoxShPr,false)&&sharedPreferences.contains(userNameShPr)) {
etLogin.setText(sharedPreferences.getString(userNameShPr, ""));
checkBox.setChecked(true);
}
if(sharedPreferences.getBoolean(checkBoxShPr,false)&&sharedPreferences.contains(passwordShPr))
etKey.setText(sharedPreferences.getString(passwordShPr,""));
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
if(checkBox.isChecked()) {
sharedPreferencesEditor.putString(userNameShPr,etLogin.getText().toString());
sharedPreferencesEditor.putString(passwordShPr,etKey.getText().toString());
sharedPreferencesEditor.putBoolean(checkBoxShPr,true);
}else{
sharedPreferencesEditor.putBoolean(checkBoxShPr,false);
sharedPreferencesEditor.remove(userNameShPr);
sharedPreferencesEditor.remove(passwordShPr);
}
sharedPreferencesEditor.apply();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment