在将密码保存到本地 android 数据库之前,我需要对其进行加密。没有加密一切正常,我有 preferences.xml 等等。我如何在更改偏好值(例如,密码)后调用函数?这是我的代码:
public class Preferences extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
// Get the custom preference
Preference customPref = (Preference) findPreference("pass");
customPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener(){
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String crypto = SimpleCrypto.encrypt("MYSECRETKEY", newValue.toString()); // encrypt
// Here is where I'm wrong, I guess.
SharedPreferences settings = getSharedPreferences("preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("pass", crypto);
editor.commit();
});
}
}
P.S:像这样,当我更改密码时,它会存储未加密的密码。
最佳答案
我通过扩展基本的 EditTextPreference 并在那里加密/解密密码来做到这一点:
public class EncryptedEditTextPreference extends EditTextPreference {
public EncryptedEditTextPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public EncryptedEditTextPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public EncryptedEditTextPreference(Context context) {
super(context);
}
@Override
public String getText() {
String value = super.getText();
return SecurityUtils.decrypt(value);
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
super.setText(restoreValue ? getPersistedString(null) : (String) defaultValue);
}
@Override
public void setText(String text) {
if (Utils.isStringBlank(text)) {
super.setText(null);
return;
}
super.setText(SecurityUtils.encrypt(text));
}
}
我的个人实用程序有一些调用,但我认为代码非常清楚您需要做什么。
关于android - 在 Android 中保存之前处理偏好值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5858790/