storing credentials in android

試著忘記壹切 提交于 2019-12-03 21:59:41

This can be done using SharedPreferences..

SharedPreferences wmbPreference1,wmbPreference2;    
SharedPreferences.Editor editor;

//wmbPreference for Shared Prefs that lasts forever
wmbPreference1 = PreferenceManager.getDefaultSharedPreferences(this);  

//save_item for Shared Prefs that lasts only just once each time program is running. It is just a name given.
wmbPreference2 =getApplicationContext().getSharedPreferences("save_item",Activity.MODE_PRIVATE);

To save values

SharedPreferences.Editor editor = wmbPreference1.edit();
editor.putString("MYKEY", "12345");
editor.commit();

You can retrieve the values like

String Phonenumber = wmbPreference1.getString("MYKEY", ""); 

where MYKEY is the keyname by which you can identify the value..

Read more about it in the docs here or here

UPDATE

As @adelphus mentioned in his comment, it is always advised to encrypt the passwords before saving it.

in my case i store username and password in sharedprefrences but not usual and unsecured. in addition to @Lal answer i recommend you to use secureSharedPrefrences with this great job and secure method from scottyab, ok for start add this dependencies to your gradle:

com.scottyab:secure-preferences-lib:0.1.1

for extra information from this lib:

This is Android Shared preference wrapper that encrypts the values of Shared Preferences using AES 128, CBC, and PKCS5 padding with integrity checking in the form of a SHA 256 hash. Each key is stored as a one way SHA 256 hash. Both keys and values are base64 encoded before storing into prefs xml file. By default the generated key is stored in the backing preferences file and so can be read and extracted by root user.

so after add dependency to your gradle, create class with this snippet:

public class App extends Application {
protected static App instance;
private SecurePreferences secureAppData;

public App(){
    super();
    instance = this;
}
public static App get() {
    return instance;
}

public SharedPreferences getSharedPreferences() {
    if(secureAppData==null){
        secureAppData = new SecurePreferences(this, null, "my_prefs.xml");
        SecurePreferences.setLoggingEnabled(true);
    }
    return secureAppData;
}

}

in any activity use this snippet for store key

SharedPreferences secureAppData = App.get().getSharedPreferences();
        secureAppData.edit().putString("key",myKey)
                .commit();

and for retrieve use this

secureAppData.getString("key",null)

for those who ask about Application class and theory for that: Sometimes you want to store data, like global variables which need to be accessed from multiple Activities - sometimes everywhere within the application. In this case, the Application object will help you.

maybe this help someone.

adelphus

In response to my comment (and because I couldn't find a simple example in any other SO question), this is a bit of commented code to hash, store and check credentials. If you want to understand salting and password hashing, Wikipedia has some good information.

Saving:

void saveCredentials(String username, String password) {
 /* create some random salt bytes - the value doesn't need to be secret (which is
  why we can save it) but it must be unpredictable and unique per-user */
 SecureRandom sr = new SecureRandom();
 byte[] salt = new byte[16];
 sr.nextBytes(salt);

  // hash the (salt + password)
  // hashing algorithms vary, but for now, SHA256 is a reasonable choice
  try {
     MessageDigest hasher = MessageDigest.getInstance("SHA-256");
     hasher.update(salt);
     hasher.update(password.getBytes("UTF-8"));
     byte[] hashedbytes = hasher.digest();

     // we can now save the salt and the hashed bytes to a file,
     //  SharedPreference or any other storage location
     savedata(username, salt, hashedbytes);

  } catch (Exception e) {
     // do something sensible on errors
  }

}

Checking:

boolean checkPassword(String username, String password) {
  // read the info for the user that we saved in storage
  byte[] salt = readdata(username, "salt");
  byte[] correcthash = readdata(username, "pwdhash");

  // hash the password we are checking in the same way that we did
  // for the original password
  try {
     MessageDigest hasher = MessageDigest.getInstance("SHA-256");
     hasher.update(salt);
     hasher.update(password.getBytes("UTF-8"));
     byte[] testhash = hasher.digest();

     // if the password is correct, the two hashed values will match
     // - if it's wrong, the hashed values will have one or more
     // bytes that do not match
     for (int i=0; i < testhash.length; i++) {
         if (testhash[i] != correcthash[i])
             return false;  // mismatch - wrong password
     }

     // if we reach here, all the hash bytes match, so the password
     // matches the original
     return true;

  } catch (Exception e) {
     // do something sensible on errors
  }

  return false;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!