Skip to content

Instantly share code, notes, and snippets.

@gauravssnl
Created December 14, 2016 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gauravssnl/2f78f48b86915bacc57b4eba4cc50761 to your computer and use it in GitHub Desktop.
Save gauravssnl/2f78f48b86915bacc57b4eba4cc50761 to your computer and use it in GitHub Desktop.
🔑 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