Sha256: 4f0f26d49cc6e3484a3c3c8610b644ce7a0194fd8cbc774a7c8e0922340e6ea3

Contents?: true

Size: 1.36 KB

Versions: 21

Compression:

Stored size: 1.36 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

    def self.compare(*args)
      new().compare(*args)
    end

    def self.encrypt(*args)
      new().encrypt(*args)
    end

    def self.hash(*args)
      new().hash(*args)
    end

    def self.md5(*args)
      new().md5(*args)
    end
  end
end

Version data entries

21 entries across 21 versions & 1 rubygems

Version Path
challah-1.6.1 lib/challah/encrypter.rb
challah-1.6.0 lib/challah/encrypter.rb
challah-1.5.0 lib/challah/encrypter.rb
challah-1.4.2 lib/challah/encrypter.rb
challah-1.4.1 lib/challah/encrypter.rb
challah-1.4.0 lib/challah/encrypter.rb
challah-1.3.3 lib/challah/encrypter.rb
challah-1.3.2 lib/challah/encrypter.rb
challah-1.3.1 lib/challah/encrypter.rb
challah-1.3.0 lib/challah/encrypter.rb
challah-1.2.11 lib/challah/encrypter.rb
challah-1.2.10 lib/challah/encrypter.rb
challah-1.2.9 lib/challah/encrypter.rb
challah-1.2.8 lib/challah/encrypter.rb
challah-1.2.7 lib/challah/encrypter.rb
challah-1.2.6 lib/challah/encrypter.rb
challah-1.2.5 lib/challah/encrypter.rb
challah-1.2.5.pre lib/challah/encrypter.rb
challah-1.2.4 lib/challah/encrypter.rb
challah-1.2.3 lib/challah/encrypter.rb