DEV Community

Cover image for #How to create a PASSWORD checker
Emmanuel Jerry
Emmanuel Jerry

Posted on

#How to create a PASSWORD checker

In a world where our privacy is now at risk, where they have been alot of data breaches, knowing if your password is leaked on the internet is more than essential. In this article we are going to creating a password checker with python.

import requests
from hashlib import sha1
Enter fullscreen mode Exit fullscreen mode

First we are going to import the request module, and sha1 from the hashlib which we will use to hash. We need to hash our password to be able to securely send it over the internet, and also the api we are working only accept our password request as hash

def request_api(query):
   url = '' + str(query)
   res = requests.get(url)
   if res.status_code != 200:
      raise RuntimeError(f'Error fectching: {res.status_code}, 
                         check your api and try again')
   return res
Enter fullscreen mode Exit fullscreen mode

The function above will send request to to check if the password we passed in their database.

But before that we have to hash our password, and pass only the first five letters of our hash.

def pwned_api_check(password):
    sha1pswd = sha1(password.encode('utf-8')).hexdigest().upper()
    first5_char, tail = sha1pswd[:5], sha1pswd[5:]
    response = request_data(first5_char)
    return get_password_check(response, tail)
Enter fullscreen mode Exit fullscreen mode

The above function first hashes the password, then divide the hash into two parts the head(first5_char and tail), we can now pass the head of the hash password to our request_data func.

def get_password_check(hashes, hash_tail):
    hashes = (line.split(':') for line in hashes.text.splitlines())
    for h, count in hashes:
        if h == hash_tail:
            return count
    return 0
Enter fullscreen mode Exit fullscreen mode

When we send the request it will return all hash_password that start with our first5_char, so we have to check for our exact password,
now we remove the first5_char from all the hash_password we got from our request, now we are left with only the hash_tail we compare all the hash_tail with that of the password we passed in, this function will return the number of times the password appears
if h == hash_tail: return count

def main(args):
    for password in args:
        count = pwned_api_check(password)
        if count:
            print(f'{password} was found {count} times ... you shoupld probably change your password ')
            print(f'{password} was not found ...carry on')
Enter fullscreen mode Exit fullscreen mode

Our program is a CLI tool so the last function helps us check all the password we passed on our command-line interface.

Hopefully you learnt a few interesting things, follow me for more of this type of content.

python #security #hash

Top comments (0)