Java如何安全地存储密码hash值

走着路睡觉
  • java
小于 1 分钟

spring-security

依赖

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-crypto</artifactId>
    <version>5.7.5</version>
</dependency>

代码

// Argon2算法
Argon2PasswordEncoder argon2PasswordEncoder = new Argon2PasswordEncoder();
//加密后的密码
String aCryptedPassword = argon2PasswordEncoder.encode("password");
//检验密码
boolean passwordIsValid = argon2PasswordEncoder.matches("password", aCryptedPassword);

// SCrypt算法
SCryptPasswordEncoder sCryptPasswordEncoder = new SCryptPasswordEncoder();
//加密后的密码
String sCryptedPassword = sCryptPasswordEncoder.encode("password");
//检验密码
boolean passwordIsValid = sCryptPasswordEncoder.matches("password", sCryptedPassword);

// BCrypt算法
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
//加密后的密码
String bCryptedPassword = bCryptPasswordEncoder.encode("password");
//检验密码
boolean passwordIsValid = bCryptPasswordEncoder.matches("password", bCryptedPassword);

// Pbkdf2算法
Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = new Pbkdf2PasswordEncoder();//加密后的密码
String pbkdf2CryptedPassword = pbkdf2PasswordEncoder.encode("password");
//检验密码
boolean passwordIsValid = pbkdf2PasswordEncoder.matches("password", pbkdf2CryptedPassword)

BCrypt包

文档

http://www.mindrot.org/projects/jBCrypt/

jar包下载地址

http://www.mindrot.org/files/jBCrypt/

使用说明

// Hash a password for the first time
String hashed = BCrypt.hashpw(password, BCrypt.gensalt());

// gensalt's log_rounds parameter determines the complexity
// the work factor is 2**log_rounds, and the default is 10
String hashed = BCrypt.hashpw(password, BCrypt.gensalt(12));

// Check that an unencrypted password matches one that has
// previously been hashed
if (BCrypt.checkpw(candidate, hashed))
	System.out.println("It matches");
else
	System.out.println("It does not match");
上次编辑于:
贡献者: zhaojingbo
Loading...