Spring security中的BCryptPasswordEncoder方法對密碼進行加密與密碼匹配
阿新 • • 發佈:2020-09-09
1.BCryptPasswordEncoder使用之前要加入依賴
如果是SSM加入的依賴
<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>5.1.4.RELEASE</version> </dependency>
如果是SpringBoot加入的依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring‐boot‐starter‐security</artifactId> </dependency>
BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder(); 加密: bcryptPasswordEncoder.encode(password); //password是輸入的密碼,encodedPassword是通過bcryptPasswordEncoder進行加密的密碼 解密: bcrytPasswordEncoder.matches(password,encodedPassword)
測試:
package com.qingfeng.service.impl; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; public class Test { public static void main(String[] args) { String password = "123456"; BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder(); //加密:bcryptPasswordEncoder進行密碼加密 String encodedPassword = bcryptPasswordEncoder.encode(password); System.out.println("bcryptPasswordEncoder進行密碼加密:"+encodedPassword); //解密: boolean flag = bcryptPasswordEncoder.matches(password, encodedPassword); //如果flag為true,則解密成功 false,則解密失敗 System.out.println("解密:"+flag); } }
測試結果:
bcryptPasswordEncoder進行密碼加密:$2a$10$z1l7KwMFGthgsNOg6h0I4OVTUUyhC11paX1PN8glw7bT3tL4feZ1u 解密:true