Overview

PKCS#5 password-based key derivation function 2 (PBKDF2)

This is a backport of hashlib.pbkdf2_hmac for Python 2.6 to 2.7. The implementation comes with a pure Python implementation and a C module that depends on OpenSSL. The C code does not wrap PKCS5_PBKDF2_HMAC as its implementation is suboptimal.

Usage

>>> from backports.pbkdf2 import pbkdf2_hmac, compare_digest
>>> dkey = pbkdf2_hmac('sha1', passwordbytes, saltbytes, iterations=100000)
>>> compare_digest(dkey, originalkey)
True

pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None)

hash_name
name of the digest algorithm as string
password
password as bytes, bytearray or bytes-like object (*)
salt
salt as bytes, bytearray or bytes-like object (*). The salt should be generated with a CPRNG like os.urandom(). You should never use random.random(). About 16 bytes seem to be a good choice.
iterations
number of rounds, 100,000 rounds of SHA-1 take about 30ms on a modern CPU.
dklen
length of the derived key (defaults to digest_size)
returns
derived key as bytes

(*) bytearray and bytes-like objects are not supported on Python 2.6

Platforms

  • Python 2.6 to 3.3
  • OpenSSL 0.9.8 to 1.0.1
  • Linux
  • Solaris
  • Mac OS X
  • Windows (no C acceleration support yet)

Benchmarks

Benchmark of PBKDF2_HMAC() with SHA-1, 16 bytes of salt and default dklen (=20) in relation to password length and rounds on Python 3.3 and 2.7 (Linux AMD64, Intel i7-2860QM @ 2.50GHz). Times are in miliseconds (best of 10 runs for 50k rounds, best of 3 runs for 100k rounds).

Python 3.3 (50k rounds)

password length 10 100 500 1000
backports.pbkdf2 C 34.2 35.6 35.6 35.4
backports.pbkdf2 Py 94.7 96.3 98.0 98.2
Django pbkdf2 1.5.5 117.2 123.6 125.2 126.2
Django pbkdf2 1.5.4 216.5 271.9 304.0 338.4
pbkdf2_ctypes 0.99.3 63.6 82.0 117.7 157.6
pbkdf2.py 1.3 566.0 612.5 637.5 694.2
PyCrypto 2.6.1 676.4 940.2 955.5 1015.3

Python 3.3 (100k rounds)

password length 10 100 500 1000
backports.pbkdf2 C 64.5 66.8 68.8 66.8
backports.pbkdf2 Py 187.6 190.8 193.4 195.2
Django pbkdf2 1.5.5 287.5 275.4 268.8 269.1
pbkdf2_ctypes 0.99.3 121.7 162.3 225.2 316.6
pbkdf2.py 1.3 1323.2 1299.5 1380.2 1450.4
PyCrypto 2.6.1 1527.8 2047.3 2170.4 2085.1

Python 2.7 (50k rounds)

password length 10 100 500 1000
backports.pbkdf2 C 30.5 32.3 32.5 33.2
backports.pbkdf2 Py 134.2 136.3 139.6 140.6
Django pbkdf2 1.5.5 144.7 145.5 150.8 148.2
pbkdf2_ctypes 0.99.3 60.9 68.4 101.3 150.5
pbkdf2.py 1.3 759.6 798.9 856.1 896.9
PyCrypto 2.6.1 659.4 914.2 932.2 970.7