在我的应用程序中,我必须保存用户名、密码、 token ...以重用它们。最初我将这些数据保存在正常的共享首选项中,但在 Root设备上很容易读取所有首选项,我认为这不是一件好事。
现在我正在尝试使用 SecurePreferences 库 ( this ),但如果我以这种方式初始化此首选项:
SharedPreferences prefs = new SecurePreferences(context);
当我在 onCreateView 上打开一个 Activity 或 fragment 时,初始化通常需要大约 2-3 秒(我使用 TraceView 对其进行了测试),这会减慢我的 Activity 或 fragment 打开速度。
有一种方法可以将 SecurePreferences 放入单例中,并在我的所有应用程序中只实例化一次吗? 或者还有另一种最佳方法来保存这些数据并将它们隐藏到所有外部应用程序中?
更新 #1:
我找到了这个解决方案。要仅实例化 SecurePreferences 一次,您应该创建一个以这种方式扩展 Application 的 App 类:
public class App extends Application {
private static final String TAG = "secureprefsample";
protected static App instance;
private SecurePreferences mSecurePrefs;
private SecurePreferences mUserPrefs;
public App(){
super();
instance = this;
}
public static App get() {
return instance;
}
/**
* Single point for the app to get the secure prefs object
* @return
*/
public SharedPreferences getSharedPreferences() {
if(mSecurePrefs==null){
mSecurePrefs = new SecurePreferences(this, "", "my_prefs.xml");
SecurePreferences.setLoggingEnabled(true);
}
return mSecurePrefs;
}
/**
* This is just an example of how you might want to create your own key with less iterations 1,000 rather than default 10,000. This makes it quicker but less secure.
* @return
*/
public SharedPreferences getSharedPreferences1000() {
try {
AesCbcWithIntegrity.SecretKeys myKey = AesCbcWithIntegrity.generateKeyFromPassword(Build.SERIAL,AesCbcWithIntegrity.generateSalt(),1000);
SharedPreferences securePrefs1000 = new SecurePreferences(this, myKey, "my_prefs_1000.xml");
return securePrefs1000;
} catch (GeneralSecurityException e) {
Log.e(TAG, "Failed to create custom key for SecurePreferences", e);
}
return null;
}
public SharedPreferences getDefaultSharedPreferences() {
return PreferenceManager.getDefaultSharedPreferences(this);
}
public SecurePreferences getUserPinBasedSharedPreferences(String password){
if(mUserPrefs==null) {
mUserPrefs = new SecurePreferences(this, password, "user_prefs.xml");
}
return mUserPrefs;
}
public boolean changeUserPrefPassword(String newPassword){
if(mUserPrefs!=null){
try {
mUserPrefs.handlePasswordChange(newPassword, this);
return true;
} catch (GeneralSecurityException e) {
Log.e(TAG, "Error during password change", e);
}
}
return false;
}
然后您必须以这种方式在您的 Activity 中获取 SecurePreferences:
SharedPreferences preferences =App.get().getSharedPreferences();
最佳答案
你可能想试试 https://prashantsolanki3.github.io/Secure-Pref-Manager/轻松安全地共享首选项。 您可以使用给定的 AES 加密或实现您自己的加密算法。
添加新首选项的示例代码:
SecurePrefManager.with(this)
.set("user_name")
.value("LoremIpsum")
.go();
关于android - 安全共享首选项android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33424187/