Debian Codegraph @

pbkdf2.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 #!/usr/bin/python
2 # -*- coding: ascii -*-
3 ###########################################################################
4 # pbkdf2 - PKCS#5 v2.0 Password-Based Key Derivation
5 #
6 # Copyright (C) 2007-2011 Dwayne C. Litzenberger <[email protected]>
7 #
8 # Permission is hereby granted, free of charge, to any person obtaining
9 # a copy of this software and associated documentation files (the
10 # "Software"), to deal in the Software without restriction, including
11 # without limitation the rights to use, copy, modify, merge, publish,
12 # distribute, sublicense, and/or sell copies of the Software, and to
13 # permit persons to whom the Software is furnished to do so, subject to
14 # the following conditions:
15 #
16 # The above copyright notice and this permission notice shall be
17 # included in all copies or substantial portions of the Software.
18 #
19 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
22 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
23 # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
24 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
25 # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 #
27 # Country of origin: Canada
28 #
29 ###########################################################################
30 # Sample PBKDF2 usage:
31 # from Crypto.Cipher import AES
32 # from pbkdf2 import PBKDF2
33 # import os
34 #
35 # salt = os.urandom(8) # 64-bit salt
36 # key = PBKDF2("This passphrase is a secret.", salt).read(32) # 256-bit key
37 # iv = os.urandom(16) # 128-bit IV
38 # cipher = AES.new(key, AES.MODE_CBC, iv)
39 # ...
40 #
41 # Sample crypt() usage:
42 # from pbkdf2 import crypt
43 # pwhash = crypt("secret")
44 # alleged_pw = raw_input("Enter password: ")
45 # if pwhash == crypt(alleged_pw, pwhash):
46 # print "Password good"
47 # else:
48 # print "Invalid password"
49 #
50 ###########################################################################
51
52 __version__ = "1.3"
53 __all__ = ['PBKDF2', 'crypt']
54
55 from struct import pack
56 from random import randint
57 import string
58 import sys
59
60 try:
61 # Use PyCrypto (if available).
62 from Crypto.Hash import HMAC, SHA as SHA1
63 except ImportError:
64 # PyCrypto not available. Use the Python standard library.
65 import hmac as HMAC
66 try:
67 from hashlib import sha1 as SHA1
68 except ImportError:
69 # hashlib not available. Use the old sha module.
70 import sha as SHA1
71
72 #
73 # Python 2.1 thru 3.2 compatibility
74 #
75
76 if sys.version_info[0] == 2:
77 _0xffffffffL = long(1) << 32
78 def isunicode(s):
79 return isinstance(s, unicode)
80 def isbytes(s):
81 return isinstance(s, str)
82 def isinteger(n):
83 return isinstance(n, (int, long))
84 def b(s):
85 return s
86 def binxor(a, b):
87 return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b)])
88 def b64encode(data, chars="+/"):
89 tt = string.maketrans("+/", chars)
90 return data.encode('base64').replace("\n", "").translate(tt)
91 from binascii import b2a_hex
92 else:
93 _0xffffffffL = 0xffffffff
94 def isunicode(s):
95 return isinstance(s, str)
96 def isbytes(s):
97 return isinstance(s, bytes)
98 def isinteger(n):
99 return isinstance(n, int)
100 def callable(obj):
101 return hasattr(obj, '__call__')
102 def b(s):
103 return s.encode("latin-1")
•104 if hasattr(int, 'to_bytes') and hasattr(int, 'from_bytes'):
105 _sys_byteorder = sys.byteorder
106 _b2i = int.from_bytes
107 def binxor(a, b):
108 a_int = _b2i(a, _sys_byteorder)
109 b_int = _b2i(b, _sys_byteorder)
110 return (a_int ^ b_int).to_bytes(len(a), _sys_byteorder)
111 else:
112 def binxor(a, b):
113 return bytes([x ^ y for (x, y) in zip(a, b)])
114 from base64 import b64encode as _b64encode
115 def b64encode(data, chars="+/"):
116 if isunicode(chars):
117 return _b64encode(data, chars.encode('utf-8')).decode('utf-8')
118 else:
119 return _b64encode(data, chars)
120 from binascii import b2a_hex as _b2a_hex
121 def b2a_hex(s):
122 return _b2a_hex(s).decode('us-ascii')
123 xrange = range
124
125 class PBKDF2(object):
126 """PBKDF2.py : PKCS#5 v2.0 Password-Based Key Derivation
127
128 This implementation takes a passphrase and a salt (and optionally an
129 iteration count, a digest module, and a MAC module) and provides a
130 file-like object from which an arbitrarily-sized key can be read.
131
132 If the passphrase and/or salt are unicode objects, they are encoded as
133 UTF-8 before they are processed.
134
135 The idea behind PBKDF2 is to derive a cryptographic key from a
136 passphrase and a salt.
137
138 PBKDF2 may also be used as a strong salted password hash. The
139 'crypt' function is provided for that purpose.
140
141 Remember: Keys generated using PBKDF2 are only as strong as the
142 passphrases they are derived from.
143 """
144
145 def __init__(self, passphrase, salt, iterations=1000,
146 digestmodule=SHA1, macmodule=HMAC):
147 self.__macmodule = macmodule
148 self.__digestmodule = digestmodule
149 self._setup(passphrase, salt, iterations, self._pseudorandom)
150
151 def _pseudorandom(self, key, msg):
152 """Pseudorandom function. e.g. HMAC-SHA1"""
153 return self.__macmodule.new(key=key, msg=msg,
154 digestmod=self.__digestmodule).digest()
155
156 def read(self, bytes):
157 """Read the specified number of key bytes."""
158 if self.closed:
159 raise ValueError("file-like object is closed")
160
161 size = len(self.__buf)
162 blocks = [self.__buf]
163 i = self.__blockNum
164 while size < bytes:
165 i += 1
166 if i > _0xffffffffL or i < 1:
167 # We could return "" here, but
168 raise OverflowError("derived key too long")
169 block = self.__f(i)
170 blocks.append(block)
171 size += len(block)
172 buf = b("").join(blocks)
173 retval = buf[:bytes]
174 self.__buf = buf[bytes:]
175 self.__blockNum = i
176 return retval
177
178 def __f(self, i):
179 # i must fit within 32 bits
180 assert 1 <= i <= _0xffffffffL
181 U = self.__prf(self.__passphrase, self.__salt + pack("!L", i))
182 result = U
183 for j in xrange(2, 1+self.__iterations):
184 U = self.__prf(self.__passphrase, U)
185 result = binxor(result, U)
186 return result
187
188 def hexread(self, octets):
189 """Read the specified number of octets. Return them as hexadecimal.
190
191 Note that len(obj.hexread(n)) == 2*n.
192 """
193 return b2a_hex(self.read(octets))
194
195 def _setup(self, passphrase, salt, iterations, prf):
196 # Sanity checks:
197
198 # passphrase and salt must be str or unicode (in the latter
199 # case, we convert to UTF-8)
200 if isunicode(passphrase):
201 passphrase = passphrase.encode("UTF-8")
202 elif not isbytes(passphrase):
203 raise TypeError("passphrase must be str or unicode")
204 if isunicode(salt):
205 salt = salt.encode("UTF-8")
206 elif not isbytes(salt):
207 raise TypeError("salt must be str or unicode")
208
209 # iterations must be an integer >= 1
210 if not isinteger(iterations):
211 raise TypeError("iterations must be an integer")
212 if iterations < 1:
213 raise ValueError("iterations must be at least 1")
214
215 # prf must be callable
216 if not callable(prf):
217 raise TypeError("prf must be callable")
218
219 self.__passphrase = passphrase
220 self.__salt = salt
221 self.__iterations = iterations
222 self.__prf = prf
223 self.__blockNum = 0
224 self.__buf = b("")
225 self.closed = False
226
227 def close(self):
228 """Close the stream."""
229 if not self.closed:
230 del self.__passphrase
231 del self.__salt
232 del self.__iterations
233 del self.__prf
234 del self.__blockNum
235 del self.__buf
236 self.closed = True
237
238 def crypt(word, salt=None, iterations=None):
239 """PBKDF2-based unix crypt(3) replacement.
240
241 The number of iterations specified in the salt overrides the 'iterations'
242 parameter.
243
244 The effective hash length is 192 bits.
245 """
246
247 # Generate a (pseudo-)random salt if the user hasn't provided one.
248 if salt is None:
249 salt = _makesalt()
250
251 # salt must be a string or the us-ascii subset of unicode
252 if isunicode(salt):
253 salt = salt.encode('us-ascii').decode('us-ascii')
254 elif isbytes(salt):
255 salt = salt.decode('us-ascii')
256 else:
257 raise TypeError("salt must be a string")
258
259 # word must be a string or unicode (in the latter case, we convert to UTF-8)
260 if isunicode(word):
261 word = word.encode("UTF-8")
262 elif not isbytes(word):
263 raise TypeError("word must be a string or unicode")
264
265 # Try to extract the real salt and iteration count from the salt
266 if salt.startswith("$p5k2$"):
267 (iterations, salt, dummy) = salt.split("$")[2:5]
268 if iterations == "":
269 iterations = 400
270 else:
271 converted = int(iterations, 16)
272 if iterations != "%x" % converted: # lowercase hex, minimum digits
273 raise ValueError("Invalid salt")
274 iterations = converted
275 if not (iterations >= 1):
276 raise ValueError("Invalid salt")
277
278 # Make sure the salt matches the allowed character set
279 allowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./"
280 for ch in salt:
281 if ch not in allowed:
282 raise ValueError("Illegal character %r in salt" % (ch,))
283
284 if iterations is None or iterations == 400:
285 iterations = 400
286 salt = "$p5k2$$" + salt
287 else:
288 salt = "$p5k2$%x$%s" % (iterations, salt)
289 rawhash = PBKDF2(word, salt, iterations).read(24)
290 return salt + "$" + b64encode(rawhash, "./")
291
292 # Add crypt as a static method of the PBKDF2 class
293 # This makes it easier to do "from PBKDF2 import PBKDF2" and still use
294 # crypt.
295 PBKDF2.crypt = staticmethod(crypt)
296
297 def _makesalt():
298 """Return a 48-bit pseudorandom salt for crypt().
299
300 This function is not suitable for generating cryptographic secrets.
301 """
302 binarysalt = b("").join([pack("@H", randint(0, 0xffff)) for i in range(3)])
303 return b64encode(binarysalt, "./")
304
305 # vim:set ts=4 sw=4 sts=4 expandtab: