|
1 |
| -"""Convenience functions for random operations. Not suitable for security / cryptography operations.""" |
| 1 | +"""Keep all imports from random in one place""" |
2 | 2 |
|
3 |
| -import os |
4 |
| -import random |
5 | 3 |
|
6 |
| -try: |
7 |
| - from pyelliptic.openssl import OpenSSL |
8 |
| -except ImportError: |
9 |
| - from .pyelliptic.openssl import OpenSSL |
| 4 | +from random import seed |
| 5 | +from random import shuffle as randomshuffle |
| 6 | +from random import sample as randomsample |
| 7 | +from random import randrange as randomrandrange |
| 8 | +from random import choice as randomchoice |
| 9 | +from highlevelcrypto import randomBytes |
10 | 10 |
|
11 |
| -NoneType = type(None) |
12 |
| - |
13 |
| - |
14 |
| -def seed(): |
15 |
| - """Initialize random number generator""" |
16 |
| - random.seed() |
17 |
| - |
18 |
| - |
19 |
| -def randomBytes(n): |
20 |
| - """Method randomBytes.""" |
21 |
| - try: |
22 |
| - return os.urandom(n) |
23 |
| - except NotImplementedError: |
24 |
| - return OpenSSL.rand(n) |
25 |
| - |
26 |
| - |
27 |
| -def randomshuffle(population): |
28 |
| - """Method randomShuffle. |
29 |
| -
|
30 |
| - shuffle the sequence x in place. |
31 |
| - shuffles the elements in list in place, |
32 |
| - so they are in a random order. |
33 |
| - As Shuffle will alter data in-place, |
34 |
| - so its input must be a mutable sequence. |
35 |
| - In contrast, sample produces a new list |
36 |
| - and its input can be much more varied |
37 |
| - (tuple, string, xrange, bytearray, set, etc) |
38 |
| - """ |
39 |
| - random.shuffle(population) |
40 |
| - |
41 |
| - |
42 |
| -def randomsample(population, k): |
43 |
| - """Method randomSample. |
44 |
| -
|
45 |
| - return a k length list of unique elements |
46 |
| - chosen from the population sequence. |
47 |
| - Used for random sampling |
48 |
| - without replacement, its called |
49 |
| - partial shuffle. |
50 |
| - """ |
51 |
| - return random.sample(population, k) |
52 |
| - |
53 |
| - |
54 |
| -def randomrandrange(x, y=None): |
55 |
| - """Method randomRandrange. |
56 |
| -
|
57 |
| - return a randomly selected element from |
58 |
| - range(start, stop). This is equivalent to |
59 |
| - choice(range(start, stop)), |
60 |
| - but doesnt actually build a range object. |
61 |
| - """ |
62 |
| - if isinstance(y, NoneType): |
63 |
| - return random.randrange(x) # nosec |
64 |
| - return random.randrange(x, y) # nosec |
65 |
| - |
66 |
| - |
67 |
| -def randomchoice(population): |
68 |
| - """Method randomchoice. |
69 |
| -
|
70 |
| - Return a random element from the non-empty |
71 |
| - sequence seq. If seq is empty, raises |
72 |
| - IndexError. |
73 |
| - """ |
74 |
| - return random.choice(population) # nosec |
| 11 | +__all__ = [ |
| 12 | + 'seed', 'randomBytes', 'randomshuffle', 'randomsample', 'randomrandrange', |
| 13 | + 'randomchoice' |
| 14 | +] |
0 commit comments