Skip to content

Instantly share code, notes, and snippets.

@benhoyt
Created July 28, 2016 15:38
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 benhoyt/adb0ceee5f9a056c6625131da1a0c112 to your computer and use it in GitHub Desktop.
Save benhoyt/adb0ceee5f9a056c6625131da1a0c112 to your computer and use it in GitHub Desktop.
Python function to generate a random string (key) of length chars
"""Function to generate a random string (key) of length chars."""
import binascii
import os
def generate_key(length=40, get_bytes=os.urandom):
"""Return a randomly-generated key of length chars.
>>> len(generate_key())
40
>>> len(generate_key(5))
5
>>> keys = set(generate_key() for _ in range(100))
>>> len(keys)
100
>>> all(len(k) == 40 for k in keys)
True
>>> def get_bytes(n):
... print('Getting {0} bytes'.format(n))
... return b'ABC123DEF456GHI789J0'[:n]
>>> generate_key(get_bytes=get_bytes)
Getting 20 bytes
'4142433132334445463435364748493738394a30'
>>> generate_key(10, get_bytes=get_bytes)
Getting 5 bytes
'4142433132'
>>> generate_key(5, get_bytes=get_bytes)
Getting 3 bytes
'41424'
"""
raw_bytes = get_bytes((length + 1) // 2)
hex_bytes = binascii.b2a_hex(raw_bytes)[:length]
if not isinstance(hex_bytes, str):
# On Python 3, b2a_hex returns bytes, convert to str
hex_bytes = hex_bytes.decode('ascii')
return hex_bytes
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment