Module: Doable::Helpers::Password

Defined in:
lib/doable/helpers/password.rb

Instance Method Summary collapse

Instance Method Details

#generate_password(length = 8, options = {}) ⇒ String

Generates a password

Parameters:

  • length (Fixnum) (defaults to: 8)

    Length of the password

  • options (Hash) (defaults to: {})

    Options hash for specifying password details

Returns:

  • (String)

8
9
10
11
12
# 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 }) ⇒ String

Generates a digest hash of a string

Parameters:

  • password (String)

    string to digest

  • options (Hash) (defaults to: { algorithm: :sha1, salt: true })

    Options hash for digest details

Returns:

  • (String)

18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# 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