Spring Security:PasswordEncoder密码加密匹配操作

这篇具有很好参考价值的文章主要介绍了Spring Security:PasswordEncoder密码加密匹配操作。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

目录

PasswordEncoder

SpringBoot:注入BSryptPasswordEncoder实例

BSryptPasswordEncoder详解

父接口PasswordEncoder

BSryptPasswordEncoder及其使用

成员方法

SecurityUtils安全服务工具类

测试代码


PasswordEncoder

Spring Security:PasswordEncoder密码加密匹配操作

        PasswordEncoder是Spring Security框架默认使用的密码加密器,对应的数据表sys_user的密码password字段需要以明文存储,并且要加上前缀{noop}password,否则就会抛出异常java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"(如下图所示),这样使用起来是极其不方便的,但是,Spring Security也允许我们自己替换这个默认使用的PasswordEncoder

Spring Security:PasswordEncoder密码加密匹配操作 

 SpringBoot:注入BSryptPasswordEncoder实例

        在实际开发中,我们一般使用spring security框架中提供的BSryptPasswordEncoder

因此,只需要将BSryptPasswordEncoder对象注入到Spring容器中,Spring Security就会使用该对象替换掉默认使用的PasswordEncoder对象,来进行密码校验。

        所以,接下来的工作,就是定义一个SpringSecurityConfig配置类(SpringSecurity框架要求这个配置类需要继承WebSecurityConfigureAdapter)。示例代码如下,

package com.xwd.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    //properties

    //methods

    /**
     * 注入Bean实例
     * @return BCryptPasswordEncoder实例
     */
    @Bean
    public PasswordEncoder getBCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

BSryptPasswordEncoder详解

父接口PasswordEncoder

Spring Security:PasswordEncoder密码加密匹配操作

    PasswordEncoderSpring Security框架默认使用的密码加密器。但是Spring Security框架也提供了多个具体的实现子类(如上图所示)。

/**
 * Service interface for encoding passwords.
 *
 * The preferred implementation is {@code BCryptPasswordEncoder}.
 *
 * @author Keith Donald
 */
public interface PasswordEncoder {
    ...
}

        其中,Spring Security框架源码中建议:在开发中,首选BCryptPasswordEncoder进行使用。

public interface PasswordEncoder {

	/**
	 * Encode the raw password. Generally, a good encoding algorithm applies a SHA-1 or
	 * greater hash combined with an 8-byte or greater randomly generated salt.
	 */
	String encode(CharSequence rawPassword);

	/**
	 * Verify the encoded password obtained from storage matches the submitted raw
	 * password after it too is encoded. Returns true if the passwords match, false if
	 * they do not. The stored password itself is never decoded.
	 * @param rawPassword the raw password to encode and match
	 * @param encodedPassword the encoded password from storage to compare with
	 * @return true if the raw password, after encoding, matches the encoded password from
	 * storage
	 */
	boolean matches(CharSequence rawPassword, String encodedPassword);

	/**
	 * Returns true if the encoded password should be encoded again for better security,
	 * else false. The default implementation always returns false.
	 * @param encodedPassword the encoded password to check
	 * @return true if the encoded password should be encoded again for better security,
	 * else false.
	 */
	default boolean upgradeEncoding(String encodedPassword) {
		return false;
	}
}

        而PasswordEncoder接口中只提供了3个待实现的抽象方法(源码如上),分别如下,

[1] String encode(CharSequence rawPassword);
    密码加密:通常地,一个好的加密算法可以是`SHA-1`或者更大的hash与8字节、或者更大的随机生成盐的组合。
    
[2] boolean matches(CharSequence rawPassword, String encodedPassword);    
    其中:rawPassword对应用户提交的密码;encodedPassword对应正确密码编码后得到的字符串。
    密码校验:校验密码编码后的字符串,与用户登录时提交的密码是否匹配,返回一个boolean布尔值表示是否校验通过。

[3] default boolean upgradeEncoding(String encodedPassword) {
        return false;
    }

    如果为了更好的安全性,应当对一次编码后的密码进行二次编码,返回一个boolean值标识是否进行了二次编码。

BSryptPasswordEncoder及其使用

成员方法

   BCryptPasswordEncoderPasswordEncoder的实现子类:使用了BCrypt强散列函数。客户端可以选择性的提供一个版本号(version,可选值:$2a, $2b, $2y)和一个加密强度(strength,可选值:a.k.a. log rounds in BCrypt),以及一个SecureRandom实例。

   strength加密强度默认值为10,值越大,安全性就越可靠。

        除了对PasswordEncoder接口提供的3个方法做了实现之外,也提供了用于获取加密盐的方法getSalt()

	private String getSalt() {
		if (this.random != null) {
			return BCrypt.gensalt(this.version.getVersion(), this.strength, this.random);
		}
		return BCrypt.gensalt(this.version.getVersion(), this.strength);
	}

SecurityUtils安全服务工具类

        在实际开发中使用时,面向密码加密、密码匹配两项操作,参考若依框架中:SecurityUtils安全服务工具类的写法,摘录代码如下,    

        PS:可以看到,BCryptPasswordEncoder类在使用时,主要还是调用密码加密方法encode()密码匹配/校验方法matchesPassword()

 /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password)
    {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword 真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword)
    {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

测试代码


@SpringBootTest
@RunWith(SpringRunner.class)
public class SpringBoot_Demo_Test {
    //properties
    @Autowired
    @Qualifier(value = "BCryptPasswordEncoder") //Bean实例注入已经在本部分开头进行介绍
    private PasswordEncoder passwordEncoder;

    //methods

    @Test
    public void BCryptPasswordEncoder_test(){
        /**
         * 即使是相同的密码,BCryptPasswordEncoder每次的加密结果也是不同的
         * 原因在于:BCryptPasswordEncoder每次加密时都会使用一个随机的加密盐,产生不同的加密结果
         */
        String encode = passwordEncoder.encode("123456");//密码加密操作-将加密之后的结果存储到数据库中
        String encode1 = passwordEncoder.encode("123456");
        System.out.println(encode); // $2a$10$J0HqjTj2g98KceRapnRqW.Y4uQkPzGASFstgx1yba2JQG1muHj7L2
        System.out.println(encode1); //$2a$10$foxH4yrARWiaWwxyTXjFMOkSqkiOXsMaiQ6/oWbxxond5/BZqi1ke

        /**
         * 密码校验-虽然每次加密的结果不同,但是只要是由原来的密码加密过来的字符串,匹配时也都会返回true
         * 参数1:用户登录时输入的结果;参数2:正确的加密后的密码
         */
        boolean matches = passwordEncoder.matches("123456", "$2a$10$foxH4yrARWiaWwxyTXjFMOkSqkiOXsMaiQ6/oWbxxond5/BZqi1ke");
        System.out.println("检验结果:"+matches); //检验结果:true

    }
}

Spring Security:PasswordEncoder密码加密匹配操作

 文章来源地址https://www.toymoban.com/news/detail-426258.html

到了这里,关于Spring Security:PasswordEncoder密码加密匹配操作的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Spring Security自定义登陆界面和密码验证逻辑

    目录 1添加maven依赖 2创建配置文件处理跳转拦截等功能以及密码比对功能 3创建userservice 4自定义登陆界面login.html 上面的UserDateService 中我们固定返回一个用户名密码为admin        123的user类 然后security的configure(AuthenticationManagerBuilder auth)进行密码对比,注意这里只是比较密码

    2024年02月13日
    浏览(33)
  • 系列三、Spring Security中自定义用户名/密码

    1.1.1、配置文件中配置 1.1.2、定义基于内存的用户 1.1.3、基于UserDetailService接口定义用户 概述:         Spring Security支持多种数据源,例如内存、数据库、LDAP等,这些不同来源的数据被共同封装成了UserDetailService接口,换句话说任何实现了UserDetailService接口的对象都可以作为

    2024年01月19日
    浏览(26)
  • Spring-Security+OAuth2+redis实现密码登录

    一、OAuth2认证模式         一共四种认证方式,授权码模式、密码模式、简化模式和客户端模式。实现单点登录,比较流行的方法是使用jwt方式,jwt是无状态的,其本身就能携带信息,因此服务端可以不用保存他的信息,但只要token不过期,用户就可以一直访问,这样就无

    2024年02月16日
    浏览(28)
  • 新版Spring Security6.2案例 - Authentication用户名密码

    前面有翻译了新版Spring Security6.2架构,包括总体架构,Authentication和Authorization,感兴趣可以直接点链接,这篇翻译官网给出的关于Authentication的Username/Password这页。 首先呢,官网就直接给出了基于用户名和密码的认证的代码,可以说是spring security的一个入门小案例,表单登录

    2024年02月20日
    浏览(35)
  • Spring Boot使用jasypt处理数据库账号密码等数据加密问题

    在我们业务场景中,项目中的application.yml 配置文件比如数据库账号密码,的各种链接的username,password的值都是明文的,存在一定的安全隐患,可以使用jasypt 加密框架的方式进行明文加密,进而使得我们项目更加安全 注意这里排除了mybatis-plus的包可能是项目中有冲突依赖,

    2024年02月06日
    浏览(42)
  • 【Spring Security】使用 OncePerRequestFilter 过滤器校验登录过期、请求日志等操作

    OncePerRequestFilter 是一个过滤器,每个请求都会执行一次;一般开发中主要是做检查是否已登录、Token是否过期和授权等操作,而每个操作都是一个过滤器,下面演示一下。 检查是否登录过期过滤器 检查是否登录过期过滤器 End

    2024年02月10日
    浏览(54)
  • Spring Boot学习随笔- Jasypt加密数据库用户名和密码以及解密

    学习视频:【编程不良人】2021年SpringBoot最新最全教程 Jasypt 全称是Java Simplified Encryption,是一个开源项目。 Jasypt与Spring Boot集成,以便在应用程序的属性文件中加密敏感信息,然后在应用程序运行时解密这些信息。 可以使用 jasypt-spring-boot-starter 这个依赖项。从而实现属性源

    2024年02月04日
    浏览(54)
  • 密码学学习笔记(二):对称加密(二) IND-CPA、IND-CCA安全以及分组密码操作模式

    书接上篇笔记,假设声称对手可以在给定我们方案的密文的情况下找出明文的第一位。我们如何检验这一说法? 通过加密以0或1开头的明文生成密文 将密文交给对手,等待对手决定是哪种情况,检查决定是否正确 不可区分性:  如果我们想模拟任何泄漏怎么办? 为了模拟任

    2024年02月04日
    浏览(45)
  • .Net 加密解密组件工具类 System.Security.Cryptography.Algorith

            在.NET Framework出现之前,如果我们需要进行加密的话,我们只有各种较底层的技术可以选择,如Microsoft Crypto API、Crypto++、Openssl等等,其用法相当复杂。而在 .NET Framework中,这些复杂内容(原来独立的API和SDK)已经被封装合并在一个.NET框架类中,这对于程序开发人员

    2024年02月04日
    浏览(33)
  • 【Spring Security】Spring Security 认证与授权

    在前面的章节中,我们沿用了Spring Security默认的安全机制:仅有一个用户,仅有一种角色。在实际开发中,这自然是无法满足需求的。本章将更加深入地对Spring Security迚行配置,且初步使用授权机制。 3.1 默认数据库模型的认证与授权 3.1.1、资源准备 首先,在controller包下新建

    2024年02月05日
    浏览(43)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包