RSA sm2 md5都是加密方式
md5相同的密码每次加密都一样,不太安全,在md5的基础上手动加盐(salt)处理
//uername:zhangsan password:123 salt:随时字符串
String salt = RandomStringUtils.randomAlphanumeric(10);//获取一个10位的随机字符串
System.out.println(salt);
String pswd = "123"+salt;
String saltPswd = DigestUtils.md5DigestAsHex(pswd.getBytes());
System.out.println(saltPswd);
这样同样的密码,加密多次值是不相同的,因为加入了随机字符串
BCrypt密码加密更安全。
对密码进行加密,然后存放在数据库中,在用户进行登录的时候,将其输入的密码进行加密然后与数据库中存放的密文进行比较,以验证用户密码是否正确。
1在common中引入依赖
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
</dependency>
2在common中创建类
package com.heima.common.bcrypt;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import java.security.SecureRandom;
@Configuration
public class PasswordConfig {
/**
* 随机秘钥的长度
*/
private int seedLength = 32;
/**
* : 10 # 加密强度4~31,决定了密码和盐加密时的运算次数,超过10以后加密耗时会显著增加
*/
private Integer strength = 10;
@Bean
public BCryptPasswordEncoder passwordEncoder() {
// 加密前度,数字越大强度越大,越安全,越耗时
SecureRandom random = new SecureRandom(SecureRandom.getSeed(seedLength));
return new BCryptPasswordEncoder(strength, random);
}
}