Python Secure Password Management: Hashing and Encryption #️⃣🔐✨ (2024)

Deon Pillsbury

Posted on

Python Secure Password Management: Hashing and Encryption #️⃣🔐✨ (3) Python Secure Password Management: Hashing and Encryption #️⃣🔐✨ (4) Python Secure Password Management: Hashing and Encryption #️⃣🔐✨ (5) Python Secure Password Management: Hashing and Encryption #️⃣🔐✨ (6) Python Secure Password Management: Hashing and Encryption #️⃣🔐✨ (7)

#python #programming #tutorial #webdev

When building an application that validates user passwords or needs to store tokens for future use it is critical to not store these values anywhere in clear text. If there is a security breach you want to be confident that your user’s data is protected. Hashing and Encryption are a couple of techniques which can be used to achieve this and we will take a look at how to implement these with Python.

Hashing

If your application needs to allow users to register an account and create a password then you need to store the values they singed up with in order to authenticate them later. Rather than storing the passwords in clear text, this is where a hashing algorithm should be used. Hashing algorithms are one-way functions which produce the same result for the input data but given the output data are nearly impossible to reverse. There are many types of hash algorithms but SHA-256 is a strong and NIST Approved modern algorithm that fits the need of most applications in terms of strength and performance.

Create a simple Python script file to take an input and generate the SHA-256 hash with the hashlib standard library.

📝hash.py

import hashlibpassword = input("Password: ")password_hash = hashlib.sha256(password.encode("utf-8")).hexdigest()print(f"Password Hash: {password_hash}")

Run the script and give it a few password inputs.

$ python3 hash.pyPassword: test123Password Hash: ecd71870d1963316a97e3ac3408c9835ad8cf0f3c1bc703527c30265534f75ae$ python3 hash.pyPassword: test123Password Hash: ecd71870d1963316a97e3ac3408c9835ad8cf0f3c1bc703527c30265534f75ae$ python3 hash.pyPassword: test1234Password Hash: 937e8d5fbb48bd4949536cd65b8d35c426b80d2f830c5c308e2cdec422ae2244

We can see that the same input produces the same hash result but any change such as an additional character completely changes it. The resulting hash value is what you should store in your database to later validate the user’s password.

Encryption

Hashing is a great option when you do not need use the password value. For use cases where you need to use the actual password value such as storing a long term access token to authenticate on the user’s behalf to an external application then encryption is the best option. Encryption allows you to store the values securely and decrypt them in memory when you need to use them. Python has the cryptography library which includes Fernet Symmetric Encryption to achieve this. Symmetric encryption means we will have a secret key which we can store in our environment variables and use to decrypt stored values.

Install the cryptography and dotenv library.

$ poetry add cryptography python-dotenvUsing version ^41.0.5 for cryptographyUsing version ^1.0.0 for python-dotenvUpdating dependenciesResolving dependencies... (0.1s)Package operations: 4 installs, 0 updates, 0 removals • Installing pycparser (2.21) • Installing cffi (1.16.0) • Installing cryptography (41.0.5) • Installing python-dotenv (1.0.0)

Run an inline python command to generate the Fernet secret key.

$ python3 -c "from cryptography.fernet import Fernet; print(Fernet.generate_key())"b'XvYvP_c4gBDLCLbjgz6Hc47ND_BcoMYt3Cz5pAKx1qQ='

Add this value to a .env file.

📝.env

SECRET_KEY=XvYvP_c4gBDLCLbjgz6Hc47ND_BcoMYt3Cz5pAKx1qQ=

Create a new python script which will load our secret key from the environment variables, instantiate the Fernet client with the key, and allow a new password to be encrypted and stored in a simple text file or print out the decrypted value of an existing stored password.

📝encrypt.py

import osimport sysfrom cryptography.fernet import Fernetfrom dotenv import load_dotenvload_dotenv()SECRET_KEY = os.getenv("SECRET_KEY")assert SECRET_KEYFERNET = Fernet(SECRET_KEY)if len(sys.argv) > 1 and sys.argv[1] == "decrypt": with open("pw.txt") as f: stored_password = f.read() stored_dec_password = FERNET.decrypt(stored_password).decode() print(f"Decrypted Password: {stored_dec_password}")else: new_password = input("New Password: ") new_enc_password = FERNET.encrypt(new_password.encode()).decode() with open("pw.txt", "w") as f: f.write(new_enc_password) print(f"Encrypted Password Stored: {new_enc_password}")

Test it out to validate it is working as expected.

$ python3 encrypt.pyNew Password: Test123!!Encrypted Password Stored: gAAAAABlR7V0TLTZMT_ZHEoPtqbW3B9LYgohYdUNG6Lukx9M2NSLgrFN6MUZKCNPP3Hq_KuuEPpJPPqqIktUkZTBh3qenKnQAA==$ python3 encrypt.py decryptDecrypted Password: Test123!!

Awesome! 🎉This shows the core concepts of encrypting/decrypting values and in a production environment rather than storing them in a simple text file you would just store and retrieve the values from a database.

I hope you have found this article helpful for building your next amazing (and secure) application! 😊

Top comments (5)

Subscribe

Dotenv

Dotenv

Simplify Your Secrets

Nov 8 '23

  • Copy link

Nice use of sha256. We also use it in our .env.vault mechanism - successor to .env files.

Have you seen python-dotenv-vault - different use case than what you are doing here, but as a fellow cryptography fan, you might find it interesting intellectually:

github.com/dotenv-org/python-doten...

Deon Pillsbury

Deon Pillsbury

Software Engineering Technical Leader @ Cisco 💼 | Creator ✨ | Mentor 🤝 | Tech Enthusiast 🤓

  • Location

    North Carolina, US

  • Joined

Nov 9 '23

  • Copy link

@dotenv Very nice, I had not seen the dotenv vault functionality, it is a separate use case but it does address a challenge we have with keeping .env files in-sync across our smaller teams. I love the idea of committing encrypted environment variables to the repo with a .env.vault file and only needing to manage the DOTENV_KEY. 😃 Thanks for sharing this and amazing work on the Dotenv ecosystem! ❤️

mohammadparsa-javidi

mohammadparsa-javidi

Web Developer 🙃❤

Nov 13 '23

  • Copy link

Great👌👌👍👍

Tejas

Tejas

  • Work

    Software Developer

  • Joined

Mar 12

  • Copy link

Should you add salt to your passwords?

Ken Doman

Ken Doman

  • Joined

Jul 24

  • Copy link

Good question. In the second example, using the cryptography library to encrypt and decrypt the passwords, the secret key they generated works as the salt added to the password. Salting does provide an added layer of protection as long as you protect the .env file where you store it. I think they just wanted to simplify the example so people will use it.

For further actions, you may consider blocking this person and/or reporting abuse

Python Secure Password Management: Hashing and Encryption #️⃣🔐✨ (2024)

FAQs

What is the best password hashing algorithm in Python? ›

BCrypt is a password hashing algorithm that is considered one of the most secure algorithms for password hashing in Python. BCrypt is designed to be slow, which makes it more difficult for hackers to crack the hashed passwords.

How to hash a password in Python using Hashlib? ›

Select a hashing algorithm from the hashlib module, such as SHA-256 or bcrypt. Create a hash object using the chosen algorithm. Pass the password bytes to the hash object using the update() method. Retrieve the hashed password using the hexdigest() method.

How to pass an encrypted password in a Python script? ›

There are various Python modules that are used to hide the user's inputted password, among them one is maskpass() module. In Python with the help of maskpass() module and base64() module we can hide the password of users with asterisk(*) during input time and then with the help of base64() module it can be encrypted.

What is the most secure encryption in Python? ›

So using a secure key is the most important factor in encryption. I recommend to choose encryption algorithms with proper long key lengths to prevent brute-force attacks. For example, AES with a key length of 256 bits is widely recommended for secure encryption.

What is the strongest password encryption algorithm? ›

To protect passwords, experts suggest using a strong and slow hashing algorithm like Argon2 or Bcrypt, combined with salt (or even better, with salt and pepper). (Basically, avoid faster algorithms for this usage.) To verify file signatures and certificates, SHA-256 is among your best hashing algorithm choices.

Which algorithm is best for strong passwords? ›

The most common password hashing algorithms are PBKDF2, bcrypt, and script. PBKDF2 (Password-Based Key Derivation Function 2) is a widely used algorithm that employs a salt to protect against brute force attacks.

Is SHA-256 better than MD5? ›

SHA256 has several advantages over MD5 and SHA-1, such as producing a longer hash (256 bits) that is more resistant to collisions and brute-force attacks. Additionally, there are no known vulnerabilities or weaknesses with SHA256, unlike MD5 and SHA-1 which have been exploited by hackers and researchers.

Is SHA-256 always the same? ›

Other important characteristics of SHA-256 include the fact that it is deterministic (it will always produce the same output when given the same input) and the fact that it is a one-way function. There is no way to reverse engineer an input from knowledge of the output.

Is SHA-256 secure? ›

SHA-256 (Secure Hash Algorithm 256-bit)

SHA-256 is widely used in cryptography and data integrity verification. It is known for its security and resistance to collision attacks, making it suitable for applications such as digital signatures, data authentication, and password hashing.

How to keep passwords safe in Python? ›

Use a cryptographic pepper. A pepper is added to the password and the salt before hashing. The big difference is that the pepper is NOT stored in the database but somewhere else safe. This way if an attacker access your database, he would need to brute force the pepper and the password which would be infeasible.

How do I authenticate a password in Python? ›

To authenticate registered users, you have to redirect them to your IDX page, passing “login” as the AUTH_ACTION . Update the server.py file with the code below: @app. route("/login/") def login(): access_token = request.

How do I decrypt an encrypted Python file? ›

Decrypt the encrypted file
  1. Initialize the Fernet object and store it in the fernet variable.
  2. Read the encrypted file.
  3. Decrypt the file and store it into an object.
  4. Then write the decrypted data into the same file nba. csv.
Jun 3, 2022

Which Python library is best for encryption? ›

Best Python Cryptography Libraries for Secure Data Encryption
  • PyCryptodome.
  • Cryptography.
  • PyNaCl.
  • PyOpenSSL.
  • Fernet.
  • Keyczar.
  • M2Crypto.
  • asn1crypto.
Aug 29, 2023

What is the safest encryption algorithm? ›

AES is widely considered invulnerable to all attacks except for brute force. Regardless, many internet security experts believe AES will eventually be regarded as the go-to standard for encrypting data in the private sector. Triple DES.

Why is Python so secure? ›

Python has a number of built-in features and libraries that can help developers write secure code, such as input validation and sanitization, and secure web frameworks such as Django and Flask.

Which hash method is best for password? ›

Choosing a slow algorithm is actually preferred for password hashing. Of the hashing schemes provided, only PBKDF2 and Bcrypt are designed to be slow which makes them the best choice for password hashing, MD5 and SHA-256 were designed to be fast and as such this makes them a less than ideal choice.

What is the most efficient hashing algorithm? ›

SHA-256 is one of the hashing algorithms that's part of the SHA-2 family (patented under a royalty-free U.S. patent 6829355). It's the most widely used and best hashing algorithm, often in conjunction with digital signatures, for: Authentication and encryption protocols, like TLS, SSL, SSH, and PGP.

Which hashing algorithm is used for passwords? ›

PBKDF2 (Password-Based Key Derivation Function 2)

PBKDF2 is a widely-used password hashing algorithm that iteratively applies a pseudorandom function, such as HMAC, to the input password and salt.

What is the best password based encryption algorithm? ›

Recommended encryption algorithms
  • SHA-2. SHA-2 is a family of hash functions widely employed for password encryption and other security applications due to their high level of security. ...
  • Bcrypt. ...
  • PBKDF2. ...
  • Argon2.
Apr 24, 2023

Top Articles
Bajaj Finance Limited SHARE Price Target - BAJFINANCE NSE INDIA Chart Analysis
The History Of Disney Pin Trading - DVC Shop
Hotels
Canary im Test: Ein All-in-One Überwachungssystem? - HouseControllers
Workday Latech Edu
Summit County Juvenile Court
THE 10 BEST Women's Retreats in Germany for September 2024
Academic Integrity
Puretalkusa.com/Amac
Hover Racer Drive Watchdocumentaries
Azeroth Pilot Reloaded - Addons - World of Warcraft
What Is A Good Estimate For 380 Of 60
Oppenheimer Showtimes Near Cinemark Denton
Job Shop Hearthside Schedule
Nitti Sanitation Holiday Schedule
Panorama Charter Portal
Lancasterfire Live Incidents
Kürtçe Doğum Günü Sözleri
Weather Rotterdam - Detailed bulletin - Free 15-day Marine forecasts - METEO CONSULT MARINE
Strange World Showtimes Near Roxy Stadium 14
Traveling Merchants Tack Diablo 4
Yard Goats Score
Best Transmission Service Margate
Boston Dynamics’ new humanoid moves like no robot you’ve ever seen
Parkeren Emmen | Reserveren vanaf €9,25 per dag | Q-Park
Strange World Showtimes Near Savoy 16
Marquette Gas Prices
Fuse Box Diagram Honda Accord (2013-2017)
2004 Honda Odyssey Firing Order
HP PARTSURFER - spare part search portal
Mawal Gameroom Download
Free Robux Without Downloading Apps
Space Marine 2 Error Code 4: Connection Lost [Solved]
2008 DODGE RAM diesel for sale - Gladstone, OR - craigslist
Ramsey County Recordease
Pa Legion Baseball
Is Ameriprise A Pyramid Scheme
Ohio Road Construction Map
5103 Liberty Ave, North Bergen, NJ 07047 - MLS 240018284 - Coldwell Banker
Abigail Cordova Murder
Dineren en overnachten in Boutique Hotel The Church in Arnhem - Priya Loves Food & Travel
Theater X Orange Heights Florida
Used Sawmill For Sale - Craigslist Near Tennessee
Mail2World Sign Up
Ihop Deliver
25100 N 104Th Way
antelope valley for sale "lancaster ca" - craigslist
Buildapc Deals
Minecraft Enchantment Calculator - calculattor.com
Pauline Frommer's Paris 2007 (Pauline Frommer Guides) - SILO.PUB
Latest Posts
Article information

Author: Lakeisha Bayer VM

Last Updated:

Views: 5581

Rating: 4.9 / 5 (69 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Lakeisha Bayer VM

Birthday: 1997-10-17

Address: Suite 835 34136 Adrian Mountains, Floydton, UT 81036

Phone: +3571527672278

Job: Manufacturing Agent

Hobby: Skimboarding, Photography, Roller skating, Knife making, Paintball, Embroidery, Gunsmithing

Introduction: My name is Lakeisha Bayer VM, I am a brainy, kind, enchanting, healthy, lovely, clean, witty person who loves writing and wants to share my knowledge and understanding with you.