module Doable::Helpers::Password

Public Instance Methods

generate_password(length = 8, options = {}) click to toggle source

Generates a password @param length [Fixnum] Length of the password @param options [Hash] Options hash for specifying password details @return [String]

# File lib/doable/helpers/password.rb, line 8
def generate_password(length = 8, options = {})
  options[:characters] ||= [*(2..9), *('a'..'z'), *('A'..'Z')] - %w(i l O)

  (1..length).collect{|a| options[:characters][rand(options[:characters].size)] }.join
end
password_hash(password, options = { algorithm: :sha1, salt: true } ) click to toggle source

Generates a digest hash of a string @param password [String] string to digest @param options [Hash] Options hash for digest details @return [String]

# File lib/doable/helpers/password.rb, line 18
def password_hash(password, options = { algorithm: :sha1, salt: true } )
  options[:algorithm] ||= :sha1
  options[:salt] = true unless options.has_key?(:salt)

  salt = if options[:salt]
    if options[:salt].kind_of?(String)
      if options[:salt].downcase.match(/^[0-9a-f]+$/)
        options[:salt].downcase
      else
        # hex encode the non-hex salt... good way to keep input sanitized
        options[:salt].downcase.unpack('H*').join
      end
    else
      generate_password(16, characters: [*(0..9), *('a'..'f')])
    end
  else
    ''
  end

  case options[:algorithm].to_sym
  when :sha1
    Base64.strict_encode64(Digest::SHA1.digest(password + salt) + salt)
  when :sha256, :sha2
    Base64.strict_encode64(Digest::SHA256.digest(password + salt) + salt)
  when :sha384
    Base64.strict_encode64(Digest::SHA384.digest(password + salt) + salt)
  when :sha512
    Base64.strict_encode64(Digest::SHA512.digest(password + salt) + salt)
  when :md5
    Base64.strict_encode64(Digest::MD5.digest(password + salt) + salt)
  when :ripe160, :ripemd, :rmd160
    Base64.strict_encode64(Digest::RMD160.digest(password + salt) + salt)
  else
    raise InvalidInput, "Invalid Hashing Algorithm: #{options[:algorithm].to_sym}"
  end
end