-
Notifications
You must be signed in to change notification settings - Fork 0
/
cryptutil.py
230 lines (185 loc) · 6.12 KB
/
cryptutil.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
"""Module containing a cryptographic-quality source of randomness and
other cryptographically useful functionality
Python 2.4 needs no external support for this module, nor does Python
2.3 on a system with /dev/urandom.
Other configurations will need a quality source of random bytes and
access to a function that will convert binary strings to long
integers. This module will work with the Python Cryptography Toolkit
(pycrypto) if it is present. pycrypto can be found with a search
engine, but is currently found at:
http://www.amk.ca/python/code/crypto
"""
__all__ = [
'base64ToLong',
'binaryToLong',
'hmacSha1',
'hmacSha256',
'longToBase64',
'longToBinary',
'randomString',
'randrange',
'sha1',
'sha256',
]
import hmac
import os
import random
from openid.oidutil import toBase64, fromBase64
try:
import hashlib
except ImportError:
import sha as sha1_module
try:
from Crypto.Hash import SHA256 as sha256_module
except ImportError:
sha256_module = None
else:
class HashContainer(object):
def __init__(self, hash_constructor):
self.new = hash_constructor
self.digest_size = hash_constructor().digest_size
sha1_module = HashContainer(hashlib.sha1)
sha256_module = HashContainer(hashlib.sha256)
def hmacSha1(key, text):
return hmac.new(key, text, sha1_module).digest()
def sha1(s):
return sha1_module.new(s).digest()
if sha256_module is not None:
def hmacSha256(key, text):
return hmac.new(key, text, sha256_module).digest()
def sha256(s):
return sha256_module.new(s).digest()
SHA256_AVAILABLE = True
else:
_no_sha256 = NotImplementedError(
'Use Python 2.5, install pycrypto or install hashlib to use SHA256')
def hmacSha256(unused_key, unused_text):
raise _no_sha256
def sha256(s):
raise _no_sha256
SHA256_AVAILABLE = False
try:
from Crypto.Util.number import long_to_bytes, bytes_to_long
except ImportError:
import pickle
try:
# Check Python compatiblity by raising an exception on import
# if the needed functionality is not present. Present in
# Python >= 2.3
pickle.encode_long
pickle.decode_long
except AttributeError:
raise ImportError(
'No functionality for serializing long integers found')
# Present in Python >= 2.4
try:
reversed
except NameError:
def reversed(seq):
return list(map(seq.__getitem__, range(len(seq) - 1, -1, -1)))
def longToBinary(l):
if l == 0:
return '\x00'
return ''.join(reversed(pickle.encode_long(l)))
def binaryToLong(s):
return pickle.decode_long(''.join(reversed(s)))
else:
# We have pycrypto
def longToBinary(l):
if l < 0:
raise ValueError('This function only supports positive integers')
bytes = long_to_bytes(l)
if ord(bytes[0]) > 127:
return '\x00' + bytes
else:
return bytes
def binaryToLong(bytes):
if not bytes:
raise ValueError('Empty string passed to strToLong')
if ord(bytes[0]) > 127:
raise ValueError('This function only supports positive integers')
return bytes_to_long(bytes)
# A cryptographically safe source of random bytes
try:
getBytes = os.urandom
except AttributeError:
try:
from Crypto.Util.randpool import RandomPool
except ImportError:
# Fall back on /dev/urandom, if present. It would be nice to
# have Windows equivalent here, but for now, require pycrypto
# on Windows.
try:
_urandom = file('/dev/urandom', 'rb')
except IOError:
raise ImportError('No adequate source of randomness found!')
else:
def getBytes(n):
bytes = []
while n:
chunk = _urandom.read(n)
n -= len(chunk)
bytes.append(chunk)
assert n >= 0
return ''.join(bytes)
else:
_pool = RandomPool()
def getBytes(n, pool=_pool):
if pool.entropy < n:
pool.randomize()
return pool.get_bytes(n)
# A randrange function that works for longs
try:
randrange = random.SystemRandom().randrange
except AttributeError:
# In Python 2.2's random.Random, randrange does not support
# numbers larger than sys.maxint for randrange. For simplicity,
# use this implementation for any Python that does not have
# random.SystemRandom
from math import log, ceil
_duplicate_cache = {}
def randrange(start, stop=None, step=1):
if stop is None:
stop = start
start = 0
r = (stop - start) // step
try:
(duplicate, nbytes) = _duplicate_cache[r]
except KeyError:
rbytes = longToBinary(r)
if rbytes[0] == '\x00':
nbytes = len(rbytes) - 1
else:
nbytes = len(rbytes)
mxrand = (256 ** nbytes)
# If we get a number less than this, then it is in the
# duplicated range.
duplicate = mxrand % r
if len(_duplicate_cache) > 10:
_duplicate_cache.clear()
_duplicate_cache[r] = (duplicate, nbytes)
while 1:
bytes = '\x00' + getBytes(nbytes)
n = binaryToLong(bytes)
# Keep looping if this value is in the low duplicated range
if n >= duplicate:
break
return start + (n % r) * step
def longToBase64(l):
return toBase64(longToBinary(l))
def base64ToLong(s):
return binaryToLong(fromBase64(s))
def randomString(length, chrs=None):
"""Produce a string of length random bytes, chosen from chrs."""
if chrs is None:
return getBytes(length)
else:
n = len(chrs)
return ''.join([chrs[randrange(n)] for _ in range(length)])
def const_eq(s1, s2):
if len(s1) != len(s2):
return False
result = True
for i in range(len(s1)):
result = result and (s1[i] == s2[i])
return result