Python Password CheckerMany of us are worried whether our passwords were hacked or not. By using the below python code we can check that. When we check our password and if the password was not hacked and unique, then we get an output as "****** was not found. Carry on.". But if our password was hacked, then we get an output of how many times it was hacked and used by other users.
import requests
import hashlib
import sys
def request_api_data(query_char):#query_char is first five characters of encoded password
url="https://api.pwnedpasswords.com/range/" + query_char
res=requests.get(url)
if res.status_code !=200:
raise RuntimeError(f"Error fetching:{res.status_code}")
return res
#if there is no error code then it will return the url added with first five characters of the encodeddpassword.
def get_password_leaks_count(hashes,hash_to_check):
hashes=(line.split(":") for line in hashes.text.splitlines())
for h,count in hashes:
if h==hash_to_check:
return count
return 0
def pwned_api_check(password):# This function is to encode password
sha1password= hashlib.sha1(password.encode("utf-8")).hexdigest().upper()
first5_char,tail=sha1password[:5],sha1password[5:]
response=request_api_data(first5_char)
return get_password_leaks_count(response,tail)
# This main function helps to take number of password through arguments as an input and checks every password
def main(args):
for password in args:
count = pwned_api_check(password)
if count:
print(f'{password} was found {count} times. You should probably change your password!')
else:
print(f'{password} was NOT found. Carry on!')
return 'done!'
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
In the above screenshot, passwordchecker.py is the file name
Anyone can use this code in Pycharm or any python ide. This is the most secure way to check our passwords as it can be checked in our own trusted pc only rather than trusting some unsecured websites which may not be safe.
Comments