开发者

Creating a salt in python

How would I create a random, 16-character base-62 salt in python? I need开发者_如何学Python it for a protocol and I'm not sure where to start. Thanks.


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 function

salt = 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 bcrypt
salt = bcrypt.gensalt()
# will be 29 chars you can then encode it however you want.


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

>>> "".join(chars)
'wE9mg9pu2KSmp5lh'

This should work.


Old question, new solution with secrets

import secrets

random_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.


These days there is an official mksalt method in the crypt module. It does not give you a simple 16 char long string but adds $digit$ in front required by most hashing functions anyway. If you are hashing passwords this is probably much safer to use.

import crypt
crypt.mksalt(crypt.METHOD_SHA512)

Generates outputs like the following:

$6$wpg9lx1sVFNFSCrP


in base64:

import random, base64, struct
rand_float = random.SystemRandom().random()
salt = base64.b64encode((struct.pack('!d', rand_float)))

this will be 12 chars


import random
import string

def get_salt(size=16, chars=None):
    if not chars:
        chars = ''.join(
            [string.ascii_uppercase, 
             string.ascii_lowercase, 
             string.digits]
        )
    return ''.join(random.choice(chars) for x in range(size))


I kind of like:

import md5, uuid
m = md5.md5()
m.update(uuid.uuid4())
print m.digest()[:16]

That will be very, very random.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