require 'digest/sha2'

module Password
  
    # salts and hashes the password and returns the value that can be stored
    def Password.update(password)
        salt = self.salt
        salted_hash = self.hash(password, salt)
        salted_hash + salt
    end
  
    # checks if the given password and the stored value match
    def Password.check(password, store)
        hash = store[0..127]
        salt = store[128..192]
        if self.hash(password, salt) == hash
          true
        else
          false
        end
    end
  
  protected
  
    # generates a salt (pseudo-random 64 character string)
    def Password.salt
      salt = ""
      64.times { salt << (i = Kernel.rand(62); i += ((i < 10) ? 48 : ((i < 36) ? 55 : 61 ))).chr }
      salt
    end
    
    # hashes password and salt
    def Password.hash(password, salt)
        Digest::SHA512.hexdigest("#{password}:#{salt}")
    end

end