SpringBoot整合BCrypt實現密碼加密

本文實例為大傢分享瞭SpringBoot整合BCrypt實現密碼加密的具體代碼,供大傢參考,具體內容如下

一. 首先在pom依賴中加入依賴:

<!-- security依賴包 (加密) -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
</dependency>

二.在啟動類中加入@EnableScheduling註解,獲得BCrypt支持:

package com.zzx;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
//獲得BCrypt支持
@EnableScheduling
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }


}

三.模擬獲得登錄密碼:

package com.zzx.test;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @date: 2021/11/25/ 14:30
 * @author: ZhengZiXuan
 * @title: 使用BCrypt進行密碼加密
 * @description: 引入Security依賴默認開啟瞭登錄校驗,訪問API會跳轉到登錄頁,如果隻是需要BCrypt加密功能可以在啟動類配置@SpringBootApplication (exclude = { org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class })禁用Security相關功能。
 */
public class BCryptTest {
    public static void main(String[] args) {
        //模擬從前端獲得的密碼
        String password = "123456";
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String newPassword = bCryptPasswordEncoder.encode(password);
        System.out.println("加密的密碼為: "+newPassword);
        boolean same_password_result = bCryptPasswordEncoder.matches(password,newPassword);
        //返回true
        System.out.println("相同代碼對比: "+same_password_result);
        boolean other_password_result = bCryptPasswordEncoder.matches("1234456",newPassword);
        //返回false
        System.out.println("其他密碼對比: " + other_password_result);
    }
}

運行結果如下:

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: