You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

crypto.py 3.0KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. """
  2. Django's standard crypto functions and utilities.
  3. """
  4. import hashlib
  5. import hmac
  6. import random
  7. import time
  8. from django.conf import settings
  9. from django.utils.encoding import force_bytes
  10. # Use the system PRNG if possible
  11. try:
  12. random = random.SystemRandom()
  13. using_sysrandom = True
  14. except NotImplementedError:
  15. import warnings
  16. warnings.warn('A secure pseudo-random number generator is not available '
  17. 'on your system. Falling back to Mersenne Twister.')
  18. using_sysrandom = False
  19. def salted_hmac(key_salt, value, secret=None):
  20. """
  21. Return the HMAC-SHA1 of 'value', using a key generated from key_salt and a
  22. secret (which defaults to settings.SECRET_KEY).
  23. A different key_salt should be passed in for every application of HMAC.
  24. """
  25. if secret is None:
  26. secret = settings.SECRET_KEY
  27. key_salt = force_bytes(key_salt)
  28. secret = force_bytes(secret)
  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 and
  31. # SHA1 works nicely.
  32. key = hashlib.sha1(key_salt + secret).digest()
  33. # If len(key_salt + secret) > sha_constructor().block_size, the above
  34. # line is redundant and could be replaced by key = key_salt + secret, since
  35. # the hmac module does the same thing for keys longer than the block size.
  36. # However, we need to ensure that we *always* do this.
  37. return hmac.new(key, msg=force_bytes(value), digestmod=hashlib.sha1)
  38. def get_random_string(length=12,
  39. allowed_chars='abcdefghijklmnopqrstuvwxyz'
  40. 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
  41. """
  42. Return a securely generated random string.
  43. The default length of 12 with the a-z, A-Z, 0-9 character set returns
  44. a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
  45. """
  46. if not using_sysrandom:
  47. # This is ugly, and a hack, but it makes things better than
  48. # the alternative of predictability. This re-seeds the PRNG
  49. # using a value that is hard for an attacker to predict, every
  50. # time a random string is required. This may change the
  51. # properties of the chosen random sequence slightly, but this
  52. # is better than absolute predictability.
  53. random.seed(
  54. hashlib.sha256(
  55. ('%s%s%s' % (random.getstate(), time.time(), settings.SECRET_KEY)).encode()
  56. ).digest()
  57. )
  58. return ''.join(random.choice(allowed_chars) for i in range(length))
  59. def constant_time_compare(val1, val2):
  60. """Return True if the two strings are equal, False otherwise."""
  61. return hmac.compare_digest(force_bytes(val1), force_bytes(val2))
  62. def pbkdf2(password, salt, iterations, dklen=0, digest=None):
  63. """Return the hash of password using pbkdf2."""
  64. if digest is None:
  65. digest = hashlib.sha256
  66. dklen = dklen or None
  67. password = force_bytes(password)
  68. salt = force_bytes(salt)
  69. return hashlib.pbkdf2_hmac(digest().name, password, salt, iterations, dklen)