Last active
April 2, 2019 04:58
-
-
Save cowbert/9ada90b777754ba6c4fce72cc535f76c to your computer and use it in GitHub Desktop.
RFC 4122 Version 1 UUID with CSPRNG-based node ID and clock sequence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
We patch uuid.uuid1() to take a random `node` (used to be the 48 bit MAC | |
address) according to RFC 4122 section 4.5 and CSPRNG 14 bit `clockseq` | |
See: https://docs.python.org/2/library/uuid.html#uuid.uuid1 | |
and https://svn.python.org/projects/python/branches/release27-maint/Lib/uuid.py | |
and https://tools.ietf.org/html/rfc4122#section-4.5 | |
The primary use-case for a UUID like this is to guarantee a virtually | |
collision-free monotonically-increasing value (based on the clock) such | |
that it can replace an object like an 'autoincrementing' integer primary | |
key field in a database that plays nicely with clustered indexing. | |
""" | |
from random import SystemRandom | |
from uuid import uuid1 as _uuid1 | |
def uuid1(node=None, clockseq=None): | |
if node is None: | |
node = SystemRandom().randrange(0, 1<<48) | 0x010000000000 | |
# according to RFC the LSB of the first octet should be set to 1 | |
if clockseq is None: | |
clockseq = SystemRandom().randrange(1<<14) | |
return _uuid1(node, clockseq) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment