105

I'd like to generate some alphanumeric passwords in Python. Some possible ways are:

import string
from random import sample, choice
chars = string.ascii_letters + string.digits
length = 8
''.join(sample(chars, length))                 # first way
''.join(choice(chars) for i in range(length))  # second way

But I don't the first way because only unique chars are selected and you can't generate passwords where length > len(chars) and I don't like the second way because we have an unused i variable. Are there any other good options?

5
  • There's nothing really wrong with the second option. Is it too slow? Do you need it to be faster? Are you running out of memory? Oct 4, 2010 at 11:25
  • Unused 'i' bother my mind and IDE. ;) Oct 4, 2010 at 11:28
  • 3
    use _ instead. Oct 4, 2010 at 11:29
  • 22
    Just quick FYI, the draft PEP 0506 -- Adding A Secrets Module To The Standard Library just came out and it specifically links to this question and an answer.
    – livibetter
    Sep 20, 2015 at 1:07
  • you should NOT use the random module, it's pseudo-randomness is fine for testing but INCREDIBLY weak for this purpose. Use the built-in secrets module instead Jul 4, 2021 at 1:16

12 Answers 12

227

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

For more information on recipes and best practices, see this section on recipes in the Python documentation. You can also consider adding string.punctuation.

3
  • if you decide to add string.punctuation, I would recommend to slice out `\' backslash which is the 23rd character as it can be confusing.
    – Ji Wei
    Jun 1 at 17:15
  • 1
    @JiWei Is it? As long as the character is available on all common keyboards and not easily confusable, it would seem that it's fine in a password. Anyway, removing one character from a sufficiently long password is not going to break security (I personally avoid I, 1, O, 0 in any passwords I have to type manually).
    – gerrit
    Jun 2 at 6:35
  • @gerrit: It could confuse an amateur like me. :D I used your code snippet to generate a password to password-protect an Excel file, and at the same time printed the password to stdout (I use Powershell and Notepad++). I realized that whenever there are 2 backslashes, somehow the password cannot be used to unprotect the Excel file. Turns out it should be read as one backslash because the first backslash is an escape character.
    – Ji Wei
    Jun 2 at 12:02
38

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.

6
  • 1
    You can eliminate the list in the last line via a generator expression: return "".join(chars[ord(c) % len(chars)] for c in urandom(length)) Mar 4, 2015 at 20:38
  • 1
    This is the best answer, but you should clearify the answer so that anyone finding this via Google understands why it's the best one. Sep 29, 2015 at 17:42
  • 1
    crypto-PRNG stands for "cryptograhically-secure Pseudorandom number generator". This answer is one of the best because it generates secure passwords. The default pseudorandom number generator in the random module is not secure. Sep 15, 2017 at 16:16
  • FWIW, after years of service, this code generated an obscene password. here is another post about the perils of alphanumeric password/id generation: softwareengineering.stackexchange.com/q/143405/32537
    – Ben Mosher
    Aug 30, 2018 at 12:01
  • TypeError: ord() expected string of length 1, but int found I am getting this error when running this code, don't know why people are saying this is good. Jan 12, 2021 at 18:34
31

Two recipes using the builtin secrets (python 3.6+)

1. secrets.token_urlsafe

This is much faster than the accepted answer. (see timings below)

import secrets
password = secrets.token_urlsafe(32)

Example output:

4EPn9Z7RE3l6jtCxEy7CPhia2EnYDEkE6N1O3-WnntU

The argument for token_urlsafe is number of bytes. On average, one byte is 1.3 characters (base64 encoded).

2. Enforce amount of digits/upper characters etc

This is slighly modified copy from the docs of secrets. With this you have more fine grained control on how to generated passwords have to look. Of course, this is not fast option if you need to generate a lot of passwords.

  • Forcing length to be 20 characters
  • Forcing at least 4 lower case character
  • Forcing at least 4 upper case characters
  • Forcing at least 4 digits
  • Special characters can be added to alphabet. In this example, there are just - and _ added.
import string
import secrets
alphabet = string.ascii_letters + string.digits + '-_'
while True:
    password = ''.join(secrets.choice(alphabet) for i in range(20))
    if (sum(c.islower() for c in password) >=4
            and sum(c.isupper() for c in password) >=4
            and sum(c.isdigit() for c in password) >=4):
        break

Example output:

HlxTm2fcFE54JA1I_Yp5

3. "I don't need the finer-grained control"

If considered speed, you can also drop the while-loop. In this case, it actually simplifies to gerrit's answer (but then you loose the finer-grained control):

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

Speed comparison

1. secrets.token_urlsafe

1.62 µs ± 96.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

2. Enforce amount of digits/upper characters etc

107 µs ± 11.9 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

3. "I don't need the finer-grained control"

77.2 µs ± 9.31 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Speed comparison setup: python 3.8.5 64-bit on Win10, 43 characters in each password (=32 bytes for token_urlsafe).

12

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.

2
  • 42
    You should use secure random number generators for password generation or your passwords may be easily compromised. The default python RNG is not a secure one. "Python uses the Mersenne Twister as the core generator. ... The Mersenne Twister ... is completely unsuitable for cryptographic purposes." -docs.python.org/library/random.html
    – Fasaxc
    Jul 16, 2012 at 17:56
  • 3
    I would like to backup Fasaxc on this. Please look at @livibetter's comment, use the secrets module from PEP0506. As livibetter stated, this article is referenced as a bad example. I know this is an old question that I am commenting on, but it's still one of the top search results. I'd recommend someone change the accepted answer to gerrit's. Aug 30, 2017 at 1:37
6

I think this'll do the trick. random.SystemRandom uses the same underlying crypto random function as os.urandom but it uses the familiar random interface. This function won't be subject to the weird 128 byte thing as in Ben's answer.

import random
import string

def gen_random_string(char_set, length):
    if not hasattr(gen_random_string, "rng"):
        gen_random_string.rng = random.SystemRandom() # Create a static variable
    return ''.join([ gen_random_string.rng.choice(char_set) for _ in xrange(length) ])

password_charset = string.ascii_letters + string.digits
gen_random_string(password_charset, 32)
3
  • Why would you want to set rng as an attribute? Jan 4, 2018 at 8:20
  • This is so you don't have to initialize random.SystemRandom() each time. Jan 4, 2018 at 17:12
  • One thing to note, this solution isn't any less secure (in the current version of python) than the accepted version that uses secrets.choice. secrets.choice is an alias of random.SystemRandom().choice, although I would recommend the secrets module for newer programs. (This post was created when python 2 was still a thing and the secrets module wasn't universally available). Nov 9, 2020 at 22:24
4

I suggest the following for those stuck on python <3.6:

import os, math, string, struct

def generate_password(pass_len):
    symbols = string.printable.strip()
    return ''.join([symbols[x * len(symbols) / 256] for x in struct.unpack('%dB' % (pass_len,), os.urandom(pass_len))])

This has the advantage over Ben Mosher's solution that the each symbol from symbols has an equal change of occurring whereas using modulus slightly favors the first symbols in the alpabet. The alphabet of symbols is also larger in this suggestion.

0
0

What I once did while using PyCryptodome module was this:

from Cryptodome.Random import get_random_bytes
from base64 import b64encode, b64decode

def get_password(lenght):
    return b64encode(get_random_bytes(lenght)).decode('utf-8')

password = get_password(21)

You decide how long you want the password to be at "get_random_bytes(lenght)".

1
  • lenght <> length May 10, 2022 at 1:03
0

You can use random and chr with symbols from 33 to 127:

from random import randint

symb_count = int(input('Enter count of symbols:'))
passwd = []
while len(passwd) < symb_count:
    passwd.append(chr(randint(33, 127)))
print(''.join(passwd))
-1

Yet another one-liner:

python -c "import random;print(''.join([random.choice(random.choice([['a','e','f','g','h','m','n','t','y'],['A','B','E','F','G','H','J','K','L','M','N','Q','R','T','X','Y'],['2','3','4','5','6','7','8','9'],['/','*','+','~','@','#','%','^','&','//']])) for i in range(16)]));"

Samples:

L+f##Q~H88NBe6Ny

&7@M7gt4J^///gH3e

5e2455hgn2h^//ffh

Advantage:

Change char list explicitly, exclude similar chars(etc. i 1 l I, 0 o O).(Just add/del in the list)

Change password length from 16 to whatever you want.

Disadvantage:

Readability.

PS. readable version:

python -c "import random;\
print(''.join([random.choice(random.choice(\
[\
 ['a','e','f','g','h','m','n','t','y'],\
 ['A','B','E','F','G','H','J','K','L','M','N','Q','R','T','X','Y'],\
 ['2','3','4','5','6','7','8','9'],\
 ['/','*','+','~','@','#','%','^','&','//']\
])) \
for i in range(16)]));"
1
  • 1
    This is insecure
    – user3064538
    Jun 7 at 15:06
-3

Here in the line 9 of above coding:

return (choice(options) for _ in xrange(length))

Actually the xrange is not defined, so the correct coding for this is:

return (choice(options) for _ in range(length))

Same in 76 line too.

2
-5

I wrote a script with my preferences, which mostly are concerned with avoiding mistakes when transcribing and remembering. (For example: remove somewhat ambiguous and no repeated characters.)

import optparse
import os
import random
import sys

DEFAULT_CHARS = "234679ADEFGHJKLMNPRTUWabdefghijkmnpqrstuwy"
DEFAULT_LEN = 18

def choices(options, length, choice=random.choice):
  return (choice(options) for _ in xrange(length))

def choices_non_repeated(options, length, choice=random.choice):
  assert len(options) > 1
  last = choice(options)
  count = 0
  while count < length:
    yield last
    count += 1

    while True:
      value = choice(options)
      if value != last:
        last = value
        break

def main(args):
  op = optparse.OptionParser(add_help_option=False)
  op.add_option("--help", action="help",
    help="show help message and exit")
  op.add_option("-b", "--bare", action="store_true", default=False,
    help="print passwords without trailing newline")
  op.add_option("-c", "--chars", metavar="SET", nargs=1, default=DEFAULT_CHARS,
    help="character set to use (default: %default)")
  op.add_option("--repeat", action="store_true", default=False,
    help="allow repetition")
  op.add_option("-l", "--len", dest="max", nargs=1, type="int", default=DEFAULT_LEN,
    help="max length (default: %default)")
  op.add_option("--min", nargs=1, type="int", default=None,
    help="min length (defaults to max)")
  op.add_option("-n", "--count", nargs=1, type="int", default=None,
    help="number of passwords to generate (default: %default)")
  op.add_option("--cols", type="int", default=None,
    help="number of columns to use")
  opts, args = op.parse_args(args)
  if args:
    op.error("unknown arguments")

  if os.isatty(sys.stdin.fileno()) and (
    opts.count is None and opts.cols is None
    and not opts.bare
  ):
    opts.cols = 80 // (opts.max + 1)
    opts.count = opts.cols * 25
  else:
    if opts.count is None:
      opts.count = 1
    if opts.cols is None:
      opts.cols = 1

  if opts.bare and opts.cols != 1:
    op.error("bare output requires --cols=1")

  if opts.min == None:
    opts.min = opts.max

  if any(x < 1 for x in [opts.cols, opts.count, opts.min, opts.max]):
    op.error("values must be >= 1")

  choices_func = choices_non_repeated
  if opts.repeat:
    choices_func = choices
  elif len(set(opts.chars)) < 2:
    op.error("must allow repetition or provide a longer character set")
    return "op.error shouldn't return"

  col = 0
  for _ in xrange(opts.count):
    length = random.randint(opts.min, opts.max)
    password = "".join(choices_func(opts.chars, length))
    sys.stdout.write(password)
    if not opts.bare:
      col += 1
      if col == opts.cols:
        sys.stdout.write("\n")
        col = 0
      else:
        sys.stdout.write(" ")


if __name__ == "__main__":
  sys.exit(main(sys.argv[1:]))
1
-5

You may want to use map instead of list comprehensions:

''.join(map(lambda x: random.choice(chars), range(length)))
1

Not the answer you're looking for? Browse other questions tagged or ask your own question.