Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

User model basics: SHA256 passwords (See related posts)

class User < ActiveRecord::Base
  # ...

  def password ; @password ; end
  def password=(value)
    self.password_salt = [Array.new(6){rand(256).chr}.join].pack("m").chomp
    self.password_sha  = self.encrypt_password(value)
    @password = value
  end
  
  def encrypt_password(cleartext)
    Digest::SHA256.hexdigest(cleartext + self.password_salt)
  end
  
  def self.authenticate(nickname, password)
    user = self.find_active_by_nickname(nickname)
    raise "Username or Password invalid" if user.blank? || user.encrypt_password(password) != user.password_sha
    return user
  end
end

You need to create an account or log in to post comments to this site.


Click here to browse all 5140 code snippets

Related Posts