1.前言
* BCryptPasswordEncoder相關知識:
* 用戶表的密碼通常使用MD5等不可逆算法加密后存儲,為防止彩虹表破解更會先使用一個特定的字符串(如域名)加密,然后再使用一個隨機的salt(鹽值)加密。
* 特定字符串是程序代碼中固定的,salt是每個密碼單獨隨機,一般給用戶表加一個字段單獨存儲,比較麻煩。
* BCrypt算法將salt隨機並混入最終加密后的密碼,驗證時也無需單獨提供之前的salt,從而無需單獨處理salt問題。
*
與他類似的 加密方法還有 SCryptPasswordEncoder 等
出現問題 : 報錯 java.lang.NoClassDefFoundError: org/bouncycastle/crypto/generators/SCrypt
2.解決
需要導入依賴包即可
<!-- SCryptPasswordEncoder 加密需要使用--> <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15on</artifactId> <version>1.64</version> </dependency>
3.加密測試【因為是單向加密,故無法解密,只能使用內置的方法比較】
import org.junit.Test; import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder; public class t { @Test public void t2(){
//加密
String s = (new SCryptPasswordEncoder()).encode("11");
System.out.println(s);
//字符長度
System.out.println(s.length());
//解密
if ((new SCryptPasswordEncoder()).matches("11",s)){
System.out.println("密碼一樣");
}else {
System.out.println("密碼不一樣");
}
} }
運行結果 ,【 長度140】
4.其他
其他類似 SCryptPasswordEncoder 的加密方式還有
- BCryptPasswordEncoder【一樣的用法 ,長度60,推薦使用】
- Pbkdf2PasswordEncoder 【一樣的用法 ,長度80】
- StandardPasswordEncoder 【一樣的用法 ,長度80,這個已被淘汰,但是還能用,不建議使用】
分別需要的包
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;