Skip to content

Instantly share code, notes, and snippets.

@watzon
Created June 14, 2019 18:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save watzon/192ba6101922e4a5d93be87787dc0529 to your computer and use it in GitHub Desktop.
Save watzon/192ba6101922e4a5d93be87787dc0529 to your computer and use it in GitHub Desktop.
Lucky valdator to make sure a password isn't in the Have I Been Pwned database
require "http/client"
require "openssl"
module NotPwnedValidation
def validate_not_in_hibp
password.value.try do |value|
hash = get_sha1_hash(value).upcase
first_five = hash[0...5]
response = HTTP::Client.get("https://api.pwnedpasswords.com/range/" + first_five)
hashes = response.body.split("\r\n")
.map(&.split(':'))
.to_h
exists = hashes.has_key?(hash[5..-1])
if exists
password.add_error("has been pwned. Please choose another.")
end
end
end
private def get_sha1_hash(password)
digest = OpenSSL::Digest.new("SHA1")
digest.update(password)
hash = digest.to_s
digest.reset
hash
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment