我认为,如果您将加密保留在已有的SharedPrefs子类中,会限制可维护性和关注点分离。
因此,我建议重新考虑对首选项类(例如CheckBoxPreference)进行子类化,并在那里执行计算。
理想情况下,您还可以使用某种组合或静态工具,这样虽然您可能需要为使用的每种类型的首选项进行子类化,但可以使用单个位置来执行加密/解密计算。这也将允许您在将来更灵活地加密或解密其他数据或者API发生变化时进行调整。
对于子类化,您可以这样做:
例如:
class ListPreferenceCrypt extends ListPreference
{
ListPreferenceCrypt (Context context, AttributeSet attrs) {
super ( context, attrs );
}
ListPreferenceCrypt (Context context) {
super ( context );
}
@Override
public void setValue( String value )
{
String encryptedVal = MyCryptUtil.encrypt(value);
super.setValue ( encryptedVal );
}
@Override
public String getValue( String key )
{
String decryptedValue = MyCryptUtil.decrypt(super.getValue ( key ));
return decryptedValue;
}
}
NOTE the above is psuedo-code, there would be different methods to override
And your XML might look like this:
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="@string/inline_preferences">
<com.example.myprefs.ListPreferenceCrypt
android:key="listcrypt_preference"
android:title="@string/title_listcrypt_preference"
android:summary="@string/summary_listcrypt_preference" />
</PreferenceCategory>
</PreferenceScreen>
EDIT
Caveats/Decompiling
As I thought about this more, I realized one of the caveats is that this method is not particularly difficult to bypass when decompiling an APK. This does give the full class names of overriden classes in the layouts (though that can be avoided by not using XML)
However, I don't think this is significantly less secure than sub-classing SharedPreferences
. That too, is susceptible to decompiling. Ultimately, if you want stronger security, you should consider alternative storage methods. Perhaps OAuth or the AccountManager as suggested in your linked post.
PreferenceFragment
(如果你要支持早于HC的设备,则还需要分叉PreferenceActivity
),以及它们直接引用的所有资源。也有可能这就是“全部”所需的,但我不能排除需要分叉和克隆更多的代码的可能性。 - CommonsWare