private String getSalt() {
long salt = getLong(LOCK_PASSWORD_SALT_KEY, 0);
if (salt == 0) {
try {
salt = SecureRandom.getInstance("SHA1PRNG").nextLong();
setLong(LOCK_PASSWORD_SALT_KEY, salt);
Log.v(TAG, "Initialized lock password salt");
} catch (NoSuchAlgorithmException e) {
// Throw an exception rather than storing a password we'll never be able to recover
throw new IllegalStateException("Couldn't get SecureRandom number", e);
}
}
return Long.toHexString(salt);
}
/*
* Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
* Not the most secure, but it is at least a second level of protection. First level is that
* the file is in a location only readable by the system process.
* @param password the gesture pattern.
* @return the hash of the pattern in a byte array.
*/
public byte[] passwordToHash(String password) {
if (password == null) {
return null;
}
String algo = null;
byte[] hashed = null;
try {
byte[] saltedPassword = (password + getSalt()).getBytes();
byte[] sha1 = MessageDigest.getInstance(algo = "SHA-1").digest(saltedPassword);
byte[] md5 = MessageDigest.getInstance(algo = "MD5").digest(saltedPassword);
hashed = (toHex(sha1) + toHex(md5)).getBytes();
} catch (NoSuchAlgorithmException e) {
Log.w(TAG, "Failed to encode string because of missing algorithm: " + algo);
}
return hashed;
}