Skip to content

Instantly share code, notes, and snippets.

@electronicbites
Last active August 29, 2015 14:02
Show Gist options
  • Save electronicbites/c0f0f3e799bce10e1e82 to your computer and use it in GitHub Desktop.
Save electronicbites/c0f0f3e799bce10e1e82 to your computer and use it in GitHub Desktop.
Bcrypt Encryption, Decrpytion copied from devise
# constant-time comparison algorithm to prevent timing attacks
def secure_compare(a, b)
return false if a.blank? || b.blank? || a.bytesize != b.bytesize
l = a.unpack "C#{a.bytesize}"
res = 0
b.each_byte { |byte| res |= byte ^ l.shift }
res == 0
end
# Verifies whether an password (ie from sign in) is the user password.
def valid_password?(password)
return false if encrypted_password.blank?
bcrypt = ::BCrypt::Password.new(encrypted_password)
password = ::BCrypt::Engine.hash_secret("#{password}#{self.class.pepper}", bcrypt.salt)
secure_compare(password, encrypted_password)
end
# Digests the password using bcrypt. Custom encryption should override
# this method to apply their own algorithm.
#
# See https://github.com/plataformatec/devise-encryptable for examples
# of other encryption engines.
def password_digest(password)
::BCrypt::Password.create("#{password}#{klass.pepper}", :cost => klass.stretches).to_s
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment