]> www.wagner.pp.ru Git - oss/ctypescrypto.git/blob - ctypescrypto/rand.py
Converted tabs to spaces to make pylint happy
[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     pass
13
14 def bytes( num, check_result=False):
15     """
16         Returns num bytes of cryptographically strong pseudo-random
17         bytes. If checkc_result is True, raises error if PRNG is not
18         seeded enough
19     """
20
21     if num <= 0 :
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]
28
29 def pseudo_bytes(num):
30     """
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.
37     """
38     if num <= 0 :
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]
43
44 def seed(data, entropy=None):
45     """
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).
49     """
50     if not isinstance(data,str):
51         raise TypeError("A string is expected")
52     ptr = c_char_p(data)
53     size = len(data)
54     if entropy is None:
55         libcrypto.RAND_seed(ptr, size)
56     else :
57         libcrypto.RAND_add(ptr, size, entropy)
58
59 def status():
60     """
61         Returns 1 if random generator is sufficiently seeded and 0
62         otherwise
63     """
64
65     return libcrypto.RAND_status()
66     
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)