Created
February 18, 2011 21:23
-
-
Save drtoast/834438 to your computer and use it in GitHub Desktop.
how to use SHA1 digests to encrypt passwords, based on Clearance authentication gem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'digest/sha1' | |
class User | |
=begin | |
u = User.new | |
u.set_password "hello" | |
u.sign_in "hello" | |
=> true | |
u.sign_in "blah" | |
=> false | |
u.generate_remember_token | |
=> "61bba71faab853965e4e9ff83ccbba86937acda0" | |
User.find_by_remember_token "61bba71faab853965e4e9ff83ccbba86937acda0" | |
=> <# User...> | |
=end | |
attr_accessor :password, :salt, :encrypted_password, :remember_token | |
def set_password(password) | |
# save as instance variable for convenience | |
@password = password | |
# set the salt to a random value | |
@salt = Digest::SHA1.hexdigest("--#{Time.now.utc}--#{@password}--#{rand}--") | |
# encrypt the password by creating a unique digest via the random salt and the plaintext password | |
@encrypted_password = Digest::SHA1.hexdigest("--#{@salt}--#{@password}--") | |
# create an initial token for cookies | |
generate_remember_token | |
end | |
# check the password and set the cookie to the user's temporary token | |
def sign_in(password) | |
if authenticate(password) | |
cookies[:remember_token] = {:value => @remember_token} | |
true | |
else | |
false | |
end | |
end | |
# delete the cookie and create a new token for next time | |
def sign_out | |
cookies.delete(:remember_token) | |
generate_remember_token | |
end | |
# is the saved encrypted password the same as the re-encrypted plaintext password? | |
def authenticate(password) | |
@password = password | |
@encrypted_password == Digest::SHA1.hexdigest("--#{@salt}--#{@password}--") | |
end | |
# create a "temporary password" token for cookie | |
def generate_remember_token | |
@remember_token = Digest::SHA1.hexdigest("--#{Time.now.utc}--#{@encrypted_password}--#{rand}--") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment