Skip to content

Instantly share code, notes, and snippets.

@ebsaral
Last active August 29, 2015 13:56
Show Gist options
  • Save ebsaral/9246709 to your computer and use it in GitHub Desktop.
Save ebsaral/9246709 to your computer and use it in GitHub Desktop.
Generating random string encoded in base32 with Python
import base64
import random
def generate_16char_base32(pre):
"""
Encode a string of 16 length in base32
with a given string - maximum length of 10 chars -
Note: 10 char = 16 char string in base32
Warning: Decoding is not a part of this example
since it adds a random integer to the end of string
"""
prefix = unicode(pre)
prefix_len = len(prefix)
if prefix_len > 10:
return None
remaining = 10 - prefix_len
random_int_str = ''
if remaining != 0:
random_from = 10 ** (remaining-1)
random_to = (10 ** remaining) - 1
random_int = random.randint(random_from, random_to)
random_int_str = unicode(random_int)
str_to_encode = prefix + random_int_str
encoded_str = base64.b32encode(str_to_encode)
return encoded_str
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment