Assignments  »  Strings  »  Set 1  »  Solution 9

Write a program in python that accepts a string to setup a passwords. Your entered password must meet the following requirements: * The password must be at least eight characters long. * It must contain at least one uppercase letter. * It must contain at least one lowercase letter. * It must contain at least one numeric digit.

Your program should should perform this validation.

Source Code

Enter your password: snake That password is not valid. Enter your password: kangaroo That password is not valid. Enter your password: Cat20 That password is not valid. Enter your password: Elephant6 That is a valid password.

Storing and Retrieving Passwords Securely in Python

Storing And Retrieving Passwords Securely In Python

Passwords provide the first line of defence for securing access to applications and online accounts. As developers, we have a responsibility to store user passwords securely. Improper password storage can put users’ personal information and data at risk.

In this comprehensive guide, we’ll cover Python’s best practices for securely saving passwords to a database and retrieving them for authentication. Whether you’re building a new application or improving security in an existing system, this guide has you covered.

Also read: Random Password Generator in Python | GUI Tkinter

Why Password Security Matters

When an application needs to authenticate users, it must have some way to verify their identity. The most common method is asking the user to provide a username and password. These passwords serve as sensitive “keys” that grant access.

If poorly stored, passwords can be stolen in database breaches. Hacked databases are sold online, exposing users’ credentials. With a stolen password, attackers can:

  • Log into the user’s account to steal private data
  • Access integrated third-party accounts like email and financial services
  • Commit identity fraud using personal information from breached accounts

Securing user passwords helps mitigate these risks. Proper password storage also builds user trust in your application.

Core Concepts of Secure Data Storage

Before diving into Python code, let’s review some core concepts for safely handling user passwords:

Hash Functions

A cryptographic  hash function  encodes data in a one-way, irreversible format. The same input always produces the same fixed-length output. But there is no way to “reverse” the output and reveal the original input.

This allows matching passwords without actually storing passwords. When a user signs up, their password is hashed. The hash value is stored instead of the plain text password. Later during login, the user-entered password is hashed again. If the newly generated hash matches the stored hash, the passwords are the same.

Also read: How Do I Return Hash Values of a 1D array?

Most users have common passwords like “123456” and “password”. This makes hash collisions more likely for identical passwords.

A  salt  is random data added to each password hash. Salting ensures every hashed password has a unique value, even if the plain text passwords are identical. This protects against precomputed “rainbow table” attacks that crack hashed passwords.

Performing computationally intensive  iterations  of hash functions further slows brute force attacks. With key derivation functions like PBKDF2, we can configure hundreds of thousands of hash iterations. This massively delays dictionary and brute force attacks.

A  pepper  is an application-wide secret value added to password hashes for extra protection. Unlike salts which are unique per user, the pepper is the same across all passwords. It provides an additional obstacle for leaked password databases. If the pepper isn’t known, brute forcing hashes is extremely difficult.

Python Password Storage Process

Equipped with those core concepts, let’s outline the secure password workflow:

  • User signs up and enters a password
  • Generate a long, random salt value
  • Optionally append a standard pepper value
  • Hash the salted password thousands of times
  • Save the salt, hash iterations, hash value to the user’s database record

When authenticating later:

  • Retrieve the user’s salt, iterations, and hash value from the database
  • Salt and hash the entered login password using the same parameters
  • Compare the login hash to stored hash to check for match

Next, we’ll explore Python code implementations for each step.

Generating Random Salts

Here is function to create a cryptographically-secure 16 byte (128 bit) random salt value:

The  os.urandom()  function from Python’s standard library generates secure random byte values. We take 16 random bytes for a 128 bit salt.

Alternatively, the  secrets module  introduced in Python 3.6 provides a  secrets.token_bytes()  method for generating secure random data.

Salts should have sufficient randomness to make collisions unlikely. Longer byte lengths are ideal to prevent rainbow table attacks tailored to shorter salts.

Hashing Passwords

Python’s  hashlib module  implements standardized cryptographic hash functions for securely encoding text and bytes.

For example, here is how to hash a password with SHA-256:

We salt each password with the random  generate_salt()  value.  hashlib.sha256()  expects byte input, so the password string is encoded. Calling  .hexdigest()  returns the hash value as a hexadecimal string.

The salt bytes concatenated with the hexadecimal digest is the final salted, hashed password. We’ll split these apart later during verification.

SHA-256 offers decent protection for passwords. For extra security, key derivation functions like  PBKDF2  hash thousands of times to resist brute force cracking.

Key Derivation with PBKDF2

Python’s hashlib implements PBKDF2 key derivation as hashlib.pbkdf2_hmac(). The example below handles user sign up, generating a secure salted hash with 100,000 PBKDF2 iterations:

We pass the hash algorithm, password, salt, and iterations into  hashlib.pbkdf2_hmac() . It returns the derived key as bytes. The final password hash concatenates the random salt and hash value.

