random.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Random/random.py : Strong alternative for the standard 'random' module
  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. """A cryptographically strong version of Python's standard "random" module."""
  25. __revision__ = "$Id$"
  26. __all__ = ['StrongRandom', 'getrandbits', 'randrange', 'randint', 'choice', 'shuffle', 'sample']
  27. from Crypto import Random
  28. import sys
  29. if sys.version_info[0] == 2 and sys.version_info[1] == 1:
  30. from Crypto.Util.py21compat import *
  31. class StrongRandom(object):
  32. def __init__(self, rng=None, randfunc=None):
  33. if randfunc is None and rng is None:
  34. self._randfunc = None
  35. elif randfunc is not None and rng is None:
  36. self._randfunc = randfunc
  37. elif randfunc is None and rng is not None:
  38. self._randfunc = rng.read
  39. else:
  40. raise ValueError("Cannot specify both 'rng' and 'randfunc'")
  41. def getrandbits(self, k):
  42. """Return a python long integer with k random bits."""
  43. if self._randfunc is None:
  44. self._randfunc = Random.new().read
  45. mask = (1L << k) - 1
  46. return mask & bytes_to_long(self._randfunc(ceil_div(k, 8)))
  47. def randrange(self, *args):
  48. """randrange([start,] stop[, step]):
  49. Return a randomly-selected element from range(start, stop, step)."""
  50. if len(args) == 3:
  51. (start, stop, step) = args
  52. elif len(args) == 2:
  53. (start, stop) = args
  54. step = 1
  55. elif len(args) == 1:
  56. (stop,) = args
  57. start = 0
  58. step = 1
  59. else:
  60. raise TypeError("randrange expected at most 3 arguments, got %d" % (len(args),))
  61. if (not isinstance(start, (int, long))
  62. or not isinstance(stop, (int, long))
  63. or not isinstance(step, (int, long))):
  64. raise TypeError("randrange requires integer arguments")
  65. if step == 0:
  66. raise ValueError("randrange step argument must not be zero")
  67. num_choices = ceil_div(stop - start, step)
  68. if num_choices < 0:
  69. num_choices = 0
  70. if num_choices < 1:
  71. raise ValueError("empty range for randrange(%r, %r, %r)" % (start, stop, step))
  72. # Pick a random number in the range of possible numbers
  73. r = num_choices
  74. while r >= num_choices:
  75. r = self.getrandbits(size(num_choices))
  76. return start + (step * r)
  77. def randint(self, a, b):
  78. """Return a random integer N such that a <= N <= b."""
  79. if not isinstance(a, (int, long)) or not isinstance(b, (int, long)):
  80. raise TypeError("randint requires integer arguments")
  81. N = self.randrange(a, b+1)
  82. assert a <= N <= b
  83. return N
  84. def choice(self, seq):
  85. """Return a random element from a (non-empty) sequence.
  86. If the seqence is empty, raises IndexError.
  87. """
  88. if len(seq) == 0:
  89. raise IndexError("empty sequence")
  90. return seq[self.randrange(len(seq))]
  91. def shuffle(self, x):
  92. """Shuffle the sequence in place."""
  93. # Make a (copy) of the list of objects we want to shuffle
  94. items = list(x)
  95. # Choose a random item (without replacement) until all the items have been
  96. # chosen.
  97. for i in xrange(len(x)):
  98. x[i] = items.pop(self.randrange(len(items)))
  99. def sample(self, population, k):
  100. """Return a k-length list of unique elements chosen from the population sequence."""
  101. num_choices = len(population)
  102. if k > num_choices:
  103. raise ValueError("sample larger than population")
  104. retval = []
  105. selected = {} # we emulate a set using a dict here
  106. for i in xrange(k):
  107. r = None
  108. while r is None or selected.has_key(r):
  109. r = self.randrange(num_choices)
  110. retval.append(population[r])
  111. selected[r] = 1
  112. return retval
  113. _r = StrongRandom()
  114. getrandbits = _r.getrandbits
  115. randrange = _r.randrange
  116. randint = _r.randint
  117. choice = _r.choice
  118. shuffle = _r.shuffle
  119. sample = _r.sample
  120. # These are at the bottom to avoid problems with recursive imports
  121. from Crypto.Util.number import ceil_div, bytes_to_long, long_to_bytes, size
  122. # vim:set ts=4 sw=4 sts=4 expandtab: