Skip to content

Instantly share code, notes, and snippets.

@gorakhargosh
Created July 4, 2011 19:16
Show Gist options
  • Save gorakhargosh/1063809 to your computer and use it in GitHub Desktop.
Save gorakhargosh/1063809 to your computer and use it in GitHub Desktop.
def generate_random_string(bit_strength=64, decimal=False):
"""
Generates a random ASCII-encoded unsigned integral random number in decimal
or hexadecimal representation.
:param bit_strength:
Bit strength.
:returns:
A string representation of a randomly-generated ASCII-encoded
hexadecimal/decimal-representation unsigned integral number
based on the bit strength specified.
"""
if bit_strength % 8 or bit_strength <= 0:
raise ValueError("This function expects a bit strength: got `%r`." % (bit_strength, ))
length = bit_strength / 8
value = binascii.b2a_hex(os.urandom(length))
if decimal:
value = bytes(int(value, 16))
return value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment