Ich habe ein kleines Skript geschrieben, welches einen Passwort hash erzeugt. Ist quasi aus einer Übungsaufgabe entstanden, die ich erweitert habe. Aber ich verstehe leider nicht, wie ich nun ein Passwort eines Benutzers mit dem Hash prüfen kann. Hab schon mehreres probiert, von dem nichts gekappt hat.
Die Überprüfung ist nicht mit in dem Code, das habe ich bisher nur in der interaktiven Konsole getestet. Das Problem ist, das der Hash einfach nicht mit dem User übereinstimmt.
Wäre nett, wenn mir jemand weiterhelfen kann. Wünsche Euch eine angenehme Woche.
Hier mein Code, mit dem ich den Hash erstelle:
Code: Alles auswählen
# Imports
# *********************************************************************
import os
import hashlib
import getpass
import binascii
# *********************************************************************
def password_user():
"""Password user input
:return: The password from the user
"""
pw = getpass.getpass()
pw_sha = hashlib.sha512(bytes(pw, 'utf-8'))
return pw, pw_sha
def salt_gen(n):
"""Salt generator
:param n: The number of bytes
To make it impossible for an attacker to create a lookup table for
every possible salt, the salt must be long. A good rule of thumb is
to use a salt that is the same size as the output of the hash
function. For example, the output of SHA256 is 256 bits (32 bytes),
so the salt should be at least 32 random bytes.
[https://crackstation.net/hashing-security.htm - (CC BY-SA 3.0)]
:return: The created salt
"""
salt = os.urandom(n)
return salt
def secure_pw_hash(hash_name, pw, salt):
"""Create a secure password hash with hashlib.pbkdf2_hmac
:param hash_name: The hash algorithm name (e.g. sha512)
:param pw: The password from the function -> password_user
:param salt: The salt that generated in function -> salt_gen
:return: The Secure password -> sec_pw
"""
# Caution: 1_000_000 only on Python >= 3.6 . When below use: 1000000
sec_pw = hashlib.pbkdf2_hmac(hash_name, pw.encode(), salt, 1_000_000)
return sec_pw
def main():
"""Receive and send all relevant data"""
# Method calls
pw, pw_sha = password_user()
salt = salt_gen(64)
sec_pw = secure_pw_hash('sha512', pw, salt)
# Bytes to hex
hex_sec_pw = binascii.b2a_hex(sec_pw)
hex_salt = binascii.b2a_hex(salt)
# Decode to str
hex_sec_pw = hex_sec_pw.decode()
hex_salt = hex_salt.decode()
pw_sha = pw_sha.hexdigest()
print('Secure Password: {}\nHashed Password: {}\nSalt: {}'.format(
hex_sec_pw, pw_sha, hex_salt))
if __name__ == '__main__':
main()