Java經過BCrypt加密

1、概述

 

在用戶模塊,對於用戶密碼的保護,一般都會進行加密。咱們一般對密碼進行加密,而後存放在數據庫中,在用戶進行登陸的時候,將其輸入的密碼進行加密而後與數據庫中存放的密文進行比較,以驗證用戶密碼是否正確。javascript

目前,MD5和BCrypt比較流行。相對來講,BCrypt比MD5更安全,但加密更慢。
 
2、使用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。
 
3、加鹽
若是兩我的或多我的的密碼相同,加密後保存會獲得相同的結果。破一個就能夠破一片的密碼。若是名爲A的用戶能夠查看數據庫,那麼他能夠觀察到本身的密碼和別人的密碼加密後的結果都是同樣,那麼,別人用的和本身就是同一個密碼,這樣,就能夠利用別人的身份登陸了。
其實只要稍微混淆一下就能防範住了,這在加密術語中稱爲「加鹽」。具體來講就是在原有材料(用戶自定義密碼)中加入其它成分(通常是用戶自有且不變的因素),以此來增長系統複雜度。當這種鹽和用戶密碼相結合後,再經過摘要處理,就能獲得隱蔽性更強的摘要值。
原文地址:https://www.cnblogs.com/xingzc/p/8624007.html
相關文章
相關標籤/搜索