SpringBoot整合BCrypt进行密码加密

该博客介绍了如何在Spring Boot应用中集成Spring Security的BCryptPasswordEncoder进行密码加密。首先,在pom.xml文件中添加了spring-security-web和spring-security-config的依赖。接着,在启动类中启用@EnableScheduling注解以支持BCrypt。然后,通过BCryptTest类展示了如何使用BCrypt对密码进行加密和验证。最后,提供了模拟登录密码加密的示例代码及其运行结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一. 首先在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);
    }
}

运行结果如下:

在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小郑要做干饭人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值