Generating UUID for API tokens in Python

Viewed 4300

I'm currently generating UUIDs in Python as follows:

import uuid
import secrets

uuid.UUID(bytes=secrets.token_bytes(16))

Is this safe to be used as an API token or access token?

1 Answers

Two reasons that your current approach is, arguably, a safe and sound one:

  • the probability of generating a duplicate id with 128 bits of entropy is effectively nil. (This is the standard UUID size, which you are using.)
  • secrets is designed specifically with the purpose of generating cryptographically strong random numbers; token_bytes() is really just a call to os.urandom(), which in turn returns random bytes from an OS-specific randomness source.*

A suggestion - uuid.uui4() does basically this same exact thing without the overhead of calling intermediary functions:

# https://github.com/python/cpython/blob/3.5/Lib/uuid.py
def uuid4():
    """Generate a random UUID."""
    return UUID(bytes=os.urandom(16), version=4)

One other suggestion regardless - you can use .hex of the resulting UUID object to get a nice non-hyphenated string.

>>> uuid.uuid4().hex
'22c482ef3cd84c26bb49c0287828428f'

*On Unix, that's /dev/urandom, which collects info from sources like device drivers. I.e. garbled info that is particular to the generating machine but sufficiently random and not identifiable of the host computer itself.

Related