Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/Crypto/Random/Fortuna/FortunaGenerator.py: 92%

60 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-07 07:03 +0000

1# -*- coding: ascii -*- 

2# 

3# FortunaGenerator.py : Fortuna's internal PRNG 

4# 

5# Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net> 

6# 

7# =================================================================== 

8# The contents of this file are dedicated to the public domain. To 

9# the extent that dedication to the public domain is not available, 

10# everyone is granted a worldwide, perpetual, royalty-free, 

11# non-exclusive license to exercise all rights associated with the 

12# contents of this file for any purpose whatsoever. 

13# No rights are reserved. 

14# 

15# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 

16# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 

17# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 

18# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 

19# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 

20# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 

21# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 

22# SOFTWARE. 

23# =================================================================== 

24 

25__revision__ = "$Id$" 

26 

27import sys 

28if sys.version_info[0] == 2 and sys.version_info[1] == 1: 

29 from Crypto.Util.py21compat import * 

30from Crypto.Util.py3compat import * 

31 

32import struct 

33 

34from Crypto.Util.number import ceil_shift, exact_log2, exact_div 

35from Crypto.Util import Counter 

36from Crypto.Cipher import AES 

37 

38from . import SHAd256 

39 

40class AESGenerator(object): 

41 """The Fortuna "generator" 

42 

43 This is used internally by the Fortuna PRNG to generate arbitrary amounts 

44 of pseudorandom data from a smaller amount of seed data. 

45 

46 The output is generated by running AES-256 in counter mode and re-keying 

47 after every mebibyte (2**16 blocks) of output. 

48 """ 

49 

50 block_size = AES.block_size # output block size in octets (128 bits) 

51 key_size = 32 # key size in octets (256 bits) 

52 

53 # Because of the birthday paradox, we expect to find approximately one 

54 # collision for every 2**64 blocks of output from a real random source. 

55 # However, this code generates pseudorandom data by running AES in 

56 # counter mode, so there will be no collisions until the counter 

57 # (theoretically) wraps around at 2**128 blocks. Thus, in order to prevent 

58 # Fortuna's pseudorandom output from deviating perceptibly from a true 

59 # random source, Ferguson and Schneier specify a limit of 2**16 blocks 

60 # without rekeying. 

61 max_blocks_per_request = 2**16 # Allow no more than this number of blocks per _pseudo_random_data request 

62 

63 _four_kiblocks_of_zeros = b("\0") * block_size * 4096 

64 

65 def __init__(self): 

66 self.counter = Counter.new(nbits=self.block_size*8, initial_value=0, little_endian=True) 

67 self.key = None 

68 

69 # Set some helper constants 

70 self.block_size_shift = exact_log2(self.block_size) 

71 assert (1 << self.block_size_shift) == self.block_size 

72 

73 self.blocks_per_key = exact_div(self.key_size, self.block_size) 

74 assert self.key_size == self.blocks_per_key * self.block_size 

75 

76 self.max_bytes_per_request = self.max_blocks_per_request * self.block_size 

77 

78 def reseed(self, seed): 

79 if self.key is None: 

80 self.key = b("\0") * self.key_size 

81 

82 self._set_key(SHAd256.new(self.key + seed).digest()) 

83 self.counter() # increment counter 

84 assert len(self.key) == self.key_size 

85 

86 def pseudo_random_data(self, bytes): 

87 assert bytes >= 0 

88 

89 num_full_blocks = bytes >> 20 

90 remainder = bytes & ((1<<20)-1) 

91 

92 retval = [] 

93 for i in range(num_full_blocks): 

94 retval.append(self._pseudo_random_data(1<<20)) 

95 retval.append(self._pseudo_random_data(remainder)) 

96 

97 return b("").join(retval) 

98 

99 def _set_key(self, key): 

100 self.key = key 

101 self._cipher = AES.new(key, AES.MODE_CTR, counter=self.counter) 

102 

103 def _pseudo_random_data(self, bytes): 

104 if not (0 <= bytes <= self.max_bytes_per_request): 

105 raise AssertionError("You cannot ask for more than 1 MiB of data per request") 

106 

107 num_blocks = ceil_shift(bytes, self.block_size_shift) # num_blocks = ceil(bytes / self.block_size) 

108 

109 # Compute the output 

110 retval = self._generate_blocks(num_blocks)[:bytes] 

111 

112 # Switch to a new key to avoid later compromises of this output (i.e. 

113 # state compromise extension attacks) 

114 self._set_key(self._generate_blocks(self.blocks_per_key)) 

115 

116 assert len(retval) == bytes 

117 assert len(self.key) == self.key_size 

118 

119 return retval 

120 

121 def _generate_blocks(self, num_blocks): 

122 if self.key is None: 

123 raise AssertionError("generator must be seeded before use") 

124 assert 0 <= num_blocks <= self.max_blocks_per_request 

125 retval = [] 

126 for i in range(num_blocks >> 12): # xrange(num_blocks / 4096) 

127 retval.append(self._cipher.encrypt(self._four_kiblocks_of_zeros)) 

128 remaining_bytes = (num_blocks & 4095) << self.block_size_shift # (num_blocks % 4095) * self.block_size 

129 retval.append(self._cipher.encrypt(self._four_kiblocks_of_zeros[:remaining_bytes])) 

130 return b("").join(retval) 

131 

132# vim:set ts=4 sw=4 sts=4 expandtab: