Math2Hard
Math2Hard

Reputation: 57

Ruby password hashing

I'm having trouble correctly hashing the passwords for new users that register on to a makeshift website. Users have a username, password and an avatar which is loaded via filename and subsequently stored onto an SQL database. Any help would be appreciated.

Here is my code:

    def register(user, filename, file, password, confirm)
      if(password != confirm) then return false end
      if(not_found(user) == user) 
        user = html_clean(user)
        password = html_clean(password)
        upload_file(filename, file)
        n = SecureRandom.hex
        p = password + n
        hashed = Digest::SHA256.hexdigest p
        @db.prepare("INSERT INTO Users VALUES(?,?,#{filename},
       {n}\")").execute([user,hashed])
      end
      true
    end  

Upvotes: 1

Views: 3535

Answers (1)

Cody Caughlan
Cody Caughlan

Reputation: 32758

Use bcrypt for password storage, hashing validation.

Using BCrypt for password hashing has several advantages over the builtin Digest classes. Also it the built-in security. Passwords are automatically salted. Furthermore, BCrypt has a parameter cost which exponentially scales the computation time.

gem install bcrypt

An example:

The User model

require 'bcrypt'

class User < ActiveRecord::Base
  # users.password_hash in the database is a :string
  include BCrypt

  def password
    @password ||= Password.new(password_hash)
  end

  def password=(new_password)
    @password = Password.create(new_password)
    self.password_hash = @password
  end
end

Creating an account

def create
  @user = User.new(params[:user])
  @user.password = params[:password]
  @user.save!
end

Authenticating a user

def login
  @user = User.find_by_email(params[:email])
  if @user.password == params[:password]
    give_token
  else
    redirect_to home_url
  end
end

Links: https://github.com/codahale/bcrypt-ruby

Upvotes: 4

Related Questions