When using has_secure_password
in Rails 3.1, bcrypt randomly generates a salt for each user's password. Based on this response, I understand the salt is stored as part of the password hash. Is there a method or attribute available to access that salt separately, for example to use in writing secure cookies?
Asked
Active
Viewed 4,598 times
10
1 Answers
15
You'll be able to get the salt and checksum if you need it.
gem install bcrypt-ruby
irb
require 'bcrypt'
hash = BCrypt::Password.create 'superpass'
=> "$2a$10$DtjuZD6nJtrBRLEySlSVm.bJyBMhEhVRAeiVk/GjmQdBNf7WhmDWi"
hash.salt
=> "$2a$10$DtjuZD6nJtrBRLEySlSVm."
hash.checksum
"bJyBMhEhVRAeiVk/GjmQdBNf7WhmDWi"
hash == "starbucks"
=> false
hash == "superpass"
=> true
Your salt and checksum will vary.
More info: https://github.com/codahale/bcrypt-ruby

joanwolk
- 1,105
- 1
- 15
- 26

Jesse Wolgamott
- 40,197
- 4
- 83
- 109
-
2Thanks! With this in mind, plus a look at [the Rails secure_password model](https://github.com/rails/rails/blob/master/activemodel/lib/active_model/secure_password.rb), I was able to determine that I needed to write a method for my code (to access the salt neatly, anyway).`def salt @salt ||= BCrypt::Password.new(password_digest).salt end` is perfect! – joanwolk Jun 02 '11 at 12:56