Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.