This is a post on a example of how to hash a password with a salt. A salt in cryptography is a method that applies a one way function to hash data like passwords. The advantage of using salts is to protect your sensitive data against dictionary attacks, etc. Everytime a salt is applied to the same string, the hashed string will provide a different result.
Installing Bcrypt
I will be using bcrypt to hash my password. I always use alpine images and this is how I got bcrypt running on alpine:
1 2 3 |
|
This command should produce a 0 exit code
:
1
|
|
Bcrypt Example to Hash a Password
Here is a example to show you the output when a salt is applied to a string, such as a password. First we will define our very weak password:
1 2 3 4 |
|
The bcrypt package has a function called gensalt()
that accepts a parameter log_rounds
which defines the complexity of the hashing. Lets create a hash for our password:
1 2 3 4 5 |
|
As you can see, the hashed string was different when we called it for the second time.
Bcrypt Salt Hash and Verification Example:
Thanks to this post, here is a example on how to hash strings and how to verify the plain text password with the provided salt.
Our functions to create the hash and to verify the password:
1 2 3 4 5 6 7 8 9 |
|
Create a hashed string:
1 2 |
|
Verify the hash with your plain text password and the salt that was created:
1 2 |
|
When you you provide the wrong password, with the correct salt, the verification will fail:
1 2 |
|
When you provide the correct password with the incorrect salt, the verification will also fail:
1 2 |
|