2 Interface to the OpenSSL pseudo-random generator
5 from ctypes import create_string_buffer, c_char_p, c_int, c_double
6 from ctypescrypto import libcrypto
7 from ctypescrypto.exception import LibCryptoError
9 __all__ = ['RandError', 'bytes', 'pseudo_bytes', 'seed', 'status']
11 class RandError(LibCryptoError):
12 """ Exception raised when openssl function return error """
15 def bytes(num, check_result=False):
17 Returns num bytes of cryptographically strong pseudo-random
18 bytes. If checkc_result is True, raises error if PRNG is not
23 raise ValueError("'num' should be > 0")
24 buf = create_string_buffer(num)
25 result = libcrypto.RAND_bytes(buf, num)
26 if check_result and result == 0:
27 raise RandError("Random Number Generator not seeded sufficiently")
30 def pseudo_bytes(num):
32 Returns num bytes of pseudo random data. Pseudo- random byte
33 sequences generated by pseudo_bytes() will be unique if
34 they are of sufficient length, but are not necessarily
35 unpredictable. They can be used for non-cryptographic purposes
36 and for certain purposes in cryptographic protocols, but usually
37 not for key generation etc.
40 raise ValueError("'num' should be > 0")
41 buf = create_string_buffer(num)
42 libcrypto.RAND_pseudo_bytes(buf, num)
45 def seed(data, entropy=None):
47 Seeds random generator with data.
48 If entropy is not None, it should be floating point(double)
49 value estimating amount of entropy in the data (in bytes).
51 if not isinstance(data, str):
52 raise TypeError("A string is expected")
56 libcrypto.RAND_seed(ptr, size)
58 libcrypto.RAND_add(ptr, size, entropy)
62 Returns 1 if random generator is sufficiently seeded and 0
66 return libcrypto.RAND_status()
68 libcrypto.RAND_add.argtypes = (c_char_p, c_int, c_double)
69 libcrypto.RAND_seed.argtypes = (c_char_p, c_int)
70 libcrypto.RAND_pseudo_bytes.argtypes = (c_char_p, c_int)
71 libcrypto.RAND_bytes.argtypes = (c_char_p, c_int)