PBKDF2 massively slows brute force attacks compared to single-round hashes. 100,000 iterations add just 150 milliseconds delay – negligible for users, but a lifetime for attackers!

Adding an Application-Wide Pepper

We can require a standard pepper value across all password hashes for additional safety. This pepper is an extra secret attacker must know to crack hashes.

Here is an updated example using a pepper named  SECRET_KEY :

We concatenate the pepper to the user’s password before hashing. Now, an attacker must discover both the pepper value and salt to brute force a match.

Peppers provide an extra layer of protection if your hashed passwords are leaked. They are toughest to crack when the pepper value differs from salts and is unknown to attackers.

Storing Hashed Passwords using Python and MySQL

With secure hashing functions implemented, let’s save user passwords. Hashed passwords should be stored in a database table alongside related authentication details like:

  • Random salt value
  • Hash algorithm name
  • PBKDF2 iterations
  • Username or ID foreign key

Here is an example user  accounts  table schema with a  password_hash  column:

When a new user signs up, we’ll run our hashing procedure and insert hash details into the table:

The user’s login credentials are securely saved in the database, ready for verification during login.

Authenticating Users using Secured Password Hashes

When users attempt to log in with their password, we’ll fetch their password hash details from the database.

We re-hash the entered password using the original salt, algorithm, and iterations. We can verify if the password matches after comparing the newly generated hash to the stored hash.

Here is an example login code:

We reuse the original salt, algorithm, and iteration count to re-hash the entered password. Now, comparing hashes rather than plain text we can rest assured that the actual passwords are never exposed.

This allows verifying logins without storing or exposing real passwords. Even if your database is breached, properly hashed values are difficult for attackers to reverse.

Securely handling user passwords is crucial for building trust in any application. Never store plain text passwords – instead, properly hash and salt them.

Python’s standard library has excellent tools for password security:

  • os.urandom  and  secrets.token_bytes  generate cryptographically-secure random salt values
  • hashlib  provides access to fast, modern hashing functions like SHA-256
  • PBKDF2 hashes passwords hundreds of thousands times resisting brute force
  • Peppers provide application-wide secrets protecting leaked hashes

With hashes safely stored in the database, users are protected even in the event of a breach. With these best practices, we can authenticate users without ever handling their real plain text passwords.

5 Best Ways to Check If a Password Meets Criteria in Python

💡 Problem Formulation: When building a user authentication system, it’s critical to ensure that passwords meet specific security criteria before being accepted. This article discusses how to construct a Python program capable of validating a password against custom rules such as length, presence of special characters, digits, and mixed case. For example, an input might be a string "Password123!" , and the desired output is a boolean indicating whether it satisfies the defined criteria.

Method 1: Using Regular Expressions

Regular expressions in Python provide a powerful way to check for complex patterns in strings. By defining a regular expression pattern, this method enables checking a password for multiple criteria such as length, lowercase, uppercase, numbers, and special characters in a compact form.

Here’s an example:

Output: True

This function is_valid_password uses a regular expression that enforces at least one lowercase letter, one uppercase letter, one digit, one special character, and a minimum length of 8 characters. The re.match() checks the password against the pattern, returning a match object if found, which gets converted to a boolean.

Method 2: Using Conditional Statements

This approach involves a series of if-else statements to check each criterion one by one. It offers clear, explicit logic for each rule and is easily understandable for those not familiar with regular expressions.

In the code snippet above, we define a function is_valid_password that uses five boolean variables to check each condition. The final condition uses the all() function to ensure every criterion is met.

Method 3: Using Iterative Checks

This method iterates through the password string and checks for each condition during the iteration. It’s ideal for cases where you may want to stop checking as soon as one criteria fails, thus possibly saving some computational resources.

This function starts by checking the length, then initializes a dictionary to keep track of whether each condition has been met. As it iterates, it updates the dictionary accordingly. After completing the loop, it uses the all() function to ensure all conditions are True.

Method 4: Using OOP Principles

Applying Object-Oriented Programming principles, this method involves creating a password validator class. Different criteria are checked using methods, offering a modular approach that can easily be expanded or modified.

Here, the PasswordValidator class encapsulates the logic for password validation, providing an interface via the is_valid() method. Private methods prefixed with an underscore check individual criteria. Using classes allows for easy extension and maintenance.

Bonus One-Liner Method 5: Using a Functional Approach

The functional approach uses higher-order functions like all() and any() within a single expression to check all criteria at once. It’s concise and utilizes the capabilities of Python’s built-in functions elegantly.

The one-liner is_valid_password combines the use of a lambda function with list comprehension and boolean checks. This functional approach is concise but can be harder to read and debug, especially for those not well-versed in functional programming concepts.

Summary/Discussion

  • Method 1: Regular Expressions. It allows compact code and is highly efficient for complex pattern matching. However, regex patterns can become difficult to read and maintain for non-trivial requirements.
  • Method 2: Conditional Statements. This method’s strength is in its readability and simplicity. It may not be as concise as other methods and can become cumbersome for more complex validation rules.
  • Method 3: Iterative Checks. Efficient in early exit scenarios. However, its explicit iteration is more verbose compared to using higher-level abstractions like in other methods.
  • Method 4: Using OOP Principles. Enhances code maintainability and modularity, making it powerful for applications that require complex password validation frameworks. The primary weakness is additional overhead in setting up the class structure.
  • Bonus Method 5: Functional Approach. Offers a succinct solution that is elegant and expressive but may present a steep learning curve and reduced readability for some programmers.

Emily Rosemary Collins is a tech enthusiast with a strong background in computer science, always staying up-to-date with the latest trends and innovations. Apart from her love for technology, Emily enjoys exploring the great outdoors, participating in local community events, and dedicating her free time to painting and photography. Her interests and passion for personal growth make her an engaging conversationalist and a reliable source of knowledge in the ever-evolving world of technology.

How to Build a Password Manager in Python

Want to code faster? Our Python Code Generator lets you create Python scripts with just a few clicks. Try it now!

In this tutorial, we’re going to be building our own custom password manager. I’m pretty sure you know what a password manager is, and its importance. But for formalities, a password manager is an application that securely stores organizes, and manages a user's passwords for various online accounts and services. It is used to simplify the process of creating and remembering complex and unique passwords for enhanced online security. 

Basically, it saves us the hassle of remembering passwords for different accounts and complex passwords. This is because security-wise, we’re expected to use different passwords for different accounts so that if an account is compromised, using the same credentials wouldn’t grant hackers access to another account owned by the same victim. We are also expected to use strong, unguessable passwords. We talked about this in a previous tutorial .

The basic functionalities of our password manager include: logging in (only we should have access to our password manager using our username and master password), adding passwords, retrieving passwords (obviously), viewing saved websites (to be sure which websites we have saved) and copying the retrieved password to our clipboard as it saves us the time of having to type it. I don’t know about you, but I can be very lazy.

We are going to be storing the saved passwords in a JSON file. But it will be encrypted so that even if someone manages to get access to the file, it would be useless to them. We’ll also store our login credentials (username and master password) in a JSON file. Similarly, it would be hashed so it’s useless to unauthorized parties.

So do me a favor. Create a folder, and create a Python file in it. password_manager.py or whatever you like. During the course of running this program, we are going to create two JSON files.  One is passwords.json and the other, user_data.json .

The passwords.json file is where we’ll store our saved passwords, and the user_data.json is where we will store login credentials. Please bear in mind that you do not have to create these files beforehand as we do that automatically in the program.

We’re using Python 3. Any version above 3.6 is fine as we’re going to make use of F strings. Also, to copy our retrieved password to our clipboard, we’ll make use of the pyperclip module. To install, open up your command prompt (or terminal) and run:

We're also installing the cryptography library for encryption .

Now, the fun can begin. Open up your Python file and let’s import the necessary libraries:

json  is a library for encoding and decoding JSON (JavaScript Object Notation) data, commonly used for data serialization and interchange.

hashlib is a library that provides secure hash functions, including SHA-256, for creating hash values from data, often used for password hashing and data integrity verification. You can check this tutorial on how to use it.

getpass : A library for safely and interactively entering sensitive information like passwords without displaying the input on the screen. Similar to the way the Linux terminals are.

os : A library for interacting with the operating system, allowing you to perform tasks like file and directory manipulation.

pyperclip : A library for clipboard operations, enabling you to programmatically copy and paste text to and from the clipboard in a platform-independent way.

sys : This module is a built-in Python module that provides access to various system-specific parameters and functions.

cryptography.fernet : Part of the cryptography library, it provides the Fernet symmetric-key encryption method for securely encrypting and decrypting data. You can check this tutorial for more info.

After importing the necessary libraries, we create a function for hashing . This function would be used to hash our master password upon registration:

After that, we create a function for generating a key. This key would be used to encrypt our passwords upon adding, and decrypt upon retrieval. Please bear in mind that only the key we used to encrypt our passwords, can be used to decrypt it. If you use another, you’ll get errors. I’m saying this because this is a function and anytime it gets executed (you call it), it generates a new key. This is worth noting in case you want to use the function in another program. In this program, we generate it once, store it, and keep using it, so you have nothing to worry about.

Next up, we fernet the key (making it able to encrypt and decrypt our passwords) and create functions for encrypting and decrypting:

After that, we create a function for owner registration. Saving credentials in the user_data.json file. Remember, we’ll be hashing the password. This is the master password. The keys to the kingdom:

Next up, we create a function for logging a user in. It accepts a username and password from a user, it then hashes the password entered by the user. If the hash of the entered password is the same as the hash of the saved password (in the JSON file) and the usernames are also the same, it grants access. Otherwise, you know the rest. This is how password-cracking processes take place.

In secure systems, passwords are stored as hashes and not plain texts. So attackers keep trying the hashes of different known passwords in the hope of gaining access to the system. This is why we are advised to use strong, unique passwords:

Next is a function to view websites saved in our password manager. Remember that the order in which functions are written doesn’t really matter. It’s the calling that matters:

Next up, we generate or load our key. If it’s the first time, we generate and save our key. Otherwise, we just load it:

Basically, this function checks if an encryption_key.key file exists. If it does, it loads it for use. If it doesn’t, it creates it and saves our unique key in it. If it exists, it means it isn’t our first time running the program so it just loads our unique key. This key is the heart of this program. You want to make sure you keep it safe. 

Now let's make a function to add passwords:

Here, we encrypt the passwords and save them in our JSON file.

Let's create a function to retrieve a saved password:

This function takes in the website as a parameter and returns the decrypted password to the user (us).

Finally the body of the program. Option displays and function calling according to the user’s input:

When you run the program (after fulfilling all the requirements earlier stated), the first thing you want to do is register . Afterwards, you can log in and play with all the features. Don’t forget that when you retrieve a password, it copies to the clipboard. Feel free to test that by pasting it to see for yourself.

Here's a single run:

Here's another run as a screenshot:

password assignment python

After registering, your  user_data.json  should look like this:

password assignment python

After playing around, your  passwords.json  file should look like this:

password assignment python

Please bear in mind that full-scale password managers are often more complex than this. The essence of this tutorial is to try to show you the methodology involved in this process. I hope I was able to do that.

Get the complete code here .

In this tutorial, we've walked you through creating your own custom password manager using Python. We've covered the essentials from securing your login credentials with hashing to saving and retrieving encrypted passwords from a JSON file. By leveraging Python libraries like json , hashlib , getpass , and cryptography , we built a functional, secure password manager. Now, you don't have to remember complex passwords; let Python do the work for you!

Finally, if you're more interested in cryptography, then I highly recommend you check our Cryptography with Python eBook ! It'll equip you with the foundations and practical skills in the world of Cryptography; check it out here .

Learn also: How to Make a Login Password Guesser in Python

Happy coding ♥

Take the stress out of learning Python. Meet our Python Code Assistant – your new coding buddy. Give it a whirl!

How to Make a Login Password Guesser in Python

How to Make a Login Password Guesser in Python

Master the art of ethical hacking with this hands-on tutorial on creating a Python-based login password guesser using brute-force techniques. Designed for educational purposes, this guide will level up your cybersecurity expertise.

How to Make a Phone Number Tracker in Python

How to Make a Phone Number Tracker in Python

Learn how to build a phone number tracker in Python using phonenumbers, OpenCage and folium libraries.

How to Crack Hashes in Python

How to Crack Hashes in Python

Learn how to crack hashes using Python's hashlib library and a brute-force approach with a wordlist. Gain insights into various hashing algorithms and understand the importance of secure data handling.

Comment panel

Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!

Ethical Hacking with Python EBook - Topic - Top

Join 40,000+ Python Programmers & Enthusiasts like you!

  • Ethical Hacking
  • Machine Learning
  • General Python Tutorials
  • Web Scraping
  • Computer Vision
  • Python Standard Library
  • Application Programming Interfaces
  • Game Development
  • Web Programming
  • Digital Forensics
  • Natural Language Processing
  • PDF File Handling
  • Python for Multimedia
  • GUI Programming
  • Cryptography
  • Packet Manipulation Using Scapy

Ethical Hacking with Python EBook - Topic - Middle

New Tutorials

  • How to Extract Metadata from Docx Files in Python
  • How to Make a Grep Clone in Python
  • How to Remove Metadata from PDFs in Python
  • How to Find Past Wi-Fi Connections on Windows in Python
  • How to Build a Username Search Tool in Python

Popular Tutorials

  • How to Convert Speech to Text in Python
  • How to Read Emails in Python
  • How to Extract Tables from PDF in Python
  • How to Make a Keylogger in Python
  • How to Encrypt and Decrypt Files in Python

Ethical Hacking with Python EBook - Topic - Bottom

Claim your Free Chapter!

password assignment python

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

password-checker

Here are 37 public repositories matching this topic..., chrispetrou / fastaudit.

:shipit:

  • Updated Feb 2, 2023

nk4456542 / Password-Checker

Check your password securely without transmitting your password through internet.

  • Updated Nov 18, 2020

lucifercr07 / pwnd_checker

This application checks if your account has been breached and credentials are publicly accessible. Also checks if password breached and suggests strong passwords.

  • Updated May 22, 2023

