Skip to content

Instantly share code, notes, and snippets.

@MarkusH
Created July 10, 2019 22:06
Show Gist options
  • Save MarkusH/5c38ab6dd2ea3ddfc34465f98486bf0c to your computer and use it in GitHub Desktop.
Save MarkusH/5c38ab6dd2ea3ddfc34465f98486bf0c to your computer and use it in GitHub Desktop.
Base64 Encoding of UUIDs
>>> import base64, binascii, uuid
>>>
>>> def encode(uid: uuid.UUID) -> str:
... return base64.urlsafe_b64encode(uid.bytes).decode().rstrip("=")
...
>>> def decode(uid: str) -> uuid.UUID:
... return uuid.UUID(binascii.b2a_hex(base64.urlsafe_b64decode(uid_b64 + "==")).decode())
...
>>> uid = uuid.UUID("12546fd8-6dd9-4923-9c0a-f1fefadd3e2b")
>>> uid
UUID('12546fd8-6dd9-4923-9c0a-f1fefadd3e2b')
>>> uid_b64 = encode(uid)
>>> uid_b64
'ElRv2G3ZSSOcCvH--t0-Kw'
>>> decode(uid_b64)
UUID('12546fd8-6dd9-4923-9c0a-f1fefadd3e2b')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment