Python function to generate secure random password



In this short tutorial, we will explain how to write a function to generate a secure random password generator. This python random password generated will output alphanumeric strings (letters and numbers), however, chars can be changed by the parameter.

The code

The python is very simple and it's only two lines. We use SystemRandom since it's more secure and provides more entropy. The first line initializes the random generator, then we use choice to select size times from the chars list. We then use the join method of string to join the generated list as a string.

#!/usr/bin/env python

import string
from random import SystemRandom

def password_generator(size=8, chars=string.ascii_letters + string.digits):
    Returns a string of random characters using SystemRandom class which uses the system function os.urandom()
    os.urandom() should be used for cryptographically secure pseudo-random number generator

    random_gen = SystemRandom()
    return ''.join(random_gen.choice(chars) for i in range(size))