How to Create a Random String

• 2 min read

Random strings are used everywhere in computing -- mostly as keys for cryptographic signing sensitive data. So how does one go about creating one?

My first thinking was to use Python code and its random library. I came up with this

import string
import random

def gen_random_string(length=32, charset=string.printable):
    '''
    A function to generate a string of specified length composed of random
    characters. The characters with which the string is composed can be
    customized thru the second parameter.

    Parameters:
        length - int, length of the string. Defaults to 32.
        charset - array of characters from which the letters to compose
                 the string are randomly chosen. Defaults to string.printable

    Returns:
        string

    Raises:
       None
    '''
    num_chars = len(charset)
    random_string = ''
    random.seed()
    for i in range(0, length):
        random_string += charset[random.randint(0, num_chars-1)]
    return random_string

It does produce a random string of the required length.

However, I found out a better way:

$ openssl rand -base64 48

This generates a random string of length 48 characters.

Not only is the latter more succinct (though it requires OpenSSL to be installed), I would think the generated string it's more random than one based in python random library.