title: Ruby BCrypt hash comparison
body: <p>I'm trying to implement what seems like a very simple authentication approach using Sinatra and BCrypt but clearly I'm missing something...</p>
  
  <p>Users are preassigned a temporary password which is stored in plaintext in the db.</p>
  
  <p>I authenticate against the temp password and then create both a salt and password_hash and write them as strings to the db (mongo in this case).</p>
  
  <p>To authenticate I fetch the salt from the db and user password to compare.</p>
  
  <pre><code>post "/password_reset" do
    user = User.first(:email =&gt; params[:email], :temp_password =&gt; params[:temp_password])
    if dealer != nil then
    password_salt = BCrypt::Engine.generate_salt
    password_hash = BCrypt::Engine.hash_secret(params[:password], password_salt)
    user.set(:password_hash =&gt; password_hash)
    user.set(:password_salt =&gt; password_salt)
    end
  end
  
  post "/auth" do
    @user = User.first(:email =&gt; params[:email])
    @user_hash = BCrypt::Password.new(@user.password_hash) #because the password_hash is  stored in the db as a string, I cast it as a BCrypt::Password for comparison
    if @user_hash == BCrypt::Engine.hash_secret(params[:password], @user.password_salt.to_s)   then
      auth = true
    else
      auth = false
    end
  end
  </code></pre>
  
  <p>The value returned by BCrypt::Engine.hash_secret(params[:password], password_salt) is different than what is stored in the db (both are of class BCrypt::Password, but they don't match).</p>
  
  <p>What am I missing here? Many thanks in advance for any insight!</p>
  
  <p>Marc</p>