Class: RubyDrupalHash

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_drupal_hash.rb

Overview

RubyDrupalHash.verify(“password1234”, “$S$DeIZ1KTE.VzRvudZ5.xgOakipuMFrVyPmRdWTjAdYieWj27NMglI”)

Constant Summary collapse

DRUPAL_HASH_COUNT =
15
DRUPAL_MIN_HASH_COUNT =
7
DRUPAL_MAX_HASH_COUNT =
30
DRUPAL_HASH_LENGTH =
55
ITOA64 =
'./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
HASH =
Digest::SHA2.new(512)

Class Method Summary collapse

Class Method Details

.is_drupal_hash?(hashed_password) ⇒ Boolean

Returns:

  • (Boolean)


29
30
31
# File 'lib/ruby_drupal_hash.rb', line 29

def self.is_drupal_hash?(hashed_password)
  hashed_password and (hashed_password[0..3] == 'U$S$' || hashed_password[0..2] == '$S$')
end

.verify(password, hashed_password) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/ruby_drupal_hash.rb', line 33

def self.verify(password, hashed_password)
  return false if password.nil? or hashed_password.nil?
  return false if not is_drupal_hash?(hashed_password)

  # Known as an 'upgraded' Drupal hash
  if hashed_password[0..1] == 'U$'
    hashed_password = hashed_password[1..-1]
    password = Digest::MD5.new().hexdigest(password)
  end
  
  setting = hashed_password[0..11]
  if setting[0] != '$' or setting[2] != '$'
    # Wrong hash format
    return false
  end
      
  count_log2 = ITOA64.index(setting[3])
  
  if count_log2 < DRUPAL_MIN_HASH_COUNT or count_log2 > DRUPAL_MAX_HASH_COUNT
    return false
  end

  salt = setting[4..4+7]
  
  if salt.length != 8
    return false
  end
  
  count = 2 ** count_log2
     
  pass_hash = HASH.digest(salt + password)

  1.upto(count) do |i|
    pass_hash = HASH.digest(pass_hash + password)
  end

  hash_length = pass_hash.length

  output = setting + password_base64_encode(pass_hash, hash_length)

  if output.length != 98
    return false
  end

  return output[0..(DRUPAL_HASH_LENGTH-1)] == hashed_password      
end