Creating a salt in python Creating a salt in python python python

Creating a salt in python


>>> import random>>> ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ">>> chars=[]>>> for i in range(16):    chars.append(random.choice(ALPHABET))>>> "".join(chars)'wE9mg9pu2KSmp5lh'

This should work.


You shouldn't use UUIDs, they are unique, not random: Is using a CreateUUID() function as salt a good idea?

Your salts should use a cryptographically secure random numbers, in python 2.4+, os.urandom is the source of these (if you have a good timing source).

# for some given b62encode functionsalt = b62encode(os.urandom(16))

you could also use a generator from bcrypt or other awesome crypto/hashing library that is well known and vetted by the people much more expert than I am.

import bcryptsalt = bcrypt.gensalt()# will be 29 chars you can then encode it however you want.


Old question, new solution with secrets

import secretsrandom_string = secrets.token_hex(8)

Will produce a cryptographically strong 16-character random string.

Use this over standard pseudo-random number generators as they are much less secure.

To quote from the secrets page:

The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.

In particularly, secrets should be used in preference to the default pseudo-random number generator in the random module, which is designed for modelling and simulation, not security or cryptography.