Генератор паролей python random

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.

Источник

secrets — Generate secure random numbers for managing secrets¶

The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.

In particular, secrets should be used in preference to the default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography.

Random numbers¶

The secrets module provides access to the most secure source of randomness that your operating system provides.

class secrets. SystemRandom ¶

A class for generating random numbers using the highest-quality sources provided by the operating system. See random.SystemRandom for additional details.

Return a randomly chosen element from a non-empty sequence.

Return a random int in the range [0, n).

Return an int with k random bits.

Generating tokens¶

The secrets module provides functions for generating secure tokens, suitable for applications such as password resets, hard-to-guess URLs, and similar.

secrets. token_bytes ( [ nbytes=None ] ) ¶

Return a random byte string containing nbytes number of bytes. If nbytes is None or not supplied, a reasonable default is used.

>>> token_bytes(16) b'\xebr\x17D*t\xae\xd4\xe3S\xb6\xe2\xebP1\x8b' 

Return a random text string, in hexadecimal. The string has nbytes random bytes, each byte converted to two hex digits. If nbytes is None or not supplied, a reasonable default is used.

>>> token_hex(16) 'f9bf78b9a18ce6d46a0cd2b0b86df9da' 

Return a random URL-safe text string, containing nbytes random bytes. The text is Base64 encoded, so on average each byte results in approximately 1.3 characters. If nbytes is None or not supplied, a reasonable default is used.

>>> token_urlsafe(16) 'Drmhze6EPcv0fN_81Bj-nA' 

How many bytes should tokens use?¶

To be secure against brute-force attacks, tokens need to have sufficient randomness. Unfortunately, what is considered sufficient will necessarily increase as computers get more powerful and able to make more guesses in a shorter period. As of 2015, it is believed that 32 bytes (256 bits) of randomness is sufficient for the typical use-case expected for the secrets module.

For those who want to manage their own token length, you can explicitly specify how much randomness is used for tokens by giving an int argument to the various token_* functions. That argument is taken as the number of bytes of randomness to use.

Otherwise, if no argument is provided, or if the argument is None , the token_* functions will use a reasonable default instead.

That default is subject to change at any time, including during maintenance releases.

Other functions¶

Return True if strings or bytes-like objects a and b are equal, otherwise False , using a “constant-time compare” to reduce the risk of timing attacks. See hmac.compare_digest() for additional details.

Recipes and best practices¶

This section shows recipes and best practices for using secrets to manage a basic level of security.

Generate an eight-character alphanumeric password:

import string import secrets alphabet = string.ascii_letters + string.digits password = ''.join(secrets.choice(alphabet) for i in range(8)) 

Applications should not store passwords in a recoverable format, whether plain text or encrypted. They should be salted and hashed using a cryptographically strong one-way (irreversible) hash function.

Generate a ten-character alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits:

import string import secrets alphabet = string.ascii_letters + string.digits while True: password = ''.join(secrets.choice(alphabet) for i in range(10)) if (any(c.islower() for c in password) and any(c.isupper() for c in password) and sum(c.isdigit() for c in password) >= 3): break 
import secrets # On standard Linux systems, use a convenient dictionary file. # Other platforms may need to provide their own word-list. with open('/usr/share/dict/words') as f: words = [word.strip() for word in f] password = ' '.join(secrets.choice(words) for i in range(4)) 

Generate a hard-to-guess temporary URL containing a security token suitable for password recovery applications:

import secrets url = 'https://example.com/reset=' + secrets.token_urlsafe() 

Источник

Читайте также:  Best one page html templates
Оцените статью