Debian Codegraph @

lib/Crypto/Random/random.py

raw symbols SCIP
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 <[email protected]>
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 __all__ = ['StrongRandom', 'getrandbits', 'randrange', 'randint', 'choice', 'shuffle', 'sample']
26
27 from Crypto import Random
28
29 from Crypto.Util.py3compat import is_native_int
30
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
42 def getrandbits(self, k):
43 """Return an integer with k random bits."""
44
45 if self._randfunc is None:
46 self._randfunc = Random.new().read
47 mask = (1 << k) - 1
48 return mask & bytes_to_long(self._randfunc(ceil_div(k, 8)))
49
50 def randrange(self, *args):
51 """randrange([start,] stop[, step]):
52 Return a randomly-selected element from range(start, stop, step)."""
53 if len(args) == 3:
54 (start, stop, step) = args
55 elif len(args) == 2:
56 (start, stop) = args
57 step = 1
58 elif len(args) == 1:
59 (stop,) = args
60 start = 0
61 step = 1
62 else:
63 raise TypeError("randrange expected at most 3 arguments, got %d" % (len(args),))
64 if (not is_native_int(start) or not is_native_int(stop) or not
65 is_native_int(step)):
66 raise TypeError("randrange requires integer arguments")
67 if step == 0:
68 raise ValueError("randrange step argument must not be zero")
69
70 num_choices = ceil_div(stop - start, step)
71 if num_choices < 0:
72 num_choices = 0
73 if num_choices < 1:
74 raise ValueError("empty range for randrange(%r, %r, %r)" % (start, stop, step))
75
76 # Pick a random number in the range of possible numbers
77 r = num_choices
78 while r >= num_choices:
79 r = self.getrandbits(size(num_choices))
80
81 return start + (step * r)
82
83 def randint(self, a, b):
84 """Return a random integer N such that a <= N <= b."""
85 if not is_native_int(a) or not is_native_int(b):
86 raise TypeError("randint requires integer arguments")
87 N = self.randrange(a, b+1)
88 assert a <= N <= b
89 return N
90
91 def choice(self, seq):
92 """Return a random element from a (non-empty) sequence.
93
94 If the seqence is empty, raises IndexError.
95 """
96 if len(seq) == 0:
97 raise IndexError("empty sequence")
98 return seq[self.randrange(len(seq))]
99
100 def shuffle(self, x):
101 """Shuffle the sequence in place."""
102 # Fisher-Yates shuffle. O(n)
103 # See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
104 # Working backwards from the end of the array, we choose a random item
105 # from the remaining items until all items have been chosen.
106 for i in range(len(x)-1, 0, -1): # iterate from len(x)-1 downto 1
107 j = self.randrange(0, i+1) # choose random j such that 0 <= j <= i
108 x[i], x[j] = x[j], x[i] # exchange x[i] and x[j]
109
110 def sample(self, population, k):
111 """Return a k-length list of unique elements chosen from the population sequence."""
112
113 num_choices = len(population)
114 if k > num_choices:
115 raise ValueError("sample larger than population")
116
117 retval = []
118 selected = {} # we emulate a set using a dict here
119 for i in range(k):
120 r = None
121 while r is None or r in selected:
122 r = self.randrange(num_choices)
123 retval.append(population[r])
124 selected[r] = 1
125 return retval
126
127 _r = StrongRandom()
128 getrandbits = _r.getrandbits
129 randrange = _r.randrange
130 randint = _r.randint
131 choice = _r.choice
132 shuffle = _r.shuffle
133 sample = _r.sample
134
135 # These are at the bottom to avoid problems with recursive imports
136 from Crypto.Util.number import ceil_div, bytes_to_long, long_to_bytes, size
137
138 # vim:set ts=4 sw=4 sts=4 expandtab: