This code snippet implements password hashing for safe storage. It uses Argon2 as hashing algorithm. The method hash_password() is used to hash and salt a password. The method verify() is used to check whether a password matches a hash.

Initial setup:

pip install argon2-cffi


from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError

def hash_password(password):
    ph = PasswordHasher()
    pw_hash = ph.hash(password)
    return pw_hash

def verify(pw_hash, password):
    ph = PasswordHasher()
        return ph.verify(pw_hash, password)
    except VerifyMismatchError:
        return False

def main():
    pw_hash = hash_password('s3cr3t')
    print(verify(pw_hash, 's3cr3t'))
    print(verify(pw_hash, 's3cr4t'))
    return None

if __name__ == '__main__':

1- Do you think the implementation of hash_password is up-to-date and secure?

2- Do you think the implementation of verify is up-to-date and secure?

3- Would you make any other changes to this code snippet?

4- Did you use any additional resources while checking the code? If yes, please provide a link or description of your resource


1 Answer 1


Argon2 is a decent choice of hash. Well done for following the most important rule of cryptography, and letting someone else design and implement the cryptography!

There are a few minor style things which I'd change about your code:

  • I'd return the hash immediately instead of assigning it to a variable.
  • I'd avoid an explicit return None from a function which just drops off the end.
  • The guidance in the documentation for your argon2 library says to call check_needs_rehash alongside verify, so that may want exploring. It's a key part of ensuring that you stay up-to-date and secure.
  • Depending on the context in which you're running this code, and in particular if you're likely to be running it in an already multi-threaded environment like many web servers, I'd be tempted to dial back the parallelism parameter to the PasswordHasher object.
  • This isn't a problem in practice when you're just using the defaults, but because PasswordHasher could be parameterised you may want to put a bit more thought into ensuring the hashing and verification objects match. For example, you could use a singleton pattern or a common function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.