spring security中的BCryptPasswordEncoder方法採用SHA-256 +隨機鹽+密鑰對密碼進行加密。SHA系列是Hash算法,不是加密算法,使用加密算法意味着可以解密(這個與編碼/解碼一樣),但是採用Hash處理,其過程是不可逆的。
(1)加密(encode):註冊用戶時,使用SHA-256+隨機鹽+密鑰把用戶輸入的密碼進行hash處理,得到密碼的hash值,然後將其存入數據庫中。
(2)密碼匹配(matches):用戶登錄時,密碼匹配階段並沒有進行密碼解密(因爲密碼經過Hash處理,是不可逆的),而是使用相同的算法把用戶輸入的密碼進行hash處理,得到密碼的hash值,然後將其與從數據庫中查詢到的密碼hash值進行比較。如果兩者相同,說明用戶輸入的密碼正確。
保存在數據庫中的用戶密碼是使用SHA-256 +隨機鹽+密鑰對密碼加密後的結果,使用隨機鹽可以確保每次加密的結果不一樣而進行密碼匹配的時候只需要比較密碼的hash值,其他的不在比較範圍之內。
測試見測
用戶註冊時對密碼進行加密
@RequestMapping("/add")
public Result add(@RequestBody TbSeller seller){
try {
//密碼加密
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
seller.setPassword(encoder.encode(seller.getPassword()));
// 添加默認的字段信息
// 0 表示未審覈
seller.setStatus("0");
// 申請時間
seller.setCreateTime(new Date());
sellerService.add(seller);
return new Result(true, "增加成功");
} catch (Exception e) {
e.printStackTrace();
return new Result(false, "增加失敗");
}
}
對spring-security.xml進行修改,確保登錄時對用戶輸入的密碼進行加密操作
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<!-- 以下資源不被攔截 -->
<http pattern="/css/**" security="none"/>
<http pattern="/img/**" security="none"/>
<http pattern="/js/**" security="none"/>
<http pattern="/plugins/**" security="none"/>
<http pattern="/seller/add.do" security="none"/>
<http pattern="/*.html" security="none"/>
<!-- 頁面攔截規則 -->
<http use-expressions="false">
<intercept-url pattern="/**" access="ROLE_SELLER" />
<form-login login-page="/shoplogin.html"
default-target-url="/admin/index.html" authentication-failure-url="/shoplogin.html"
always-use-default-target="true" />
<csrf disabled="true" />
<headers>
<frame-options policy="SAMEORIGIN" />
</headers>
<logout />
</http>
<!-- 認證管理器 -->
<authentication-manager>
<authentication-provider user-service-ref="userDetailService">
<password-encoder ref="bcryptEncoder"/>
</authentication-provider>
</authentication-manager>
<!-- 定義自定義認證類 -->
<beans:bean id="userDetailService" class="com.offcn.service.UserDetailsServiceImpl"/>
<!--密碼加密處理類-->
<beans:bean id="bcryptEncoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />
</beans:beans>