Python – pbkdf2_hmac takes a long time in Django

pbkdf2_hmac takes a long time in Django… here is a solution to the problem.

pbkdf2_hmac takes a long time in Django

I’m doing some analysis of the django rest framework API and using cProfile-based analytics middleware, I get the following output:

Sat Mar  2 23:55:13 2019    /var/folders/jr/something
41224 function calls (40529 primitive calls) in 0.182 seconds

Ordered by: internal time

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    1    0.124    0.124    0.124    0.124 {built-in method _hashlib.pbkdf2_hmac}
   11    0.006    0.001    0.007    0.001 {method 'execute' of 'psycopg2.extensions.cursor' objects}
  252    0.003    0.000    0.003    0.000 {built-in method posix.stat}
   11    0.002    0.000    0.009    0.001 /Users/my-local-user/.pyenv/versions/3.7.0/lib/python3.7/

Based on this, calling .pbkdf2_hmac once _hashlib is almost 70% of the total execution time of my single request!

I haven’t found a lot of information about this other than it’s used in openSSL – but I’m running it locally without SSL.

Why should I spend so much time on a cryptographic function for a simple API request?


PBKDF2 is designed to run slowly. Its purpose is difficult to calculate, so brute force takes a lot of time.

If you want to get analytical data without this slowness, you can turn down the number of iterations used for this calculation. See Password management in Django for more details. Remember to turn it down only for testing and analysis, as running it with a low number of iterations in production is a security risk!

Related Problems and Solutions