Class: HaveIBeenPwned::PwnedPasswords

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

Constant Summary collapse

BASE_URL =
"https://api.pwnedpasswords.com"

Class Method Summary collapse

Class Method Details

.check(password, mode: :sha1, padding: false) ⇒ Object



11
12
13
14
# File 'lib/haveibeenpwned/pwned_passwords.rb', line 11

def check(password, mode: :sha1, padding: false)
  hash = hash_password(password, mode)
  check_hash(hash, mode: mode, padding: padding)
end

.check_hash(hash, mode: :sha1, padding: false) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/haveibeenpwned/pwned_passwords.rb', line 16

def check_hash(hash, mode: :sha1, padding: false)
  hash = hash.upcase
  prefix = hash[0..4]
  suffix = hash[5..-1]

  response = range_search(prefix, mode: mode, padding: padding)

  # Parse response and find matching suffix
  response.each_line do |line|
    hash_suffix, count = line.strip.split(":")
    return count.to_i if hash_suffix == suffix
  end

  0
end

.range_search(prefix, mode: :sha1, padding: false) ⇒ Object

Raises:



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/haveibeenpwned/pwned_passwords.rb', line 32

def range_search(prefix, mode: :sha1, padding: false)
  params = {}
  params[:mode] = mode.to_s if mode == :ntlm

  headers = {}
  headers["Add-Padding"] = "true" if padding

  response = connection.get("/range/#{prefix}", params) do |req|
    headers.each { |key, value| req.headers[key] = value }
  end

  raise Error, "Unexpected response: #{response.status}" unless response.status == 200

  response.body
end