一、概述
在用戶模塊,對於用戶密碼的保護,通常都會進行加密。我們通常對密碼進行加密,然后存放在數據庫中,在用戶進行登錄的時候,將其輸入的密碼進行加密然后與數據庫中存放的密文進行比較,以驗證用戶密碼是否正確。
目前,MD5和BCrypt比較流行。相對來說,BCrypt比MD5更安全,但加密更慢。
二、使用BCrypt
首先,可以在官網中取得源代碼
http://www.mindrot.org/projects/jBCrypt/
然后通過Ant進行編譯。編譯之后得到jbcrypt.jar。也可以不需要進行編譯,而直接使用源碼中的java文件(本身僅一個文件)。
下面是官網的一個Demo。
public class BCryptDemo { public static void main(String[] args) { // Hash a password for the first time String password = "testpassword"; String hashed = BCrypt.hashpw(password, BCrypt.gensalt()); System.out.println(hashed); // gensalt's log_rounds parameter determines the complexity // the work factor is 2**log_rounds, and the default is 10 String hashed2 = BCrypt.hashpw(password, BCrypt.gensalt(12));// Check that an unencrypted password matches one that has
// previously been hashed
String candidate = "testpassword";
//String candidate = "wrongtestpassword";
if (BCrypt.checkpw(candidate, hashed))
System.out.println("It matches");
else
System.out.println("It does not match");
}
}
在這個例子中,
BCrypt.hashpw(password, BCrypt.gensalt())
是核心。通過調用BCrypt類的靜態方法hashpw對password進行加密。第二個參數就是我們平時所說的加鹽。
BCrypt.checkpw(candidate, hashed)
該方法就是對用戶后來輸入的密碼進行比較。如果能夠匹配,返回true。
三、加鹽
如果兩個人或多個人的密碼相同,加密后保存會得到相同的結果。破一個就可以破一片的密碼。如果名為A的用戶可以查看數據庫,那么他可以觀察到自己的密碼和別人的密碼加密后的結果都是一樣,那么,別人用的和自己就是同一個密碼,這樣,就可以利用別人的身份登錄了。
其實只要稍微混淆一下就能防范住了,這在加密術語中稱為“加鹽”。具體來說就是在原有材料(用戶自定義密碼)中加入其它成分(一般是用戶自有且不變的因素),以此來增加系統復雜度。當這種鹽和用戶密碼相結合后,再通過摘要處理,就能得到隱蔽性更強的摘要值。