comparison MoinMoin/support/passlib/utils/md4.py @ 5919:efd7c0be3339

added passlib 1.6.1 to MoinMoin/support/ removed passlib's unit tests (so our test runner does not run them also)
author Thomas Waldmann <tw AT waldmann-edv DOT de>
date Fri, 18 Jan 2013 01:38:07 +0100
parents
children 86a41c2bedec
comparison
equal deleted inserted replaced
5918:5126fadbf24f 5919:efd7c0be3339
1 """
2 helper implementing insecure and obsolete md4 algorithm.
3 used for NTHASH format, which is also insecure and broken,
4 since it's just md4(password)
5
6 implementated based on rfc at http://www.faqs.org/rfcs/rfc1320.html
7
8 """
9
10 #=============================================================================
11 # imports
12 #=============================================================================
13 # core
14 from binascii import hexlify
15 import struct
16 from warnings import warn
17 # site
18 from passlib.utils.compat import b, bytes, bascii_to_str, irange, PY3
19 # local
20 __all__ = [ "md4" ]
21 #=============================================================================
22 # utils
23 #=============================================================================
24 def F(x,y,z):
25 return (x&y) | ((~x) & z)
26
27 def G(x,y,z):
28 return (x&y) | (x&z) | (y&z)
29
30 ##def H(x,y,z):
31 ## return x ^ y ^ z
32
33 MASK_32 = 2**32-1
34
35 #=============================================================================
36 # main class
37 #=============================================================================
38 class md4(object):
39 """pep-247 compatible implementation of MD4 hash algorithm
40
41 .. attribute:: digest_size
42
43 size of md4 digest in bytes (16 bytes)
44
45 .. method:: update
46
47 update digest by appending additional content
48
49 .. method:: copy
50
51 create clone of digest object, including current state
52
53 .. method:: digest
54
55 return bytes representing md4 digest of current content
56
57 .. method:: hexdigest
58
59 return hexdecimal version of digest
60 """
61 # FIXME: make this follow hash object PEP better.
62 # FIXME: this isn't threadsafe
63 # XXX: should we monkeypatch ourselves into hashlib for general use? probably wouldn't be nice.
64
65 name = "md4"
66 digest_size = digestsize = 16
67
68 _count = 0 # number of 64-byte blocks processed so far (not including _buf)
69 _state = None # list of [a,b,c,d] 32 bit ints used as internal register
70 _buf = None # data processed in 64 byte blocks, this holds leftover from last update
71
72 def __init__(self, content=None):
73 self._count = 0
74 self._state = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
75 self._buf = b('')
76 if content:
77 self.update(content)
78
79 # round 1 table - [abcd k s]
80 _round1 = [
81 [0,1,2,3, 0,3],
82 [3,0,1,2, 1,7],
83 [2,3,0,1, 2,11],
84 [1,2,3,0, 3,19],
85
86 [0,1,2,3, 4,3],
87 [3,0,1,2, 5,7],
88 [2,3,0,1, 6,11],
89 [1,2,3,0, 7,19],
90
91 [0,1,2,3, 8,3],
92 [3,0,1,2, 9,7],
93 [2,3,0,1, 10,11],
94 [1,2,3,0, 11,19],
95
96 [0,1,2,3, 12,3],
97 [3,0,1,2, 13,7],
98 [2,3,0,1, 14,11],
99 [1,2,3,0, 15,19],
100 ]
101
102 # round 2 table - [abcd k s]
103 _round2 = [
104 [0,1,2,3, 0,3],
105 [3,0,1,2, 4,5],
106 [2,3,0,1, 8,9],
107 [1,2,3,0, 12,13],
108
109 [0,1,2,3, 1,3],
110 [3,0,1,2, 5,5],
111 [2,3,0,1, 9,9],
112 [1,2,3,0, 13,13],
113
114 [0,1,2,3, 2,3],
115 [3,0,1,2, 6,5],
116 [2,3,0,1, 10,9],
117 [1,2,3,0, 14,13],
118
119 [0,1,2,3, 3,3],
120 [3,0,1,2, 7,5],
121 [2,3,0,1, 11,9],
122 [1,2,3,0, 15,13],
123 ]
124
125 # round 3 table - [abcd k s]
126 _round3 = [
127 [0,1,2,3, 0,3],
128 [3,0,1,2, 8,9],
129 [2,3,0,1, 4,11],
130 [1,2,3,0, 12,15],
131
132 [0,1,2,3, 2,3],
133 [3,0,1,2, 10,9],
134 [2,3,0,1, 6,11],
135 [1,2,3,0, 14,15],
136
137 [0,1,2,3, 1,3],
138 [3,0,1,2, 9,9],
139 [2,3,0,1, 5,11],
140 [1,2,3,0, 13,15],
141
142 [0,1,2,3, 3,3],
143 [3,0,1,2, 11,9],
144 [2,3,0,1, 7,11],
145 [1,2,3,0, 15,15],
146 ]
147
148 def _process(self, block):
149 "process 64 byte block"
150 # unpack block into 16 32-bit ints
151 X = struct.unpack("<16I", block)
152
153 # clone state
154 orig = self._state
155 state = list(orig)
156
157 # round 1 - F function - (x&y)|(~x & z)
158 for a,b,c,d,k,s in self._round1:
159 t = (state[a] + F(state[b],state[c],state[d]) + X[k]) & MASK_32
160 state[a] = ((t<<s) & MASK_32) + (t>>(32-s))
161
162 # round 2 - G function
163 for a,b,c,d,k,s in self._round2:
164 t = (state[a] + G(state[b],state[c],state[d]) + X[k] + 0x5a827999) & MASK_32
165 state[a] = ((t<<s) & MASK_32) + (t>>(32-s))
166
167 # round 3 - H function - x ^ y ^ z
168 for a,b,c,d,k,s in self._round3:
169 t = (state[a] + (state[b] ^ state[c] ^ state[d]) + X[k] + 0x6ed9eba1) & MASK_32
170 state[a] = ((t<<s) & MASK_32) + (t>>(32-s))
171
172 # add back into original state
173 for i in irange(4):
174 orig[i] = (orig[i]+state[i]) & MASK_32
175
176 def update(self, content):
177 if not isinstance(content, bytes):
178 raise TypeError("expected bytes")
179 buf = self._buf
180 if buf:
181 content = buf + content
182 idx = 0
183 end = len(content)
184 while True:
185 next = idx + 64
186 if next <= end:
187 self._process(content[idx:next])
188 self._count += 1
189 idx = next
190 else:
191 self._buf = content[idx:]
192 return
193
194 def copy(self):
195 other = _builtin_md4()
196 other._count = self._count
197 other._state = list(self._state)
198 other._buf = self._buf
199 return other
200
201 def digest(self):
202 # NOTE: backing up state so we can restore it after _process is called,
203 # in case object is updated again (this is only attr altered by this method)
204 orig = list(self._state)
205
206 # final block: buf + 0x80,
207 # then 0x00 padding until congruent w/ 56 mod 64 bytes
208 # then last 8 bytes = msg length in bits
209 buf = self._buf
210 msglen = self._count*512 + len(buf)*8
211 block = buf + b('\x80') + b('\x00') * ((119-len(buf)) % 64) + \
212 struct.pack("<2I", msglen & MASK_32, (msglen>>32) & MASK_32)
213 if len(block) == 128:
214 self._process(block[:64])
215 self._process(block[64:])
216 else:
217 assert len(block) == 64
218 self._process(block)
219
220 # render digest & restore un-finalized state
221 out = struct.pack("<4I", *self._state)
222 self._state = orig
223 return out
224
225 def hexdigest(self):
226 return bascii_to_str(hexlify(self.digest()))
227
228 #===================================================================
229 # eoc
230 #===================================================================
231
232 # keep ref around for unittest, 'md4' usually replaced by ssl wrapper, below.
233 _builtin_md4 = md4
234
235 #=============================================================================
236 # check if hashlib provides accelarated md4
237 #=============================================================================
238 import hashlib
239 from passlib.utils import PYPY
240
241 def _has_native_md4(): # pragma: no cover -- runtime detection
242 try:
243 h = hashlib.new("md4")
244 except ValueError:
245 # not supported - ssl probably missing (e.g. ironpython)
246 return False
247 result = h.hexdigest()
248 if result == '31d6cfe0d16ae931b73c59d7e0c089c0':
249 return True
250 if PYPY and result == '':
251 # workaround for https://bugs.pypy.org/issue957, fixed in PyPy 1.8
252 return False
253 # anything else and we should alert user
254 from passlib.exc import PasslibRuntimeWarning
255 warn("native md4 support disabled, sanity check failed!", PasslibRuntimeWarning)
256 return False
257
258 if _has_native_md4():
259 # overwrite md4 class w/ hashlib wrapper
260 def md4(content=None):
261 "wrapper for hashlib.new('md4')"
262 return hashlib.new('md4', content or b(''))
263
264 #=============================================================================
265 # eof
266 #=============================================================================