spring security 5 (8)-密码加密BCryptPasswordEncoder

从spring security5开始,要求必须手动配置密码加密方式,spring官方推荐使用BCrypt加密,并明确指出sha和md5都是不安全的。本篇仅介绍BCrypt的用法。

BCrypt加密与验证

		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
   		String result = encoder.encode("123");	//注册时,对密码123加密,结果将保存到数据库
		encoder.matches("123", result);	//登录时,从数据库读取密文,验证密码是否是123

基本配置

password方法参数就是上面加密过result,此时在登录界面输入密码123,将使用上面的matches方法验证密码。

	public void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.inMemoryAuthentication()
			.withUser("user").password("$2a$10$89rbg/..2V1hoRzXtlDa9ejjIzsqeO.kQgmkQnAa//xDzJLoyJgAu").authorities("auth")
				.and()
			.passwordEncoder(new BCryptPasswordEncoder());//配置BCrypt加密
	}

passwordEncoder配置也可以换成以下方式

	@Bean
	public BCryptPasswordEncoder passwordEncoder() {
	    return new BCryptPasswordEncoder();
	}

兼容多种密码

假如以前我们数据库中的用户密码没有加密,或用别的方式加密,现在系统升级,新用户都使用BCrypt加密。

	public void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.inMemoryAuthentication()
			.withUser("user").password("{bcrypt}$2a$10$89rbg/..2V1hoRzXtlDa9ejjIzsqeO.kQgmkQnAa//xDzJLoyJgAu").authorities("auth").and()
			.withUser("old").password("{noop}123").authorities("old");

此时不需要再设置passwordEncoder,而是在密码中加上前缀进行区分。如以前的用户old,给其密码加上前缀{noop},表示未加密。新用户密码前缀为{bcrypt},表示bcrypt加密。系统为根据前缀自动识别你的加密方式。在自认定认证中,同样可以根据前缀判断加密方式。

BCrypt密文解析

在密文中包含四段内容,$是分隔符。

2a:加密算法版本号。

10:加密轮次,默认为10,数值越大,加密时间和越难破解呈指数增长。可在BCryptPasswordEncoder构造参数传入。

第3个$之后:前面的内容是盐,后面的内容才是真正的密文。

以下方式可以更清晰的看出盐和全文。

		String salt = BCrypt.gensalt();	//盐  默认参数轮次10
		String result = BCrypt.hashpw("123", salt);//全文
		System.out.println(salt);	
		System.out.println(result);

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值