Skip to content

Instantly share code, notes, and snippets.

@haileys
Created December 27, 2010 03:11
Show Gist options
  • Save haileys/755826 to your computer and use it in GitHub Desktop.
Save haileys/755826 to your computer and use it in GitHub Desktop.
require 'digest/sha2'
require 'active_support/secure_random'
class User < ActiveRecord::Base
validates_presence_of :username, :password, :salt
def password=(pw)
set_salt unless salt
write_attribute :password, hash(pw)
end
def salt=(h)
raise 'User#salt is readonly'
end
def test_password(pw)
password == hash(pw)
end
private
def set_salt
write_attribute :salt, SecureRandom.base64(4)
end
def hash(msg)
digest = Digest::SHA2.new 512
digest << salt << msg << salt
digest.to_s
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment