在前一节使用数据库进行用户认证(form login using database)里,我们学习了如何把“登录帐号、密码”存储在db中,但是密码都是明文存储的,显然不太讲究。这一节将学习如何使用spring security3新加入的bcrypt算法,将登录加密存储到db中,并正常通过验证。
一、Bcrypt算法
1 int t = 0; 2 String password = "123456"; 3 System.out.println(password + " -> "); 4 for (t = 1; t <= 10; t++) { 5 BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); 6 String hashedPassword = passwordEncoder.encode(password); 7 System.out.println(hashedPassword); 8 } 9 10 password = "MIKE123"; 11 System.out.println(password + " -> "); 12 for (t = 1; t <= 10; t++) { 13 BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); 14 String hashedPassword = passwordEncoder.encode(password); 15 System.out.println(hashedPassword); 16 }
输出如下:
123456 ->
MIKE123 ->
从以上输出结果发现bcrypt算法与md5/sha算法有一个很大的区别,每次生成的hash值都是不同的,这样暴力猜解起来或许要更困难一些。同时大家可能也发现了,加密后的字符长度比较长,有60位,所以用户表中密码字段的长度,如果打算采用bcrypt加密存储,字段长度不得低于60.
二、spring-security.xml
1 2 xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://www.springframework.org/schema/beans 4 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 5 http://www.springframework.org/schema/security 6 http://www.springframework.org/schema/security/spring-security-3.2.xsd"> 7 8 9 10 11 12 13 authentication-failure-url="/login?error" username-parameter="username" 14 password-parameter="password" /> 15 16 17 18 19 20 21 22 23 24 25 users-by-username-query="select d_username username,d_password password, d_enabled enabled from t_users where d_username=?" 26 authorities-by-username-query="select d_username username, d_role role from t_user_roles where d_username=? " /> 27 28 29 30 31 class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"> 32 33 34 35
复制代码
对比上一节的内容,只是增加23行、30-33行
最后要做的事情,就是把db中原来明文的密码值,改成经过bcrypt加密后的字符串即可。
tips:如果你仍然喜欢用传统的sha算法来处理密码,只要把23行改成