kit4py / password_checker

checking your password in leaked databases using API

  • Updated Apr 20, 2023

maandree / passcheck

Passphrase strength evaluator

  • Updated Dec 5, 2015

PrashantMhrzn / password-generator-and-checker

Two programs that generate a strong password and checks if a password has been leaked or not.

  • Updated Aug 9, 2020

knownbymanoj / Password-strength-checker

A python file which checks your password if it has been breached or safe to use securely without trusting website's https connection and also send only 5 hexadecimal characters of hash to server to make sure server is not compromised and get checks done on your own personal computer without trusting any other device.

  • Updated Aug 9, 2021

Robin-mlh / TKPass

A password toolkit: Evaluate, generate, and much more.

  • Updated Oct 24, 2023

0liverFlow / PasswordChecker

PasswordChecker is a python script that evaluates a user's password strength.

  • Updated Jun 8, 2023

gorouflex / PassGen

(Simple) Password Generator and Checker

  • Updated Mar 28, 2024

0KvinayK0 / MistakePass

This is a secure password checker written in Python that uses data harvested from haveibeenpwned API to verify whether the password you are using has already been leaked.

  • Updated May 27, 2023

sandeepme / Breached

Check if your email and/or password has been breached.

  • Updated May 8, 2019

TheMuffinMane / Password-Strength-Checker

python password strength checker

  • Updated Sep 30, 2023

AswinBarath / Password-checker

The most secure password checker project

  • Updated Jan 21, 2021

Wocx32 / Passcheck

Aesthetically pleasing password checker

  • Updated Mar 22, 2022

iiiiOreo / Password-Manager

Python Tkinter-based Password Manager with AES encryption, Google Authenticator 2FA, and integrated password generator and checker for enhanced security and streamlined credential management.

  • Updated Feb 23, 2024

Mahnatse-rgb / password-checker

  • Updated Apr 17, 2020

noahfree / password-checker

Essentially, this program takes an inputted password from the user and outputs whether or not it is a good password based on the requirements specified in README.md.

  • Updated Nov 5, 2022

Samay30 / password_strength_checker

This Python tool is designed to help users assess the strength of their passwords by incorporating the most up-to-date guidelines for password security. It utilizes a combination of techniques including searching for common passwords and analyzing password characteristics such as length, character types (alphanumeric, uppercase), and more.

  • Updated Feb 7, 2024

ayume-gah / waspada_penipuan_online

hackathon project of women in tech: cybersecurity and python, a website using streamlit

  • Updated Aug 18, 2022

Improve this page

Add a description, image, and links to the password-checker topic page so that developers can more easily learn about it.

Curate this topic

Add this topic to your repo

To associate your repository with the password-checker topic, visit your repo's landing page and select "manage topics."

DEV Community

DEV Community

Posted on Mar 25, 2020

Make a password manager with python: Making the basic mechanisms

Every password manager must save the password a user gives and output it when the user needs it. We are gonna apply the same thing to our password manager. We will first start by creating a .txt file to store the passwords.

Get the full code from here with some extra addition to get the code up and running.

1| Create a text file in python

Making a text file in python is fairly simple.

At first we are checking if the file info.txt exists in our directory where the python file is. If not, just simply create one. 'w' means we are creating the file to write something. If you want to know more about files follow this.

2| Write to file

Alike you print in the terminal, you can similarly write into a file. just use the write to write inside a file. Here is how.

At first, we are opening the file we just have created. 'a' argument means we will append something in that file. We could have used 'w' which stands for write. But every time we open a file with a 'w' argument, it erases everything written previously. Which we don't want at all. So, we will continue with 'a'.

Then we take input from the user about his user name, password and the website. I'm using the empty print statement to space things out in the terminal so that it looks good. Then we are simply creating three string variables to store the username, password and website.

And then we will write to our file by using the write function. Remember, unlike print , write doesn't add a new line every time we call it. So, use \n if you want to add a new line in your file. That's it! Now our user can save passwords in info.txt file(or whatever you call).

3| Output the password

This time we will see what passwords the user has saved. The bellow function will get the job done.

Just like our previous function, we are opening our file at first. But this time, instead of append, we will open the file as read(use r ). Then we will create a new variable content which will be the place holder of the contents in the file. And then just simply print it out. BOOM!!!

Yeah! I know this function will print all the passwords which we don't want. For that, we will make need to a search operation. But in order to keep the post as simple as possible, I will end it just right here. In the next post, we will make a search option.

You can get the full code here with some extra addition to get the code up and running.

Until next time, stay safe, stay at home. 💗Love from humanity💗

Top comments (7)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

banajitrajbongshi profile image

  • Joined Jun 1, 2020

thanks Sir , I can be able to easily understand the basics. But my question how can I use these database to use in log in programme? please help me Sir

  • Location Bangladesh
  • Work Student
  • Joined Nov 21, 2019

