FortunaGenerator.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  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. __revision__ = "$Id$"
  25. import sys
  26. if sys.version_info[0] is 2 and sys.version_info[1] is 1:
  27. from Crypto.Util.py21compat import *
  28. from Crypto.Util.py3compat import *
  29. import struct
  30. from Crypto.Util.number import ceil_shift, exact_log2, exact_div
  31. from Crypto.Util import Counter
  32. from Crypto.Cipher import AES
  33. import SHAd256
  34. class AESGenerator(object):
  35. """The Fortuna "generator"
  36. This is used internally by the Fortuna PRNG to generate arbitrary amounts
  37. of pseudorandom data from a smaller amount of seed data.
  38. The output is generated by running AES-256 in counter mode and re-keying
  39. after every mebibyte (2**16 blocks) of output.
  40. """
  41. block_size = AES.block_size # output block size in octets (128 bits)
  42. key_size = 32 # key size in octets (256 bits)
  43. # Because of the birthday paradox, we expect to find approximately one
  44. # collision for every 2**64 blocks of output from a real random source.
  45. # However, this code generates pseudorandom data by running AES in
  46. # counter mode, so there will be no collisions until the counter
  47. # (theoretically) wraps around at 2**128 blocks. Thus, in order to prevent
  48. # Fortuna's pseudorandom output from deviating perceptibly from a true
  49. # random source, Ferguson and Schneier specify a limit of 2**16 blocks
  50. # without rekeying.
  51. max_blocks_per_request = 2**16 # Allow no more than this number of blocks per _pseudo_random_data request
  52. _four_kiblocks_of_zeros = b("\0") * block_size * 4096
  53. def __init__(self):
  54. self.counter = Counter.new(nbits=self.block_size*8, initial_value=0, little_endian=True)
  55. self.key = None
  56. # Set some helper constants
  57. self.block_size_shift = exact_log2(self.block_size)
  58. assert (1 << self.block_size_shift) == self.block_size
  59. self.blocks_per_key = exact_div(self.key_size, self.block_size)
  60. assert self.key_size == self.blocks_per_key * self.block_size
  61. self.max_bytes_per_request = self.max_blocks_per_request * self.block_size
  62. def reseed(self, seed):
  63. if self.key is None:
  64. self.key = b("\0") * self.key_size
  65. self._set_key(SHAd256.new(self.key + seed).digest())
  66. self.counter() # increment counter
  67. assert len(self.key) == self.key_size
  68. def pseudo_random_data(self, bytes):
  69. assert bytes >= 0
  70. num_full_blocks = bytes >> 20
  71. remainder = bytes & ((1<<20)-1)
  72. retval = []
  73. for i in xrange(num_full_blocks):
  74. retval.append(self._pseudo_random_data(1<<20))
  75. retval.append(self._pseudo_random_data(remainder))
  76. return b("").join(retval)
  77. def _set_key(self, key):
  78. self.key = key
  79. self._cipher = AES.new(key, AES.MODE_CTR, counter=self.counter)
  80. def _pseudo_random_data(self, bytes):
  81. if not (0 <= bytes <= self.max_bytes_per_request):
  82. raise AssertionError("You cannot ask for more than 1 MiB of data per request")
  83. num_blocks = ceil_shift(bytes, self.block_size_shift) # num_blocks = ceil(bytes / self.block_size)
  84. # Compute the output
  85. retval = self._generate_blocks(num_blocks)[:bytes]
  86. # Switch to a new key to avoid later compromises of this output (i.e.
  87. # state compromise extension attacks)
  88. self._set_key(self._generate_blocks(self.blocks_per_key))
  89. assert len(retval) == bytes
  90. assert len(self.key) == self.key_size
  91. return retval
  92. def _generate_blocks(self, num_blocks):
  93. if self.key is None:
  94. raise AssertionError("generator must be seeded before use")
  95. assert 0 <= num_blocks <= self.max_blocks_per_request
  96. retval = []
  97. for i in xrange(num_blocks >> 12): # xrange(num_blocks / 4096)
  98. retval.append(self._cipher.encrypt(self._four_kiblocks_of_zeros))
  99. remaining_bytes = (num_blocks & 4095) << self.block_size_shift # (num_blocks % 4095) * self.block_size
  100. retval.append(self._cipher.encrypt(self._four_kiblocks_of_zeros[:remaining_bytes]))
  101. return b("").join(retval)
  102. # vim:set ts=4 sw=4 sts=4 expandtab: