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的用户能够查看数据库,那么他能够观察到本身的密码和别人的密码加密后的结果都是同样,那么,别人用的和本身就是同一个密码,这样,就能够利用别人的身份登陆了。
其实只要稍微混淆一下就能防范住了,这在加密术语中称为“加盐”。具体来讲就是在原有材料(用户自定义密码)中加入其它成分(通常是用户自有且不变的因素),以此来增长系统复杂度。当这种盐和用户密码相结合后,再经过摘要处理,就能获得隐蔽性更强的摘要值。