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