Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
🔑 Generates and validates random url-safe user-readable strings.
from os import urandom
from base64 import b64encode
from string import ascii_letters, digits
def randkey(size=6, altchars=b'+.', ambiguous=b'IlO9GUS'):
key = ''
while len(key) < size:
chunk = b64encode(urandom(size*2), altchars)
key += str(bytes([c for c in chunk if c not in ambiguous]), encoding='utf-8')
return key[:size]
def verikey(key, size=6, altchars='+.', validchars=ascii_letters+digits):
alphabet = validchars + altchars
return len(key) == size and len(list(filter(lambda c: c not in alphabet, key))) == 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment