| 10 |
|
import random
|
| 11 |
|
L = []
|
| 12 |
|
for i in range(size):
|
| 13 |
|
L.append(chr(random.randint(0, 255)))
|
| 14 |
|
return "".join(L)
|
| |
10 |
"""
|
| |
11 |
Generate a cryptographically-secure random key. This is done by using
|
| |
12 |
Python 2.4's os.urandom, or PyCrypto.
|
| |
13 |
"""
|
| |
14 |
import os
|
| |
15 |
if hasattr(os, "urandom"): # Python 2.4+
|
| |
16 |
return os.urandom(size)
|
| |
17 |
|
| |
18 |
# Try using PyCrypto if available
|
| |
19 |
try:
|
| |
20 |
from Crypto.Util.randpool import RandPool
|
| |
21 |
from Crypto.Hash import SHA512
|
| |
22 |
return RandPool(hash=SHA512).get_bytes(size)
|
| |
23 |
|
| |
24 |
except ImportError:
|
| |
25 |
print >>sys.stderr, "WARNING: The generated key will not be cryptographically-secure key. Consider using Python 2.4+ to generate the key, or install PyCrypto."
|
| |
26 |
|
| |
27 |
# Stupid random generation
|
| |
28 |
import random
|
| |
29 |
L = []
|
| |
30 |
for i in range(size):
|
| |
31 |
L.append(chr(random.randint(0, 255)))
|
| |
32 |
return "".join(L)
|