软件编程
位置:首页>> 软件编程>> java编程>> SpringBoot整合BCrypt实现密码加密

SpringBoot整合BCrypt实现密码加密

作者:小郑要做干饭人  发布时间:2021-12-09 20:01:08 

标签: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);
   }
}

运行结果如下:

SpringBoot整合BCrypt实现密码加密

来源:https://blog.csdn.net/a1422655169/article/details/121544107

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com