To salt a password in Ruby, we can use the bcrypt
gem which provides a secure way to store passwords. Bcrypt hashes the password with a random salt before storing it in the database.
Here's an example of how to salt a password using bcrypt in Ruby:
main.rb140 chars6 lines
In the above code, we first require the bcrypt
gem which we assume is already installed. We then define the password that we want to hash and generate a random salt using BCrypt::Engine.generate_salt
. Finally, we hash the password with the salt using BCrypt::Engine.hash_secret
.
The resulting hashed_password
value is what we store in the database instead of the raw password. When a user logs in, we retrieve the hashed password from the database and use bcrypt to compare it with the user's entered password.
main.rb264 chars10 lines
In the above code, we retrieve the hashed password from the database and use bcrypt to compare it with the user's entered password. The BCrypt::Password.new
method constructs a new password object from the hashed password which we can then compare with the entered password.
gistlibby LogSnag