Sha256: a213c736352e0ba4ce65c6852674b5532ca71658574f5b8a37e37cfcba14220e

Contents?: true

Size: 1.34 KB

Versions: 13

Compression:

Stored size: 1.34 KB

Contents

require 'digest/sha2'
require 'bcrypt'

module Challah
  # Handles all encryption, hashing and comparison necessary for tokens and passwords.
  class Encrypter
    attr_accessor :cost, :joiner

    # The number of times to hash the given password.
    def cost
      @cost ||= 10
    end

    # Used to join multiple parameters for a given encrypt command.
    def joiner
      @joiner ||= "|"
    end

    # Passwords and secure objects are encrypted (hashed) in a one-way technique. This way
    # any item stored in the database can never be reversed into an actual password.
    def hash(*tokens)
      result = tokens.flatten.join(joiner)
      cost.times { result = Digest::SHA512.hexdigest(result) }
      result
    end

    def md5(*tokens)
      Digest::MD5.hexdigest(tokens.flatten.join(joiner))
    end

    def encrypt(secret)
      BCrypt::Password.create(secret, :cost => cost)
    end

    # Returns true if the the bcrypted value of a is equal to b
    def compare(crypted_string, plain_string)
      BCrypt::Password.new(crypted_string).is_password?(plain_string)
    rescue BCrypt::Errors::InvalidHash
      false
    end

    class << self
      # Setup some pass through convenience methods that use default options
      %w( hash md5 encrypt compare ).each do |f|
        class_eval "def #{f}(*args); new.#{f}(*args); end"
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 2 rubygems

Version Path
challah-rolls-0.2.0 vendor/bundle/gems/challah-0.8.0.pre/lib/challah/encrypter.rb
challah-0.8.2 lib/challah/encrypter.rb
challah-0.8.1 lib/challah/encrypter.rb
challah-0.8.0 lib/challah/encrypter.rb
challah-rolls-0.1.0 vendor/bundle/gems/challah-0.8.0.pre/lib/challah/encrypter.rb
challah-0.8.0.pre lib/challah/encrypter.rb
challah-0.7.1 lib/challah/encrypter.rb
challah-0.7.0 lib/challah/encrypter.rb
challah-0.7.0.pre2 lib/challah/encrypter.rb
challah-0.7.0.pre lib/challah/encrypter.rb
challah-0.6.2 lib/challah/encrypter.rb
challah-0.6.1 lib/challah/encrypter.rb
challah-0.6.0 lib/challah/encrypter.rb