how to salt a password in ruby

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.rb
require 'bcrypt'

password = "password123"
salt = BCrypt::Engine.generate_salt
hashed_password = BCrypt::Engine.hash_secret(password, salt)
140 chars
6 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.rb
# retrieving hashed password from database
stored_password = get_hashed_password_from_database()

# comparing entered password with stored password
if BCrypt::Password.new(stored_password) == entered_password
  # passwords match
else
  # passwords don't match
end
264 chars
10 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