Which one is more secure to use? uuid, binascii.he

2020-07-06 07:48发布

问题:

I want to create unique <client-key> and <client-secret> for the users who registers themselves for the service.

So, I was searching for the same and came up with these options:

  • uuid
  • binascii.hexlify(os.urandom(x))
  • random.SystemRandom()

It's a silly question but I want to know that which implementation is more secure to use (with proper explanation)? Why? And what are the advantages of using it over others?

Note:

AFAIK, random.SystemRandom() uses os.urandom(x). So comparison is mainly between uuid and random.SystemRandom().

Here's what I've tried so far:

1)

import random
temp = random.SystemRandom()
random_seq = ''.join(temp.choice(CHARACTER_SET) for x in range(x))
>>> 'wkdnP3EWxtEQWnB5XhqgNOr5RKL533vO7A40hsin'

2)

import uuid
str(uuid.uuid4())
>>> 'f26155d6-fa3d-4206-8e48-afe15f26048b'

I'm not sure about the solution. So, any help would be appreciated.


P.S. It'd be great if any solution is available for both Python 2.x and 3.x.

回答1:

It does not make any difference, all are of them use os.urandom both in Python 3 and 2. uuid4 just instantiates a new UUID object by passing in 16 random bytes to it:

def uuid4():
    """Generate a random UUID."""
    return UUID(bytes=os.urandom(16), version=4)

so from a standpoint of how the randomness is generated, these don't differ.