Secure Password Hashing in Python

Learn how to securely hash passwords in Python

2022 April 03 14:00:25

1 min read

The password hashing function to use is argon2id

Skip to the end to view the full code.

To get started in Python, create a virtual environment.

$ python -m venv venv

Activate the virtual environment in the current shell

# linux:
$ source ./venv/bin/activate
# windows
$ ./venv/scripts/activate

Install PyNaCl which is a Python library that binds to libsodium

$ pip install pynacl

The code

Import the argon2id class

from nacl.pwhash import argon2id

Create the hash of the password

password = "extremelysecretpassword".encode("utf-8") # password must be bytes, cannot be a string
hashed_password = argon2id.str(password) # returns bytes, good idea to store it in a bytes column in a database

Next, we take the hashed password and we verify it.

is_valid = argon2id.verify(hashed_password, password)

Calling verify with improper credentials will raise nacl.exceptions.InvalidkeyError. You can use a try/except block to capture this and send an error back to your user. Finally, we can then print the result.


Full Code

from nacl.pwhash import argon2id

password = "extremelysecretpassword".encode("utf-8")
hashed_password = argon2id.str(password)

is_valid = argon2id.verify(hashed_password, password)



$ python

PyNaCl argon2id documentation: