Password generator python code

Create a Random Password Generator using Python

In this article, we will see how to create a random password generator using Python.

Passwords are a means by which a user proves that they are authorized to use a device. It is important that passwords must be long and complex. It should contain at least more than ten characters with a combination of characters such as percent (%), commas(,), and parentheses, as well as lower-case and upper-case alphabets and numbers. Here we will create a random password using Python code.

Example of a weak password : password123

Example of a strong password : &gj5hj&*178a1

Modules needed

string – For accessing string constants. The ones we would need are –

  • string.ascii_letters: ASCII is a system that is used to represent characters digitally, every ASCII character has its own unique code. string.ascii_letters is a string constant which contains all the letters in ASCII ranging from A to Z and a to z. Its value is non-locale dependent and it is just a concatenation of ascii_uppercase and ascii_lowercase. Thus it provides us the whole letter set as a string that can be used as desired.
  • string.digits: This is a pre-initialized string that contains all the digits in the Arabic numeral system i.e. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. It should be kept in mind that even though these are digits, the type is still a string constant, and all digits are concatenated like this – “0123456789”. If we want to access specific numbers then we can do so using slicing.
  • string.punctuation: Apart from letters and digits, python also provides us all the special characters in a pre-initialized string constant. These include various kinds of braces, logical operators, comparison operators, arithmetical operators as well as punctuation marks like commas, inverted commas, periods, exclamations marks, and question marks. The whole string is – !”#$%&'()*+, -./:;?@[\]^_`<|>~

random – The python random module helps a user to generate pseudo-random numbers. Inside the module, there are various functions that just depend on the function “random()”. This function generates a random float uniformly in the semi-open range [0.0, 1.0) i.e. it generates a decimal number greater than or equal to 0 and strictly less than one. Other functions use this number in their own ways. These functions can be used for bytes, integers, and sequences. for our task, we are interested in sequences. There are functions random. choices that take in a sequence as its argument and return a random element from that sequence.

Code Implementation:

First, take the length of the password as input. Then we can display a prompt about the possible list of characters that a user wants to include in the password –

  • For including letters in the character set append string.ascii_letters in the character list.
  • For including letters in the character set append string.digits in the character list.
  • For including letters in character set append string.punctuation in the character list.

Run a for loop till the length of the password and in each iteration choose a random character using random.choice() from characterList. Finally, print the password.

Источник

How to Create a Random Password Generator in Python

Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

Learn to code a password generator in Python—to generate secure passwords—using the Python secrets module.

Python is a versatile programming language that you can use across applications in automation, web development, data analysis, and more.

You can use Python to automate real-world tasks such as monitoring websites, sending emails, and generating passwords. In this tutorial, you’ll learn how to create a secure and random password generator in Python.

3 Reasons Why You Should Code a Password Generator in Python

Random-Password-Generator

Have you ever felt tired of generating secure passwords and keeping track of them? Here’s why you should consider coding a password generator in Python.

1. Automate the Password Generation Process

On a typical day in your life, you’ll visit numerous websites – from e-commerce websites to learning and coding platforms. Most of the websites require you to log in with credentials. This is a repetitive task that you can automate using a Python script.

2. Generate Secure Passwords

Coming up with strong passwords that meet security constraints can be challenging; trivial passwords that are not strong are susceptible to security attacks.

python-password-generator

You can use Python to programmatically generate secure passwords. This lets you run the script to generate passwords as needed—without worrying about the password being secure.

3. Add a Practical Project to Your Portfolio

If you’re a beginner Python programmer, you should build projects to hone your skills and showcase your programming expertise through a portfolio.

In addition to a simple Python script, you can customize it further, and publish it as a PyPI package. You can also add a graphical user interface using libraries such as Tkinter, and much more!

This way, you can code your own password generator—to securely generate and manage your passwords—across the various sites.

The Random Module in Python: Is It Secure Enough?

Python random module also provides functions that let you sample from an alphabet and construct seemingly random sequences. The random module generates pseudo-random sequences. Let us parse what pseudo-randomness means.

The term pseudo-random signifies that even though the sequence may appear random, it actually is deterministic.

Therefore, if you set a random seed, then the random module will yield the same sequence on your machine, and for anyone who runs the same script with the same seed.

This is why you should not use random for applications where security is important, such as passwords.

So when can you use the random module?

For all applications that are not sensitive, you can use the random module. For example, there are three sets of question papers, A, B, and C in a class of 40 students. You would like to assign a particular set to each student at random.

2

In this case, you can use random.choice() inside a list comprehension expression, as shown below:

import random papers = ['A','B','C'] q_list = [random.choice(papers) for i in range(40)] print(q_list)
Sample output: ['A', 'A', 'B', 'B', 'B', 'B', 'B', 'C', 'B', 'A', 'C', 'C', 'B', 'C', 'A', 'B', 'A', 'A', 'C', 'C', 'A', 'A', 'A', 'C', 'A', 'C', 'A', 'C', 'B', 'B', 'B', 'B', 'A', 'A', 'B', 'B', 'A', 'A', 'B', 'B']

📑 Key takeaway: For statistical simulations, you can use the random module; for sensitive applications, use the secrets module.

Python Secrets Module: Your Key to Secure Passwords

The Python Enhancement Proposal, PEP 506, advises developers to use the secrets module whenever a sequence should be cryptographically secure, such as passwords and security tokens.

python-secrets-password-generator

The secrets the module has several built-in functions that let you do the following:

  • Generate sequences of random numbers that are secure for cryptographic applications.
  • Use functions like choice() , randbits() , and randbelow() to generate secure random numbers.
  • Generate tokens for a password reset, temporary URLs, and more.

How to Code a Password Generator in Python [in 4 Steps]

Prerequisites: You need to have Python 3.6 or a later version installed to code along with this tutorial. You can also run the example code in Geekflare’s Online Python Code Editor.

Step 1: Import necessary modules

As a first step, let’s import the secrets module. This module is built into the Python standard library, so you can import it as follows:

Let’s also import Python’s built-in string module:

Step 2: Define the alphabet

The next step is to define the alphabet. Alphabet denotes the set of all characters that we’ll consider for password generation. Here, we want it to contain the following: lowercase and uppercase letters and special characters.

alphabet

The string module provides string constants that we can use to define the alphabet. We’ll use the following string constants:

  • The ascii_letters is a concatenation of letters lowercase and uppercase letters.
  • The digits constant is the string containing the numbers 0 to 9: ‘0123456789’ .
  • The punctuation constant is the string of all special characters.
letters = string.ascii_letters digits = string.digits special_chars = string.punctuation

Finally, let’s concatenate the above string constants to get the alphabet.

alphabet = letters + digits + special_chars

Step 3: Fix the length of the password; Generate a password

Let’s store the length of the password in the variable, pwd_length . In this example, the password string is of length 12.

▶️ Now, run the following code cell to generate a password:

pwd = '' for i in range(pwd_length): pwd += ''.join(secrets.choice(alphabet)) print(pwd)

The above code does the following:

  • The password string pwd is an empty string initially.
  • We know that secrets.choice(alphabet) returns one character, sampled at random from the alphabet .
  • We use the join() method to add this character to the pwd string. Because we do not want any whitespace between the characters, we specify the separator to be » .
  • To repeat the above steps to generate a password, we use a loop that runs for as many iterations as the length of the password.

Step 4: Customize Your Passwords Based on Constraints

You can customize the password generation by checking if it meets certain constraints.

For example, let’s check if the generated password string of length 12 satisfies the following constraints:

  • The string pwd should contain at least one special character.
  • It should contain at least two digits.

In the code snippet below, you may modify the condition that the if statement checks for according to the constraints you define.

while True: pwd = '' for i in range(pwd_length): pwd += ''.join(secrets.choice(alphabet)) if (any(char in special_chars for char in pwd) and sum(char in digits for char in pwd)>=2): break print(pwd)

In the code cell above, we use an infinite while loop that runs so long as the password string pwd does not meet the constraints. When the generated password, pwd satisfies the constraints, we break out of the infinite loop.

Here’s the complete code for the Python password generator:

# necessary imports import secrets import string # define the alphabet letters = string.ascii_letters digits = string.digits special_chars = string.punctuation alphabet = letters + digits + special_chars # fix password length pwd_length = 12 # generate a password string pwd = '' for i in range(pwd_length): pwd += ''.join(secrets.choice(alphabet)) print(pwd) # generate password meeting constraints while True: pwd = '' for i in range(pwd_length): pwd += ''.join(secrets.choice(alphabet)) if (any(char in special_chars for char in pwd) and sum(char in digits for char in pwd)>=2): break print(pwd)

Conclusion

Congratulations on finishing this tutorial! 🎉You’ve now learned how to code a password generator in Python.

  • To generate cryptographically secure passwords, you should use the secrets module and not the random module.
  • A strong password should be sufficiently long and should be random in that it cannot be easily predicted or generated. It should be a combination of uppercase and lowercase letters, digits, and special characters.
  • Python ships with a built-in string module that provides all letters, digits, and special characters in the constants ascii_letters, digits, and punctuation, respectively. Use the syntax: string.constant to access these string constants.
  • You can use the above constants to define an alphabet (a set of all characters) for password generation.
  • Once you’ve defined an alphabet, you can use secrets.choice() to sample a random character from it. To repeat this for the length of the password, you can use a for loop.

Источник

Читайте также:  Функция корень из числа html
Оцените статью