what is the difference between uuid4 and secrets token_bytes in python?

不羁岁月 提交于 2020-05-17 06:48:06

问题


Checked the cpython source code for both secrets and uuid4. Both seems to be using os.urandom.

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

#secrets.py
def token_bytes(nbytes=None):
    """Return a random byte string containing *nbytes* bytes.
    If *nbytes* is ``None`` or not supplied, a reasonable
    default is used.
    >>> token_bytes(16)  #doctest:+SKIP
    b'\\xebr\\x17D*t\\xae\\xd4\\xe3S\\xb6\\xe2\\xebP1\\x8b'
    """
    if nbytes is None:
        nbytes = DEFAULT_ENTROPY
    return _sysrand.randbytes(nbytes)

# This is code for randbytes in SystemRandom in random
 def randbytes(self, n):
        """Generate n random bytes."""
        # os.urandom(n) fails with ValueError for n < 0
        # and returns an empty bytes string for n == 0.
        return _urandom(n)

IETF warns not to use uuid's for security capabilities. Refer section 6 UUID. It says

  1. Security Considerations

    Do not assume that UUIDs are hard to guess; they should not be used as security capabilities (identifiers whose mere possession grants access), for example. A predictable random number source will exacerbate the situation.

If secrets really does use urandom same as uuid4, can we use uuid4 instead of secrets. What's the whole purpose of using secrets token_bytes instead of uuid4 itself?. As per IETF's standards is secrets module for api keys/tokens really not secure?


回答1:


You might be surprised to learn that random UUID's are not fully random. To be precise, there are 6 bits set to specific values (to indicate that it is a random UID). They are created to be unique (with a high amount of certainty). UUID's have a specific purpose, so you'll find all kinds of methods defined on them.

Furthermore, as the name suggests they are not meant to be secrets. That may also mean that possible protection measures that apply for secrets are not taken. For instance, strings are usually easy to find in memory, and UUID's are often used/communicated in a textual representation.

A token is something different. It is usually encrypted and kept secret. As such, it serves a different purpose. Of course, both UUID and tokens can consist of random bits and bytes. However, this is more about using the right tool for the job.

If you are creating a secret key rather than a token or UUID I'd prefer a API specific method for generating the keys. Otherwise it might be a good idea to use SystemRandom directly, because a key is neither a UUID nor a Token.



来源:https://stackoverflow.com/questions/61638695/what-is-the-difference-between-uuid4-and-secrets-token-bytes-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!