entropy.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
  2. # Copyright (C) 2009-2017 Nominum, Inc.
  3. #
  4. # Permission to use, copy, modify, and distribute this software and its
  5. # documentation for any purpose with or without fee is hereby granted,
  6. # provided that the above copyright notice and this permission notice
  7. # appear in all copies.
  8. #
  9. # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
  10. # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
  12. # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  15. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. import hashlib
  17. import os
  18. import random
  19. import threading
  20. import time
  21. from typing import Any, Optional
  22. class EntropyPool:
  23. # This is an entropy pool for Python implementations that do not
  24. # have a working SystemRandom. I'm not sure there are any, but
  25. # leaving this code doesn't hurt anything as the library code
  26. # is used if present.
  27. def __init__(self, seed: Optional[bytes] = None):
  28. self.pool_index = 0
  29. self.digest: Optional[bytearray] = None
  30. self.next_byte = 0
  31. self.lock = threading.Lock()
  32. self.hash = hashlib.sha1()
  33. self.hash_len = 20
  34. self.pool = bytearray(b"\0" * self.hash_len)
  35. if seed is not None:
  36. self._stir(seed)
  37. self.seeded = True
  38. self.seed_pid = os.getpid()
  39. else:
  40. self.seeded = False
  41. self.seed_pid = 0
  42. def _stir(self, entropy: bytes) -> None:
  43. for c in entropy:
  44. if self.pool_index == self.hash_len:
  45. self.pool_index = 0
  46. b = c & 0xFF
  47. self.pool[self.pool_index] ^= b
  48. self.pool_index += 1
  49. def stir(self, entropy: bytes) -> None:
  50. with self.lock:
  51. self._stir(entropy)
  52. def _maybe_seed(self) -> None:
  53. if not self.seeded or self.seed_pid != os.getpid():
  54. try:
  55. seed = os.urandom(16)
  56. except Exception: # pragma: no cover
  57. try:
  58. with open("/dev/urandom", "rb", 0) as r:
  59. seed = r.read(16)
  60. except Exception:
  61. seed = str(time.time()).encode()
  62. self.seeded = True
  63. self.seed_pid = os.getpid()
  64. self.digest = None
  65. seed = bytearray(seed)
  66. self._stir(seed)
  67. def random_8(self) -> int:
  68. with self.lock:
  69. self._maybe_seed()
  70. if self.digest is None or self.next_byte == self.hash_len:
  71. self.hash.update(bytes(self.pool))
  72. self.digest = bytearray(self.hash.digest())
  73. self._stir(self.digest)
  74. self.next_byte = 0
  75. value = self.digest[self.next_byte]
  76. self.next_byte += 1
  77. return value
  78. def random_16(self) -> int:
  79. return self.random_8() * 256 + self.random_8()
  80. def random_32(self) -> int:
  81. return self.random_16() * 65536 + self.random_16()
  82. def random_between(self, first: int, last: int) -> int:
  83. size = last - first + 1
  84. if size > 4294967296:
  85. raise ValueError("too big")
  86. if size > 65536:
  87. rand = self.random_32
  88. max = 4294967295
  89. elif size > 256:
  90. rand = self.random_16
  91. max = 65535
  92. else:
  93. rand = self.random_8
  94. max = 255
  95. return first + size * rand() // (max + 1)
  96. pool = EntropyPool()
  97. system_random: Optional[Any]
  98. try:
  99. system_random = random.SystemRandom()
  100. except Exception: # pragma: no cover
  101. system_random = None
  102. def random_16() -> int:
  103. if system_random is not None:
  104. return system_random.randrange(0, 65536)
  105. else:
  106. return pool.random_16()
  107. def between(first: int, last: int) -> int:
  108. if system_random is not None:
  109. return system_random.randrange(first, last + 1)
  110. else:
  111. return pool.random_between(first, last)