Class: UnixCrypt::SHABase

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

Direct Known Subclasses

SHA256, SHA512

Class Method Summary collapse

Methods inherited from Base

build, generate_salt

Class Method Details

.default_salt_lengthObject



100
# File 'lib/unix_crypt.rb', line 100

def self.default_salt_length; 12; end

.hash(password, salt, rounds = nil) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/unix_crypt.rb', line 102

def self.hash(password, salt, rounds = nil)
  rounds ||= 5000
  rounds = 1000        if rounds < 1000
  rounds = 999_999_999 if rounds > 999_999_999

  salt = salt[0..15]

  password = prepare_password(password)

  b = digest.digest("#{password}#{salt}#{password}")

  a_string = password + salt + b * (password.length/length) + b[0...password.length % length]

  password_length = password.length
  while password_length > 0
    a_string += (password_length & 1 != 0) ? b : password
    password_length >>= 1
  end

  input = a = digest.digest(a_string)

  dp = digest.digest(password * password.length)
  p = dp * (password.length/length) + dp[0...password.length % length]

  ds = digest.digest(salt * (16 + a.bytes.first))
  s = ds * (salt.length/length) + ds[0...salt.length % length]

  rounds.times do |index|
    c_string = ((index & 1 != 0) ? p : input)
    c_string += s unless index % 3 == 0
    c_string += p unless index % 7 == 0
    c_string += ((index & 1 != 0) ? input : p)
    input = digest.digest(c_string)
  end

  bit_specified_base64encode(input)
end