First of all I am not a sir(it makes me uncomfortable 😅).

Secondly, sorry because I didn't continued the series for some reasons.

Finally, to answer your question, use selenium. It's a python web automation framework. I would take the login data and then input them in a website using selenium.

emperor profile image

  • Joined Mar 21, 2021

Well you can use MySQL, SQLite or PostgreSQL as these are the common ones. You can check their functioning on google or watch a video on YouTube. As for log in programmer, you can also do it without a database. user_name and password are two variables. When you enter a value in them you can create a file with the name {user_name}.{password}.txt. So basically you are opening the file where your passwords are save and your file name is your username.password

0x4a0x410x4b profile image

  • Joined Aug 15, 2020

This is a terrible idea.

Learning the basics of python (or anything for that matter) is a good thing, but you seem to start at the wrong end. Password Managers are not used to just store passwords, they are used to store them encrypted and save, they are supposed to save yourself from using the same password for everything. Nothing can be learned by reading your 3 articles on the topic. Bad practices such as not using context managers or the use of CamelCase (These two are not terrible but when trying to teach you should always try to teach the best practices) as well as suggesting that it is totally fine to store passwords unencrypted without anything to protect them. If you wanted to teach people about python then take down this article and start simple.

jonasgozdecki profile image

  • Joined Apr 20, 2021

Please, move this a new post as "How to read/write text file with data in Python". The context of "Password manager" is the opposite of store plain text sensitive data. Advice: Do not mention your employee's company name nor project. They may suffer more invasion attacks motivated by no security worries in your post.

vlasales profile image

  • Joined Jul 2, 2018

It's too complicated. Use a database (eg SQLite) instead.

Thanks, I will try it for sure. 😉

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

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

jamescroissant profile image

What is ”this” in JavaScript?

Yu Hamada - Apr 18

mikeyoung44 profile image

Megalodon: Efficient LLM Pretraining and Inference with Unlimited Context Length

Mike Young - Apr 16

ResearchAgent: Iterative Research Idea Generation over Scientific Literature with Large Language Models

The illusion of state in state-space models.

Mike Young - Apr 17

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

How to Build a Password Manager in Python

  • How to Brute Force ZIP File Passwords in Python?
  • How to Crack PDF Files in Python?
  • How to Extract Chrome Passwords in Python?
  • getpass() and getuser() in Python (Password without echo)
  • Hashing Passwords in Python with BCrypt
  • Hiding and encrypting passwords in Python?
  • Password validation in Python
  • How to change password of superuser in Django?
  • Generating Strong Password using Python
  • Storing passwords with Python keyring
  • Password Management in Cyber Security
  • How to Install maskpass package in Python on Linux?
  • Create a Random Password Generator using Python
  • Python Program to generate one-time password (OTP)
  • Remember and copy passwords to clipboard using Pyperclip module in Python
  • Categorize Password as Strong or Weak using Regex in Python
  • GUI to generate and store passwords in SQLite using Python
  • pwd module in Python
  • Best Password Managers for 2022
  • Adding new column to existing DataFrame in Pandas
  • Python map() function
  • Read JSON file using Python
  • How to get column names in Pandas dataframe
  • Taking input in Python
  • Read a file line by line in Python
  • Dictionaries in Python
  • Enumerate() in Python
  • Iterate over a list in Python
  • Different ways to create Pandas Dataframe

We have a task to create a Password Manager in Python. In this article, we will see how to create a Password Manager in Python.

What is a Password Manager?

A Password Manager in Python is a tool in which we can add the username and password. Additionally, it allows us to retrieve the username and password. We also have the option to view all added usernames and passwords with just one click. Furthermore, if we want to delete a username and password, we can do so with a single click.

Password Manager in Python

Below is the step-by-step guide for creating a Password Manager in Python :

Create a Virtual Environment

Now, create the  virtual environment  using the below commands

Installation

Here, we will install the following libraries and modules:

  • Install Python
  • Install Tkinter

Writing the Tkinter Code (app.py)

Below are the step-by-step explanation of the app.py code:

Step 1: User Input and Password Addition

In below code add() function captures the username and password entered by the user in the Tkinter GUI. It checks if both fields are non-empty. If so, it appends the username and password to a file named “passwords.txt” and displays a success message using a Tkinter messagebox.

Step 2: Retrieve and Display Password

In below code get() function retrieves a username entered by the user and reads a file named “passwords.txt” to create a dictionary of username-password pairs. If the entered username exists, it displays the corresponding password; otherwise, it indicates that the username doesn’t exist.

Step 3: Retrieve and Display All Passwords

In below code the getlist() function reads the “passwords.txt” file, creates a dictionary of all username-password pairs, and displays a messagebox containing the entire list of passwords. If the file is empty, it notifies the user that the list is empty.

Step 4: Delete User and Update File

In below code the delete() function takes a username input from the user, reads the “passwords.txt” file, excludes the specified username, and writes the modified data back to the file. If the deletion is successful, it displays a success message; otherwise, it shows an error message.

Step 5: Tkinter GUI Setup

below code has main part of the code initializes a Tkinter GUI window, sets its dimensions and title, and creates input fields for username and password. Four buttons are provided for adding passwords ( Add ), retrieving a password ( Get ), listing all passwords ( List ), and deleting a user ( Delete ).

Complete Code

Below is the complete code for main.py file that we have used in our project.

Password Manager In Python

Please Login to comment...

Similar reads.

  • Python-projects
  • Python-tkinter
  • Python Programs

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Python Forum

  • View Active Threads
  • View Today's Posts
  • View New Posts
  • My Discussions
  • Unanswered Posts
  • Unread Posts
  • Active Threads
  • Mark all forums read
  • Member List
  • Interpreter

Python Password Saver Assignment

  • Python Forum
  • Python Coding
  • 0 Vote(s) - 0 Average
  • View a Printable Version

User Panel Messages

Announcements.

password assignment python

Login to Python Forum

Issue on XMLRPC working with LoadBalancer

I am working on a Python assignment for Distributed Computing Systems and running into some issues . I have 3 VM’s running: AirlineServer1 , AirlineServer2 and a LoadBalancer which calls the two airline services in a RoundRobin mode. The LoadBalancer has functions to get list of flights, reserve a flight or cancel a flight. Then, finally, from my Mac node, I run a VacationClient which instead of calling the airline functions, it will call the LoadBalancer.

I run into the issue below after running the client. I checked DNS names, ports and firewall is disabled in the VM:

This is the VacationClient code:

This is the LoadBalancer:

This is one of the AirlineServers (AirlineServer2 is same code but different DNS and same port)

Can someone help me figure it out since I am new to Python and possible point out more error that may occur please? Thanks

This error or something similar will occur if the server is not accepting connections (or if the client attempts to connect to the wrong server). Before jumping to separate VMs, rule out a Network, Firewall, or DNS issue by a) setting ThiagoAirlineServer and all IP addresses to 127.0.0.1 (or localhost ), b) picking new distinct ports for each connection if needs be, and c) by running each server’s code in a separate Python process, e.g. in its own terminal session (by the way, it’s best practise to set config data like URLs and IP addresses in config files or in env variables - it makes testing and debugging much easier, amongst other benefits. The Twelve-Factor App and launching and tearing down a stack like this is very easy with Docker compose if you containerise the services - the containers can still be run on VMs afterwards).

If localhost alone doesn’t narrow it down, try it without the load balancer. And then if not, with only one AirlineServer . If there’s a problem running your code as a simple client / server connection over local host, then it’s worth looking at the Python code in detail.

Related Topics

IMAGES

  1. Check the Strength of any Password using Python Regex

    password assignment python

  2. Password Generator

    password assignment python

  3. Create a Random Password Generator using Python

    password assignment python

  4. Password Generator Python Source Code

    password assignment python

  5. Python

    password assignment python

  6. Password Manager using Python

    password assignment python

VIDEO

  1. Easy Hide Password Input in Python

  2. Python Password Manager

  3. Python Password Program Using While Loop 2023

  4. Generate Password #python Click that sub button

  5. Username and Password Validation in Python [Python In Pidgin]

  6. How to Protect Your Password from Hackers

COMMENTS

  1. Password validation in Python

    Using ascii values and for loop: This code uses a function that checks if a given password satisfies certain conditions. It uses a single for loop to iterate through the characters in the password string, and checks if the password contains at least one digit, one uppercase letter, one lowercase letter, and one special symbol from a predefined list and based on ascii values.

  2. Validation of a Password

    So I have to create code that validate whether a password: Is at least 8 characters long Contains at least 1 number Contains at least 1 capital letter Here is the code: def validate(): ... Stack Overflow. About ... The simplest python validation using normal methods. password = '-' while True: password = input(' enter the passwword : ') lenght ...

  3. Python program to check the validity of a Password

    Input : R@m@_f0rtu9e$ Output : Valid Password Input : Rama_fortune$ Output : Invalid Password Explanation: Number is missing Input : Rama#fortu9e Output : Invalid Password Explanation: Must consist from _ or @ or $ Way 1: Here we have used the re module that provides support for regular expressions in Python. Along with this the re.search ...

  4. 5 Best Ways to Implement a Strong Password Checker in Python

    Method 4: Using Python's any() Function. The any() function in Python is a utility that checks if any element of an iterable is True. It can be used in our password checker to simplify logical conditions when looking for the presence of various character types. Here's an example: def is_strong_password(password):

  5. Python Password Validation Program

    Program in python, check if password is correct or not. Assignments » Strings » Set 1 » Solution 9. Write a program in python that accepts a string to setup a passwords.

  6. Storing and Retrieving Passwords Securely in Python

    The os.urandom() function from Python's standard library generates secure random byte values.We take 16 random bytes for a 128 bit salt. Alternatively, the secrets module introduced in Python 3.6 provides a secrets.token_bytes() method for generating secure random data.. Salts should have sufficient randomness to make collisions unlikely. Longer byte lengths are ideal to prevent rainbow ...

  7. Light Roast 104: Strong Password Detection With Python

    For the purpose of my assignment, I had to use this code to create a program that would also check the user input against a password list. The workflow I decided to build is shown below. image by ...

  8. Mastering Password Security: A Comprehensive Guide with Python ...

    Python Script for Password Exposure Check. Below is a Python script that interfaces with the "Have I Been Pwned" service to check if a password has been exposed:

  9. 5 Best Ways to Check If a Password Meets Criteria in Python

    Method 1: Using Regular Expressions. Regular expressions in Python provide a powerful way to check for complex patterns in strings. By defining a regular expression pattern, this method enables checking a password for multiple criteria such as length, lowercase, uppercase, numbers, and special characters in a compact form.

  10. Secure Password Handling in Python

    crypt is a Python standard library module that provides functions that could be used for password hashing. The algorithms provided are however dependent on your system, and the ones listed in docs aren't as strong as the ones shown above. hashlib is another builtin module. This one however includes strong hashing functions suitable for ...

  11. How to Build a Password Manager in Python

    Learn how to build a secure custom password manager using Python. This tutorial walks you through encryption, data storage, and various functionalities like adding, retrieving, and managing passwords. Elevate your online security game with some hands-on coding.

  12. Python Secure Password Management: Hashing and Encryption #️⃣

    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

  13. password-checker · GitHub Topics · GitHub

    This Python tool is designed to help users assess the strength of their passwords by incorporating the most up-to-date guidelines for password security. It utilizes a combination of techniques including searching for common passwords and analyzing password characteristics such as length, character types (alphanumeric, uppercase), and more.

  14. Make a password manager with python: Making the basic mechanisms

    Every password manager must save the password a user gives and output it when the user needs it. We are gonna apply the same thing to our password manager. We will first start by creating a .txt file to store the passwords. Get the full code from here with some extra addition to get the code up and running. 1| Create a text file in python

  15. How to Build a Password Manager in Python

    Step 1: User Input and Password Addition. In below code add() function captures the username and password entered by the user in the Tkinter GUI. It checks if both fields are non-empty. If so, it appends the username and password to a file named "passwords.txt" and displays a success message using a Tkinter messagebox. Python3.

  16. Password Checker Assignment

    Once validated, the program will output the length of the password and determine if the password is weak or if the password is strong. The program will then output all the contents of the password log file to the screen. # whether the password meets the min and max parameters and keeps asking for input until satisfied.

  17. Generate password in Python

    On Python 3.6 + you should use the secrets module to generate cryptographically safe passwords. Adapted from the documentation: import secrets. import string. alphabet = string.ascii_letters + string.digits. password = ''.join(secrets.choice(alphabet) for i in range(20)) # for a 20-character password.

  18. Password Assighnment : r/learnpython

    Password Assighnment. The assignment is this: Many user-created passwords are simple and easy to guess. Write a program that takes a simple password and makes it stronger by replacing characters using the key below, and by appending "!" to the end of the input string. i becomes 1. a becomes @. m becomes M.

  19. Managing Passwords

    00:00 Password Management. At some point, your users might want to change their passwords. Instead of making them ask the admin to do it for them, you can add a password change form to your application. 00:14 Django needs two templates to make this work: the password_change_form to display the password change form and password_change_done to show a confirmation that the password was ...

  20. Python Program for Password with Certain Requirements

    1. I'm trying to write a Python program that prompts the user for a password. It must meet the following requirements: no less than 6 characters in length. no more than 12 characters in length. at least 1 numerical digit. at least 1 alphabetical character. no spaces.

  21. Python Password Saver Assignment

    The official dedicated python forum. Hello all, I have figured out the main parts of the assignment and am just trying to add the extra credit piece (add a 'delete password' function). I have done so and it works... but only if following these steps: Program loads > select option 4 > delete a password > select 2 > check password > select 3 > add a password > select 2 or 4 > repeat or end If I ...

  22. Issue on XMLRPC working with LoadBalancer

    Python Help. guiotti (Thiago) April 22, 2024, 6:17am 1. Hello all, I am working on a Python assignment for Distributed Computing Systems and running into some issues . I have 3 VM's running: AirlineServer1, AirlineServer2 and a LoadBalancer which calls the two airline services in a RoundRobin mode. The LoadBalancer has functions to get list ...