Skip to content

Instantly share code, notes, and snippets.

@darius
Last active August 29, 2015 14:08
Show Gist options
  • Save darius/c9cd62e2d3327a5b4e98 to your computer and use it in GitHub Desktop.
Save darius/c9cd62e2d3327a5b4e98 to your computer and use it in GitHub Desktop.
"""
Generate a random token.
"""
# After reading Zooko's, I was like oops, I'm an idiot.
# I should probably use his, but anyway here's a fix:
# correct cryptogen.sample() to cryptogen.choice().
import math
from random import SystemRandom
cryptogen = SystemRandom()
def gen_token(nbits, alphabet, sep):
assert len(set(alphabet)) == len(alphabet)
length = int(math.ceil(nbits * math.log(2, len(alphabet))))
return sep.join(cryptogen.choice(alphabet) for _ in range(length))
## nbits = 83 # 95
## alphabet = open('/home/darius/bin/words2').read().splitlines()
## print gen_token(nbits, alphabet, '.')
#. unclear.chew.latex.bush.cavern.term.bangs
## import string
## alphabet = r'0123456789-/\,.=' + string.ascii_lowercase # + r"[]'"
## nbits = 80
## print gen_token(nbits, alphabet, '')
#. rsz8pvwi.qxmak\
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment