]> www.wagner.pp.ru Git - oss/ctypescrypto.git/blob - ctypescrypto/rand.py
d9e966d67c67f6635751ce54338990ae788915eb
[oss/ctypescrypto.git] / ctypescrypto / rand.py
1 """
2     Interface to the OpenSSL pseudo-random generator
3 """
4
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
8
9 __all__ = ['RandError', 'bytes', 'pseudo_bytes', 'seed', 'status']
10
11 class RandError(LibCryptoError):
12     """ Exception raised when openssl function return error """
13     pass
14
15 def bytes(num, check_result=False):
16     """
17     Returns num bytes of cryptographically strong pseudo-random
18     bytes. If checkc_result is True, raises error if PRNG is not
19     seeded enough
20     """
21
22     if num <= 0:
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")
28     return buf.raw[:num]
29
30 def pseudo_bytes(num):
31     """
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.
38     """
39     if num <= 0:
40         raise ValueError("'num' should be > 0")
41     buf = create_string_buffer(num)
42     libcrypto.RAND_pseudo_bytes(buf, num)
43     return buf.raw[:num]
44
45 def seed(data, entropy=None):
46     """
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).
50     """
51     if not isinstance(data, str):
52         raise TypeError("A string is expected")
53     ptr = c_char_p(data)
54     size = len(data)
55     if entropy is None:
56         libcrypto.RAND_seed(ptr, size)
57     else:
58         libcrypto.RAND_add(ptr, size, entropy)
59
60 def status():
61     """
62     Returns 1 if random generator is sufficiently seeded and 0
63     otherwise
64     """
65
66     return libcrypto.RAND_status()
67
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)