pypbkdf2.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. #!/usr/bin/python
  2. # -*- coding: ascii -*-
  3. ###########################################################################
  4. # PBKDF2.py - PKCS#5 v2.0 Password-Based Key Derivation
  5. #
  6. # Copyright (C) 2007, 2008 Dwayne C. Litzenberger <dlitz@dlitz.net>
  7. # All rights reserved.
  8. #
  9. # Permission to use, copy, modify, and distribute this software and its
  10. # documentation for any purpose and without fee is hereby granted,
  11. # provided that the above copyright notice appear in all copies and that
  12. # both that copyright notice and this permission notice appear in
  13. # supporting documentation.
  14. #
  15. # THE AUTHOR PROVIDES THIS SOFTWARE ``AS IS'' AND ANY EXPRESSED OR
  16. # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  17. # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  18. # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  19. # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  20. # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  21. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  22. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. #
  26. # Country of origin: Canada
  27. #
  28. ###########################################################################
  29. # Sample PBKDF2 usage:
  30. # from Crypto.Cipher import AES
  31. # from PBKDF2 import PBKDF2
  32. # import os
  33. #
  34. # salt = os.urandom(8) # 64-bit salt
  35. # key = PBKDF2("This passphrase is a secret.", salt).read(32) # 256-bit key
  36. # iv = os.urandom(16) # 128-bit IV
  37. # cipher = AES.new(key, AES.MODE_CBC, iv)
  38. # ...
  39. #
  40. # Sample crypt() usage:
  41. # from PBKDF2 import crypt
  42. # pwhash = crypt("secret")
  43. # alleged_pw = raw_input("Enter password: ")
  44. # if pwhash == crypt(alleged_pw, pwhash):
  45. # print "Password good"
  46. # else:
  47. # print "Invalid password"
  48. #
  49. ###########################################################################
  50. # History:
  51. #
  52. # 2007-07-27 Dwayne C. Litzenberger <dlitz@dlitz.net>
  53. # - Initial Release (v1.0)
  54. #
  55. # 2007-07-31 Dwayne C. Litzenberger <dlitz@dlitz.net>
  56. # - Bugfix release (v1.1)
  57. # - SECURITY: The PyCrypto XOR cipher (used, if available, in the _strxor
  58. # function in the previous release) silently truncates all keys to 64
  59. # bytes. The way it was used in the previous release, this would only be
  60. # problem if the pseudorandom function that returned values larger than
  61. # 64 bytes (so SHA1, SHA256 and SHA512 are fine), but I don't like
  62. # anything that silently reduces the security margin from what is
  63. # expected.
  64. #
  65. # 2008-06-17 Dwayne C. Litzenberger <dlitz@dlitz.net>
  66. # - Compatibility release (v1.2)
  67. # - Add support for older versions of Python (2.2 and 2.3).
  68. #
  69. ###########################################################################
  70. __version__ = "1.2"
  71. from struct import pack
  72. from binascii import b2a_hex
  73. from random import randint
  74. import string
  75. try:
  76. # Use PyCrypto (if available)
  77. from Crypto.Hash import HMAC, SHA as SHA1
  78. except ImportError:
  79. # PyCrypto not available. Use the Python standard library.
  80. import hmac as HMAC
  81. import sha as SHA1
  82. def strxor(a, b):
  83. return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b)])
  84. def b64encode(data, chars="+/"):
  85. tt = string.maketrans("+/", chars)
  86. return data.encode('base64').replace("\n", "").translate(tt)
  87. class PBKDF2(object):
  88. """PBKDF2.py : PKCS#5 v2.0 Password-Based Key Derivation
  89. This implementation takes a passphrase and a salt (and optionally an
  90. iteration count, a digest module, and a MAC module) and provides a
  91. file-like object from which an arbitrarily-sized key can be read.
  92. If the passphrase and/or salt are unicode objects, they are encoded as
  93. UTF-8 before they are processed.
  94. The idea behind PBKDF2 is to derive a cryptographic key from a
  95. passphrase and a salt.
  96. PBKDF2 may also be used as a strong salted password hash. The
  97. 'crypt' function is provided for that purpose.
  98. Remember: Keys generated using PBKDF2 are only as strong as the
  99. passphrases they are derived from.
  100. """
  101. def __init__(self, passphrase, salt, iterations=1000,
  102. digestmodule=SHA1, macmodule=HMAC):
  103. self.__macmodule = macmodule
  104. self.__digestmodule = digestmodule
  105. self._setup(passphrase, salt, iterations, self._pseudorandom)
  106. def _pseudorandom(self, key, msg):
  107. """Pseudorandom function. e.g. HMAC-SHA1"""
  108. return self.__macmodule.new(key=key, msg=msg,
  109. digestmod=self.__digestmodule).digest()
  110. def read(self, bytes):
  111. """Read the specified number of key bytes."""
  112. if self.closed:
  113. raise ValueError("file-like object is closed")
  114. size = len(self.__buf)
  115. blocks = [self.__buf]
  116. i = self.__blockNum
  117. while size < bytes:
  118. i += 1
  119. if i > 0xffffffffL or i < 1:
  120. # We could return "" here, but
  121. raise OverflowError("derived key too long")
  122. block = self.__f(i)
  123. blocks.append(block)
  124. size += len(block)
  125. buf = "".join(blocks)
  126. retval = buf[:bytes]
  127. self.__buf = buf[bytes:]
  128. self.__blockNum = i
  129. return retval
  130. def __f(self, i):
  131. # i must fit within 32 bits
  132. assert 1 <= i <= 0xffffffffL
  133. U = self.__prf(self.__passphrase, self.__salt + pack("!L", i))
  134. result = U
  135. for j in xrange(2, 1+self.__iterations):
  136. U = self.__prf(self.__passphrase, U)
  137. result = strxor(result, U)
  138. return result
  139. def hexread(self, octets):
  140. """Read the specified number of octets. Return them as hexadecimal.
  141. Note that len(obj.hexread(n)) == 2*n.
  142. """
  143. return b2a_hex(self.read(octets))
  144. def _setup(self, passphrase, salt, iterations, prf):
  145. # Sanity checks:
  146. # passphrase and salt must be str or unicode (in the latter
  147. # case, we convert to UTF-8)
  148. if isinstance(passphrase, unicode):
  149. passphrase = passphrase.encode("UTF-8")
  150. if not isinstance(passphrase, str):
  151. raise TypeError("passphrase must be str or unicode")
  152. if isinstance(salt, unicode):
  153. salt = salt.encode("UTF-8")
  154. if not isinstance(salt, str):
  155. raise TypeError("salt must be str or unicode")
  156. # iterations must be an integer >= 1
  157. if not isinstance(iterations, (int, long)):
  158. raise TypeError("iterations must be an integer")
  159. if iterations < 1:
  160. raise ValueError("iterations must be at least 1")
  161. # prf must be callable
  162. if not callable(prf):
  163. raise TypeError("prf must be callable")
  164. self.__passphrase = passphrase
  165. self.__salt = salt
  166. self.__iterations = iterations
  167. self.__prf = prf
  168. self.__blockNum = 0
  169. self.__buf = ""
  170. self.closed = False
  171. def close(self):
  172. """Close the stream."""
  173. if not self.closed:
  174. del self.__passphrase
  175. del self.__salt
  176. del self.__iterations
  177. del self.__prf
  178. del self.__blockNum
  179. del self.__buf
  180. self.closed = True
  181. def crypt(word, salt=None, iterations=None):
  182. """PBKDF2-based unix crypt(3) replacement.
  183. The number of iterations specified in the salt overrides the 'iterations'
  184. parameter.
  185. The effective hash length is 192 bits.
  186. """
  187. # Generate a (pseudo-)random salt if the user hasn't provided one.
  188. if salt is None:
  189. salt = _makesalt()
  190. # salt must be a string or the us-ascii subset of unicode
  191. if isinstance(salt, unicode):
  192. salt = salt.encode("us-ascii")
  193. if not isinstance(salt, str):
  194. raise TypeError("salt must be a string")
  195. # word must be a string or unicode (in the latter case, we convert to UTF-8)
  196. if isinstance(word, unicode):
  197. word = word.encode("UTF-8")
  198. if not isinstance(word, str):
  199. raise TypeError("word must be a string or unicode")
  200. # Try to extract the real salt and iteration count from the salt
  201. if salt.startswith("$p5k2$"):
  202. (iterations, salt, dummy) = salt.split("$")[2:5]
  203. if iterations == "":
  204. iterations = 400
  205. else:
  206. converted = int(iterations, 16)
  207. if iterations != "%x" % converted: # lowercase hex, minimum digits
  208. raise ValueError("Invalid salt")
  209. iterations = converted
  210. if not (iterations >= 1):
  211. raise ValueError("Invalid salt")
  212. # Make sure the salt matches the allowed character set
  213. allowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./"
  214. for ch in salt:
  215. if ch not in allowed:
  216. raise ValueError("Illegal character %r in salt" % (ch,))
  217. if iterations is None or iterations == 400:
  218. iterations = 400
  219. salt = "$p5k2$$" + salt
  220. else:
  221. salt = "$p5k2$%x$%s" % (iterations, salt)
  222. rawhash = PBKDF2(word, salt, iterations).read(24)
  223. return salt + "$" + b64encode(rawhash, "./")
  224. # Add crypt as a static method of the PBKDF2 class
  225. # This makes it easier to do "from PBKDF2 import PBKDF2" and still use
  226. # crypt.
  227. PBKDF2.crypt = staticmethod(crypt)
  228. def _makesalt():
  229. """Return a 48-bit pseudorandom salt for crypt().
  230. This function is not suitable for generating cryptographic secrets.
  231. """
  232. binarysalt = "".join([pack("@H", randint(0, 0xffff)) for i in range(3)])
  233. return b64encode(binarysalt, "./")
  234. def test_pbkdf2():
  235. """Module self-test"""
  236. from binascii import a2b_hex
  237. #
  238. # Test vectors from RFC 3962
  239. #
  240. # Test 1
  241. result = PBKDF2("password", "ATHENA.MIT.EDUraeburn", 1).read(16)
  242. expected = a2b_hex("cdedb5281bb2f801565a1122b2563515")
  243. if result != expected:
  244. raise RuntimeError("self-test failed")
  245. # Test 2
  246. result = PBKDF2("password", "ATHENA.MIT.EDUraeburn", 1200).hexread(32)
  247. expected = ("5c08eb61fdf71e4e4ec3cf6ba1f5512b"
  248. "a7e52ddbc5e5142f708a31e2e62b1e13")
  249. if result != expected:
  250. raise RuntimeError("self-test failed")
  251. # Test 3
  252. result = PBKDF2("X"*64, "pass phrase equals block size", 1200).hexread(32)
  253. expected = ("139c30c0966bc32ba55fdbf212530ac9"
  254. "c5ec59f1a452f5cc9ad940fea0598ed1")
  255. if result != expected:
  256. raise RuntimeError("self-test failed")
  257. # Test 4
  258. result = PBKDF2("X"*65, "pass phrase exceeds block size", 1200).hexread(32)
  259. expected = ("9ccad6d468770cd51b10e6a68721be61"
  260. "1a8b4d282601db3b36be9246915ec82a")
  261. if result != expected:
  262. raise RuntimeError("self-test failed")
  263. #
  264. # Other test vectors
  265. #
  266. # Chunked read
  267. f = PBKDF2("kickstart", "workbench", 256)
  268. result = f.read(17)
  269. result += f.read(17)
  270. result += f.read(1)
  271. result += f.read(2)
  272. result += f.read(3)
  273. expected = PBKDF2("kickstart", "workbench", 256).read(40)
  274. if result != expected:
  275. raise RuntimeError("self-test failed")
  276. #
  277. # crypt() test vectors
  278. #
  279. # crypt 1
  280. result = crypt("cloadm", "exec")
  281. expected = '$p5k2$$exec$r1EWMCMk7Rlv3L/RNcFXviDefYa0hlql'
  282. if result != expected:
  283. raise RuntimeError("self-test failed")
  284. # crypt 2
  285. result = crypt("gnu", '$p5k2$c$u9HvcT4d$.....')
  286. expected = '$p5k2$c$u9HvcT4d$Sd1gwSVCLZYAuqZ25piRnbBEoAesaa/g'
  287. if result != expected:
  288. raise RuntimeError("self-test failed")
  289. # crypt 3
  290. result = crypt("dcl", "tUsch7fU", iterations=13)
  291. expected = "$p5k2$d$tUsch7fU$nqDkaxMDOFBeJsTSfABsyn.PYUXilHwL"
  292. if result != expected:
  293. raise RuntimeError("self-test failed")
  294. # crypt 4 (unicode)
  295. result = crypt(u'\u0399\u03c9\u03b1\u03bd\u03bd\u03b7\u03c2',
  296. '$p5k2$$KosHgqNo$9mjN8gqjt02hDoP0c2J0ABtLIwtot8cQ')
  297. expected = '$p5k2$$KosHgqNo$9mjN8gqjt02hDoP0c2J0ABtLIwtot8cQ'
  298. if result != expected:
  299. raise RuntimeError("self-test failed")
  300. if __name__ == '__main__':
  301. test_pbkdf2()
  302. # vim:set ts=4 sw=4 sts=4 expandtab: