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):
14 def bytes( num, check_result=False):
16 Returns num bytes of cryptographically strong pseudo-random
17 bytes. If checkc_result is True, raises error if PRNG is not
22 raise ValueError("'num' should be > 0")
23 buffer = create_string_buffer(num)
24 result = libcrypto.RAND_bytes(buffer, num)
25 if check_result and result == 0:
26 raise RandError("Random Number Generator not seeded sufficiently")
27 return buffer.raw[:num]
29 def pseudo_bytes(num):
31 Returns num bytes of pseudo random data. Pseudo- random byte
32 sequences generated by pseudo_bytes() will be unique if
33 they are of sufficient length, but are not necessarily
34 unpredictable. They can be used for non-cryptographic purposes
35 and for certain purposes in cryptographic protocols, but usually
36 not for key generation etc.
39 raise ValueError("'num' should be > 0")
40 buffer = create_string_buffer(num)
41 libcrypto.RAND_pseudo_bytes(buffer, num)
42 return buffer.raw[:num]
44 def seed(data, entropy=None):
46 Seeds random generator with data.
47 If entropy is not None, it should be floating point(double)
48 value estimating amount of entropy in the data (in bytes).
50 if type(data) != type(""):
51 raise TypeError("A string is expected")
55 libcrypto.RAND_seed(ptr, size)
57 libcrypto.RAND_add(ptr, size, entropy)
61 Returns 1 if random generator is sufficiently seeded and 0
65 return libcrypto.RAND_status()
67 libcrypto.RAND_add.argtypes=(c_char_p,c_int,c_double)
68 libcrypto.RAND_seed.argtypes=(c_char_p,c_int)
69 libcrypto.RAND_pseudo_bytes.argtypes=(c_char_p,c_int)
70 libcrypto.RAND_bytes.argtypes=(c_char_p,c_int)