1 | # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) |
---|
2 | # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php |
---|
3 | """ |
---|
4 | Create random secrets. |
---|
5 | """ |
---|
6 | |
---|
7 | import os |
---|
8 | import random |
---|
9 | |
---|
10 | def random_bytes(length): |
---|
11 | """ |
---|
12 | Return a string of the given length. Uses ``os.urandom`` if it |
---|
13 | can, or just pseudo-random numbers otherwise. |
---|
14 | """ |
---|
15 | try: |
---|
16 | return os.urandom(length) |
---|
17 | except AttributeError: |
---|
18 | return ''.join([ |
---|
19 | chr(random.randrange(256)) for i in xrange(length)]) |
---|
20 | |
---|
21 | def secret_string(length=25): |
---|
22 | """ |
---|
23 | Returns a random string of the given length. The string |
---|
24 | is a base64-encoded version of a set of random bytes, truncated |
---|
25 | to the given length (and without any newlines). |
---|
26 | """ |
---|
27 | s = random_bytes(length).encode('base64') |
---|
28 | for badchar in '\n\r=': |
---|
29 | s = s.replace(badchar, '') |
---|
30 | # We're wasting some characters here. But random characters are |
---|
31 | # cheap ;) |
---|
32 | return s[:length] |
---|