Development of an internal social media platform with personalised dashboards for students
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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. if not dklen:
  67. dklen = None
  68. password = force_bytes(password)
  69. salt = force_bytes(salt)
  70. return hashlib.pbkdf2_hmac(digest().name, password, salt, iterations, dklen)