<span style="font-size:14px;">為了更好的用戶體驗,移動APPclient一般都會將用戶信息進行保存以便興許能夠自己主動登錄.</span>
保存了用戶信息便涉及到了安全問題.
解決辦法大概有一下幾種:
1.首先,假設client和服務端都是你來設計開發,那么有兩種比較可靠的方案
A.client將passwordHash加密,登錄成功后將hash值保存到Sqlite.服務端得到username和hash值,採用相同的算法對password進行Hash運算,然后和用戶傳來的hash值進行比較,一致則登錄成功.更加可靠的是對password加鹽加密.比如能夠採用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 saltSecureRandom random = new SecureRandom();byte[] salt = new byte[SALT_BYTE_SIZE];random.nextBytes(salt);// Hash the passwordbyte[] hash = pbkdf2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);return PBKDF2_ITERATIONS + ":" + toHex(salt) + ":" + toHex(hash);}</span>
加密后的字符串為1000:1507039de0a3c2c88ddf896233278e37d05fd8a0fadc570d:99222374678d4afe5d7d9bf9be4786e17f045ac217c6a2ca,
1000為迭代的次數,后面各自是salt和hash值.
服務端得到這個字符串后,從中解析出迭代次數,salt,hash1值,然后採用相同的算法對數據庫里面的password進行計算
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 parametersString[] 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 lengthbyte[] 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.使用非對稱加密算法對password進行加密.
- client使用公鑰加密password,得到加密串,然后將其發送到服務端.
- 服務端使用私鑰解密password。進行驗證,
- 登錄成功后,client將加密串保存到本地,便于下次自己主動登錄;
使用非對稱加密比較可靠。即使加密串被泄露也無法得到password.
2.假設你僅僅是負責client。對服務端無能為力,那么你可能僅僅能使用對稱加密了.(如你正在為學校圖書館寫個client。你還想設置自己主動登錄。那么你本地僅僅能使用對稱加密了,將加密串保存到本地。然后下次自己主動登錄時。從數據庫取出加密串然后解密...服務端僅僅識別原始的password)
這樣的情況。你僅僅能考慮怎樣生成加密密鑰,以及怎樣保存密鑰,怎樣混淆.
考慮了一種方法:
加解密函數 DES(passwd,key,encode);
str1 = ?DES(passwd,key,encode);
str2 = ?DES(key,str1,encode);
本地數據庫中保存 str1:str2.
解密時,str2以str1解密得到key.
然后。str1以key解密得到passwd.
非對稱加密僅僅能以這樣的邏輯上的復雜度添加password的強度.
3. 使用JNI加解密。
另參考文章:
http://blog.csdn.net/hengyunabc/article/details/34623957
android中使用jni對字符串加解密實現分析
加鹽password哈希:怎樣正確使用