crypto.py 3.1 KB

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