<span style="font-size:14px;">为了更好的用户体验,移动APP客户端一般都会将用户信息进行保存以便后续可以自动登录.</span>
保存了用户信息便涉及到了安全问题.
解决的方法大概有一下几种:
1.首先,如果客户端和服务端都是你来设计开发,那么有两种比较可靠的方案
A.客户端将密码Hash加密,登录成功后将hash值保存到Sqlite.服务端得到用户名和hash值,采用同样的算法对密码进行Hash运算,然后和用户传来的hash值进行比较,一致则登录成功.更加可靠的是对密码加盐加密.例如可以采用PBKDF2加盐加密.
<span style="font-size:14px;">public static String createHash(String password)
throws NoSuchAlgorithmException, InvalidKeySpecException {
return createHash(password.toCharArray());
}
/**
* Returns a salted PBKDF2 hash of the password.
*
* @param password
* the password to hash
* @return a salted PBKDF2 hash of the password
*/
public static String createHash(char[] password)
throws NoSuchAlgorithmException, InvalidKeySpecException {
// Generate a random salt
SecureRandom random = new SecureRandom();
byte[] salt = new byte[SALT_BYTE_SIZE];
random.nextBytes(salt);
// Hash the password
byte[] hash = pbkdf2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);
return PBKDF2_ITERATIONS + ":" + toHex(salt) + ":" + toHex(hash);
}</span>1000为迭代的次数,后面分别是salt和hash值.
服务端得到这个字符串后,从中解析出迭代次数,salt,hash1值,然后采用同样的算法对数据库里面的密码进行计算
public static boolean validatePassword(String password, String correctHash)
throws NoSuchAlgorithmException, InvalidKeySpecException {
return validatePassword(password.toCharArray(), correctHash);
}
/**
* Validates a password using a hash.
*
* @param password
* the password to check
* @param correctHash
* the hash of the valid password
* @return true if the password is correct, false if not
*/
public static boolean validatePassword(char[] password, String correctHash)
throws NoSuchAlgorithmException, InvalidKeySpecException {
// Decode the hash into its parameters
String[] params = correctHash.split(":");
int iterations = Integer.parseInt(params[ITERATION_INDEX]);
byte[] salt = fromHex(params[SALT_INDEX]);
byte[] hash = fromHex(params[PBKDF2_INDEX]);
// Compute the hash of the provided password, using the same salt,
// iteration count, and hash length
byte[] testHash = pbkdf2(password, salt, iterations, hash.length);
// Compare the hashes in constant time. The password is correct if
// both hashes match.
return slowEquals(hash, testHash);
}
B.使用非对称加密算法对密码进行加密.
原文地址:http://blog.csdn.net/leokelly001/article/details/44454723