]> www.wagner.pp.ru Git - oss/ctypescrypto.git/blob - ctypescrypto/rand.py
Fixed syntax of exceptions to python3 compatibility
[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 class RandError(LibCryptoError):
10         pass
11
12 def bytes( num, check_result=False):
13         """
14                 Returns num bytes of cryptographically strong pseudo-random
15                 bytes. If checkc_result is True, raises error if PRNG is not
16                 seeded enough
17         """
18
19         if num <= 0 :
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]
26
27 def pseudo_bytes(num):
28         """
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.
35         """
36         if num <= 0 :
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]
41
42 def seed(data, entropy=None):
43         """
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).
47         """
48         if type(data) != type(""):
49                 raise TypeError("A string is expected")
50         ptr = c_char_p(data)
51         size = len(data)
52         if entropy is None:
53                 libcrypto.RAND_seed(ptr, size)
54         else :
55                 libcrypto.RAND_add(ptr, size, entropy)
56
57 def status():
58         """
59                 Returns 1 if random generator is sufficiently seeded and 0
60                 otherwise
61         """
62
63         return libcrypto.RAND_status()
64         
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)