Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate password in python

I'dl like to generate some alphanumeric passwords in python. Some possible ways are:

import string from random import sample, choice chars = string.letters + string.digits length = 8 ''.join(sample(chars,length)) # way 1 ''.join([choice(chars) for i in range(length)]) # way 2 

But I don't like both because:

  • way 1 only unique chars selected and you can't generate passwords where length > len(chars)
  • way 2 we have i variable unused and I can't find good way how to avoid that

So, any other good options?

P.S. So here we are with some testing with timeit for 100000 iterations:

''.join(sample(chars,length)) # way 1; 2.5 seconds ''.join([choice(chars) for i in range(length)]) # way 2; 1.8 seconds (optimizer helps?) ''.join(choice(chars) for _ in range(length)) # way 3; 1.8 seconds ''.join(choice(chars) for _ in xrange(length)) # way 4; 1.73 seconds ''.join(map(lambda x: random.choice(chars), range(length))) # way 5; 2.27 seconds 

So, the winner is ''.join(choice(chars) for _ in xrange(length)).

like image 379
HardQuestions Avatar asked Oct 04 '10 11:10

HardQuestions


People also ask

What is random password generator in Python?

Password generator is a Random Password generating program which generates a password mix of upper and lowercase letters, as well as numbers and symbols strong enough to provides great security. In this Blog article, we will learn how to Create a Random Password Generator. We will see the implementation in Python.


2 Answers

You should use the secrets module to generate cryptographically safe passwords, which is available starting in Python 3.6. 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 

For more information on recipes and best practices, see this section on recipes in the Python documentation. You can also consider adding string.punctuation or even just using string.printable for a wider set of characters.

like image 89
gerrit Avatar answered Sep 17 '22 12:09

gerrit


For the crypto-PRNG folks out there:

def generate_temp_password(length):     if not isinstance(length, int) or length < 8:         raise ValueError("temp password must have positive length")      chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"     from os import urandom      # original Python 2 (urandom returns str)     # return "".join(chars[ord(c) % len(chars)] for c in urandom(length))      # Python 3 (urandom returns bytes)     return "".join(chars[c % len(chars)] for c in urandom(length)) 

Note that for an even distribution, the chars string length ought to be an integral divisor of 128; otherwise, you'll need a different way to choose uniformly from the space.

like image 31
Ben Mosher Avatar answered Sep 21 '22 12:09

Ben Mosher