Skip to content

Instantly share code, notes, and snippets.

@loganstartoni
Created January 13, 2019 05:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loganstartoni/213e1043314affb56eafc02885494f40 to your computer and use it in GitHub Desktop.
Save loganstartoni/213e1043314affb56eafc02885494f40 to your computer and use it in GitHub Desktop.
Python password Validation useing using Troy Hunts pwned Password Database
from collections import namedtuple
import hashlib
import requests
test_password = "password"
pass_hash = hashlib.sha1(test_password.encode("utf-8")).hexdigest().upper()
print("Password Hash: " + pass_hash)
api_base_url = "https://api.pwnedpasswords.com/range/"
resp = requests.get(api_base_url + pass_hash[:5])
def get_hashes(hash_list):
HashResponse = namedtuple("HashResponse", "hash times")
resp = []
for hashed_password in hash_list:
pass_list = hashed_password.split(":")
resp.append(HashResponse(hash=pass_list[0], times=pass_list[1]))
return resp
if resp.ok:
possible_hashes = get_hashes(resp.text.split("\r\n"))
for possible_hash in possible_hashes:
if possible_hash.hash in pass_hash:
print(f"You can not use that password it has been pwned {possible_hash.times} times.")
elif resp.status_code == 429:
print("Rate Limit:" + resp.headers)
# class PwnedPasswordValidator:
# """
# Validate whether the password has been pwned by using the following api: https://haveibeenpwned.com
# """
# import requests
# from hashlib import sha1
# api_base_url = "https://api.pwnedpasswords.com/range/"
#
# def _get_hashes(self, password, password_hash):
# resp = self.requests.get(self.api_base_url + password_hash[:5])
#
# # Returns a list of possible hashes as password_hash[5:]:times_pwned
# possible_hashes = resp.text.split("\r\n")
# hash_responses = []
# for possible_hash in possible_hashes:
# possible_hash = possible_hash.split(":")
# hash_responses.append({"hash": possible_hash[0], "times_pwned": possible_hash[1]})
#
# return hash_responses
#
# def validate(self, password, user=None):
# password_hash = self.sha1(password.encode("utf-8")).hexdigest().upper()
# possible_hashes = self._get_hashes(password, password_hash)
# for possible_hash in possible_hashes:
# if possible_hash["hash"] in password_hash:
# raise ValidationError(
# _(f"That Password has been pwned, {possible_hash[
# 'times_pwned']} times in the past. For more information go to https://haveibeenpwned.com."),
# code='password_pwned',
# )
#
# def get_help_text(self):
# return _("Your password can't be in the pwned Database. For more information go to https://haveibeenpwned.com.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment