Hiding and Encrypting Passwords in Python?


Security is crucial in the current digital era. In our work as developers, we frequently handle confidential data like passwords. It is essential to use the right methods for password encryption and concealment in order to secure this sensitive data. Many accessible techniques and modules in Python can assist us in achieving this objective. With an explanation of the fundamental ideas and examples of useable implementations, this article investigates the best techniques and methods for concealing and encrypting passwords in Python.

The Importance of Password Security

In order to protect user accounts and sensitive information, passwords act as the first line of protection. But keeping passwords in plain text might seriously compromise your security. The passwords are easily retrievable and can be used improperly by an attacker if they have access to the application's database or files. Adopting strategies that limit password leakage and make it harder for attackers to read them is therefore crucial.

Hiding Passwords: Using getpass module

The first step towards securing passwords is to prevent them from being displayed on the screen while the user enters them. The getpass module in Python provides a simple and effective way to achieve this. By utilizing the getpass function, we can prompt the user for a password without echoing the input on the terminal. This ensures that the password remains hidden from prying eyes.

Hashing Passwords: One−Way Encryption

Password security is frequently achieved via hashing. It entails employing a hash algorithm to transform a password into a fixed−length string of characters. Reverse engineering the original password from the resultant hash is quite challenging since the resulting hash is unique to the password. Through the hashlib module, Python offers a number of hash methods, including MD5, SHA−1, and SHA−256. It is crucial to keep in mind that previous hashing algorithms like MD5 and SHA−1 no longer qualify as safe owing to flaws. Use of safer algorithms like SHA−256 or bcrypt is advised.

Salting Passwords: Adding Randomness to the Hash

Hashing alone may not be sufficient to protect passwords against attacks like rainbow tables or brute−force cracking. To further enhance security, we can introduce a technique called salting. A salt is a random value appended to the password before hashing. This random value adds uniqueness to each password hash, even if the original passwords are the same. By using salts, we can mitigate the risks associated with hash collisions and significantly increase the difficulty of cracking hashed passwords.

Using Key Derivation Functions: Strengthening Password Hashing

Key derivation functions (KDFs) provide a more secure approach to hashing passwords. These functions, such as bcrypt and PBKDF2, incorporate additional security measures like multiple iterations and customizable work factors. By increasing the computational cost of generating password hashes, KDFs slow down the cracking process and make it more resource−intensive for attackers. The bcrypt algorithm, in particular, is highly recommended due to its adaptive hashing function and resistance against brute−force attacks.

Storing Passwords Safely: Database Considerations

Passwords must normally be kept permanently in a database for most applications. It is essential to use safe procedures while saving passwords in order to avoid unwanted access. A few excellent practices include employing strong database credentials, encrypting the password hashes, and limiting access to the database. Use parameterized queries and ORM (Object−Relational Mapping) libraries, as well as database frameworks with built−in security measures, wherever possible.

Protecting Passwords in Transit: HTTPS and SSL/TLS

Passwords are vulnerable when transmitted over the network. To safeguard passwords during communication between the client and server, it is essential to use secure protocols such as HTTPS and SSL/TLS. These protocols encrypt the data exchanged between the client and server, ensuring the confidentiality and integrity of sensitive information, including passwords. By implementing SSL/TLS certificates on the server−side and configuring secure communication channels, we can protect passwords from interception and unauthorized access.

Password Encryption: Two−Way Encryption

Sometimes it's important to encrypt passwords in a way that allows us to decrypt them afterward and get the original password. Such circumstances call for two−way encryption, sometimes referred to as symmetric encryption. Through its cryptography package, Python offers a number of encryption techniques, including DES and AES (Advanced Encryption Standard). We can safely store and recover passwords by encrypting them using a secret key.

Protecting Against Common Attacks

In addition to implementing password hiding and encryption techniques, it is essential to be aware of common password−related attacks and take necessary precautions. This includes defending against brute−force attacks, enforcing password complexity requirements, implementing account lockout policies, and educating users about password security best practices.

Python Implementation


import getpass 
import hashlib 
from cryptography.fernet import Fernet 
# Password Hiding: Hiding password during input password = getpass.getpass("Enter your password: ") 
# Password Hashing: Hashing password using SHA-256 hashed_password = hashlib.sha256(password.encode()).hexdigest() 
print("Hashed Password:", hashed_password) 
# Password Salting: Adding salt to the password before hashing salt = "somesalt" salted_password = hashlib.sha256((password + salt).encode()).hexdigest() 
print("Salted Password:", salted_password) 
# Password Encryption: Encrypting and decrypting password using Fernet symmetric encryption key = Fernet.generate_key() cipher_suite = Fernet(key) 
# Encrypting password encrypted_password = cipher_suite.encrypt(password.encode()).decode() 
print("Encrypted Password:", encrypted_password) 
# Decrypting password decrypted_password = cipher_suite.decrypt(encrypted_password.encode()).decode() 
print("Decrypted Password:", decrypted_password) 


Input is abc 
Enter your password: ·········· 
Hashed 	Password: 
Salted 	Password: 
Encrypted Password: gAAAAABkb6xcfvsOZxb3PTfyJlTtmpOYx7T4XpF6WyhSIYwnXrs-UzIuuHd0xMlzj8ZV2wRy5Lg50UFipiX-na0cKgzHBbUTg== 
Decrypted Password: abc 

Password Hiding

The password is concealed during input using the getpass.getpass() method. The password won't appear on the screen when the user enters it. This guards against shoulder surfing and hides the password from prying eyes.

Password Hashing

Calculating the password's SHA−256 hash requires the hashlib.sha256() method. Passwords are changed into fixed−length character strings by the one−way process of hashing. In this illustration, a 256−bit hash is produced via the SHA−256 algorithm. Due to its degree of security and ability to perform password verification without saving the actual password, hashing is a popular approach for password storage.

Password Salting

To enhance the security of the hashed password, a salt is added before hashing. The salt is an additional random value that is concatenated with the password before hashing. This prevents the use of precomputed tables (rainbow tables) for password cracking. In the example, the salt is added by concatenating it with the password before calculating the SHA−256 hash.

Password Encryption

The password is subjected to symmetric encryption using the cryptography.fernet module. The same key is necessary for both encryption and decryption in a symmetric encryption technique. Using Fernet.generate_key(), a random key is created in this example. The key is then used to build a cipher suite using the module's Fernet class. Using cipher_suite.encrypt() and cipher_suite.decrypt(), the password is encrypted and decrypted, respectively.


Protecting passwords is a critical aspect of application security. By implementing effective password hiding and encryption techniques in Python, we can significantly enhance the security of our applications and protect user credentials. From hiding passwords during input to hashing, salting, and employing secure encryption algorithms, there are various methods available to safeguard passwords. It is essential to understand the strengths and limitations of each technique and apply them appropriately based on the specific requirements of the application. By prioritizing password security and following best practices, we can mitigate the risks of unauthorized access and ensure the privacy and integrity of sensitive user information.

Updated on: 24-Jul-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started