简体   繁体   中英

How Do I Separate The Salt from the Hash After Encrypting a Password with bCrypt using Java?

OK, I am using Java with Spring MVC and Hibernate. I am using bCrypt for password encryption for the first time. I understand doing in that bCrypt integrates the salt with the hash. I have it set up currently so that the password is accepted as an input, is encoded with bCrypt, and is saved is one column of my SQL database.

However, I would like to separate the salt from the hash and put store them separately. I have read, and tried many things, but cannot find a way to do this. So if anyone can point me in the correct direction that would be a great assistance.

This is what I have at present.

This is the basic code to setup bCrypt. It takes my password string, and encrypts it.

 BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();  
    String hashedPassword = passwordEncoder.encode(password);  

The below code takes the password and puts it into a single column in the DB.

    employee.setPasswordSalt(hashedPassword);

While it is possible to separate the salt from the calculated BCrypt hash, there is no reason to do this. BCrypt adds the salt in plain text to the resulting hash, so the verification function passwordEncoder.matches(...) can extract it from there.

$2y$10$nOUIs5kJ7naTuTFkBy1veuK0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
 |  |  |                     |
 |  |  |                     hash-value = K0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
 |  |  |
 |  |  salt = nOUIs5kJ7naTuTFkBy1veu (22 characters)
 |  |
 |  cost-factor = 10 = 2^10 iterations
 |
 hash-algorithm = 2y = BCrypt

As you can see the salt is just one of several stored parameters. With extracting the salt and storing it elsewhere, you would make password verification more difficult. Furthermore if the password encoder switches to another algorithm in future, it would not be backwards compatible.

It is safe to store the salt at the same place as the hash, the salt is not a secret. If you want to add a secret to get more security, you should not make the salt a secret, instead let the salt do its job, and encrypt the resulting hash with a server side key. More about this, you can find at the end of my tutorial about safely storing passwords .

I found out more detail for what was requested a little bit ago, and based it on that. I changed up how I encoded the password, so now it is like this...

    String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt()); 

and then stored it in 2 separate places like this...

            employee.setPasswordSalt(BCrypt.gensalt());

    employee.setPasswordHash(hashedPassword);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM