crypto.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. """
  2. Django's standard crypto functions and utilities.
  3. """
  4. import hashlib
  5. import hmac
  6. import secrets
  7. from django.conf import settings
  8. from django.utils.encoding import force_bytes
  9. class InvalidAlgorithm(ValueError):
  10. """Algorithm is not supported by hashlib."""
  11. pass
  12. def salted_hmac(key_salt, value, secret=None, *, algorithm="sha1"):
  13. """
  14. Return the HMAC of 'value', using a key generated from key_salt and a
  15. secret (which defaults to settings.SECRET_KEY). Default algorithm is SHA1,
  16. but any algorithm name supported by hashlib can be passed.
  17. A different key_salt should be passed in for every application of HMAC.
  18. """
  19. if secret is None:
  20. secret = settings.SECRET_KEY
  21. key_salt = force_bytes(key_salt)
  22. secret = force_bytes(secret)
  23. try:
  24. hasher = getattr(hashlib, algorithm)
  25. except AttributeError as e:
  26. raise InvalidAlgorithm(
  27. "%r is not an algorithm accepted by the hashlib module." % algorithm
  28. ) from e
  29. # We need to generate a derived key from our base key. We can do this by
  30. # passing the key_salt and our base key through a pseudo-random function.
  31. key = hasher(key_salt + secret).digest()
  32. # If len(key_salt + secret) > block size of the hash algorithm, the above
  33. # line is redundant and could be replaced by key = key_salt + secret, since
  34. # the hmac module does the same thing for keys longer than the block size.
  35. # However, we need to ensure that we *always* do this.
  36. return hmac.new(key, msg=force_bytes(value), digestmod=hasher)
  37. RANDOM_STRING_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  38. def get_random_string(length, allowed_chars=RANDOM_STRING_CHARS):
  39. """
  40. Return a securely generated random string.
  41. The bit length of the returned value can be calculated with the formula:
  42. log_2(len(allowed_chars)^length)
  43. For example, with default `allowed_chars` (26+26+10), this gives:
  44. * length: 12, bit length =~ 71 bits
  45. * length: 22, bit length =~ 131 bits
  46. """
  47. return "".join(secrets.choice(allowed_chars) for i in range(length))
  48. def constant_time_compare(val1, val2):
  49. """Return True if the two strings are equal, False otherwise."""
  50. return secrets.compare_digest(force_bytes(val1), force_bytes(val2))
  51. def pbkdf2(password, salt, iterations, dklen=0, digest=None):
  52. """Return the hash of password using pbkdf2."""
  53. if digest is None:
  54. digest = hashlib.sha256
  55. dklen = dklen or None
  56. password = force_bytes(password)
  57. salt = force_bytes(salt)
  58. return hashlib.pbkdf2_hmac(digest().name, password, salt, iterations, dklen)