Generate password in python Generate password in python python python

Generate password in python


You should use the secrets module to generate cryptographically safe passwords, which is available starting in Python 3.6. Adapted from the documentation:

import secretsimport stringalphabet = string.ascii_letters + string.digitspassword = ''.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.


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.


WARNING this answer should be ignored due to critical security issues!

Option #2 seems quite reasonable except you could add a couple of improvements:

''.join(choice(chars) for _ in range(length))          # in py2k use xrange

_ is a conventional "I don't care what is in there" variable. And you don't need list comprehension there, generator expression works just fine for str.join. It is also not clear what "slow" means, if it is the only correct way.