Created
October 11, 2015 14:35
-
-
Save rusek/c9d07140f61851693dfd to your computer and use it in GitHub Desktop.
Random bytes generation in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random as random_mod | |
try: | |
import ctypes | |
_long_as_byte_array = ctypes.pythonapi._PyLong_AsByteArray | |
_long_as_byte_array.argtypes = [ | |
ctypes.py_object, | |
ctypes.POINTER(ctypes.c_char), | |
ctypes.c_size_t, | |
ctypes.c_int, | |
ctypes.c_int | |
] | |
def _long_to_bytes(num, size): | |
buf = ctypes.create_string_buffer(size) | |
_long_as_byte_array(num, buf, size, 0, 0) | |
return buf.raw | |
except ImportError: | |
import binascii | |
def _long_to_bytes(num, size): | |
return binascii.unhexlify(hex(num)[2: -1].zfill(2 * size)) | |
def randbytes(size, random=None): | |
if size < 1: | |
return '' | |
if random is None: | |
random = random_mod | |
return _long_to_bytes(random.getrandbits(8 * size), size) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment