crypto.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. """
  2. Django's standard crypto functions and utilities.
  3. """
  4. from __future__ import unicode_literals
  5. import hmac
  6. import struct
  7. import hashlib
  8. import binascii
  9. import time
  10. # Use the system PRNG if possible
  11. import random
  12. try:
  13. random = random.SystemRandom()
  14. using_sysrandom = True
  15. except NotImplementedError:
  16. import warnings
  17. warnings.warn('A secure pseudo-random number generator is not available '
  18. 'on your system. Falling back to Mersenne Twister.')
  19. using_sysrandom = False
  20. from django.conf import settings
  21. from django.utils.encoding import force_bytes
  22. from django.utils import six
  23. from django.utils.six.moves import xrange
  24. def salted_hmac(key_salt, value, secret=None):
  25. """
  26. Returns the HMAC-SHA1 of 'value', using a key generated from key_salt and a
  27. secret (which defaults to settings.SECRET_KEY).
  28. A different key_salt should be passed in for every application of HMAC.
  29. """
  30. if secret is None:
  31. secret = settings.SECRET_KEY
  32. key_salt = force_bytes(key_salt)
  33. secret = force_bytes(secret)
  34. # We need to generate a derived key from our base key. We can do this by
  35. # passing the key_salt and our base key through a pseudo-random function and
  36. # SHA1 works nicely.
  37. key = hashlib.sha1(key_salt + secret).digest()
  38. # If len(key_salt + secret) > sha_constructor().block_size, the above
  39. # line is redundant and could be replaced by key = key_salt + secret, since
  40. # the hmac module does the same thing for keys longer than the block size.
  41. # However, we need to ensure that we *always* do this.
  42. return hmac.new(key, msg=force_bytes(value), digestmod=hashlib.sha1)
  43. def get_random_string(length=12,
  44. allowed_chars='abcdefghijklmnopqrstuvwxyz'
  45. 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
  46. """
  47. Returns a securely generated random string.
  48. The default length of 12 with the a-z, A-Z, 0-9 character set returns
  49. a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
  50. """
  51. if not using_sysrandom:
  52. # This is ugly, and a hack, but it makes things better than
  53. # the alternative of predictability. This re-seeds the PRNG
  54. # using a value that is hard for an attacker to predict, every
  55. # time a random string is required. This may change the
  56. # properties of the chosen random sequence slightly, but this
  57. # is better than absolute predictability.
  58. random.seed(
  59. hashlib.sha256(
  60. ("%s%s%s" % (
  61. random.getstate(),
  62. time.time(),
  63. settings.SECRET_KEY)).encode('utf-8')
  64. ).digest())
  65. return ''.join(random.choice(allowed_chars) for i in range(length))
  66. def constant_time_compare(val1, val2):
  67. """
  68. Returns True if the two strings are equal, False otherwise.
  69. The time taken is independent of the number of characters that match.
  70. For the sake of simplicity, this function executes in constant time only
  71. when the two strings have the same length. It short-circuits when they
  72. have different lengths. Since Django only uses it to compare hashes of
  73. known expected length, this is acceptable.
  74. """
  75. if len(val1) != len(val2):
  76. return False
  77. result = 0
  78. if six.PY3 and isinstance(val1, bytes) and isinstance(val2, bytes):
  79. for x, y in zip(val1, val2):
  80. result |= x ^ y
  81. else:
  82. for x, y in zip(val1, val2):
  83. result |= ord(x) ^ ord(y)
  84. return result == 0
  85. def _bin_to_long(x):
  86. """
  87. Convert a binary string into a long integer
  88. This is a clever optimization for fast xor vector math
  89. """
  90. return int(binascii.hexlify(x), 16)
  91. def _long_to_bin(x, hex_format_string):
  92. """
  93. Convert a long integer into a binary string.
  94. hex_format_string is like "%020x" for padding 10 characters.
  95. """
  96. return binascii.unhexlify((hex_format_string % x).encode('ascii'))
  97. def pbkdf2(password, salt, iterations, dklen=0, digest=None):
  98. """
  99. Implements PBKDF2 as defined in RFC 2898, section 5.2
  100. HMAC+SHA256 is used as the default pseudo random function.
  101. As of 2011, 10,000 iterations was the recommended default which
  102. took 100ms on a 2.2Ghz Core 2 Duo. This is probably the bare
  103. minimum for security given 1000 iterations was recommended in
  104. 2001. This code is very well optimized for CPython and is only
  105. four times slower than openssl's implementation. Look in
  106. django.contrib.auth.hashers for the present default.
  107. """
  108. assert iterations > 0
  109. if not digest:
  110. digest = hashlib.sha256
  111. password = force_bytes(password)
  112. salt = force_bytes(salt)
  113. hlen = digest().digest_size
  114. if not dklen:
  115. dklen = hlen
  116. if dklen > (2 ** 32 - 1) * hlen:
  117. raise OverflowError('dklen too big')
  118. l = -(-dklen // hlen)
  119. r = dklen - (l - 1) * hlen
  120. hex_format_string = "%%0%ix" % (hlen * 2)
  121. inner, outer = digest(), digest()
  122. if len(password) > inner.block_size:
  123. password = digest(password).digest()
  124. password += b'\x00' * (inner.block_size - len(password))
  125. inner.update(password.translate(hmac.trans_36))
  126. outer.update(password.translate(hmac.trans_5C))
  127. def F(i):
  128. u = salt + struct.pack(b'>I', i)
  129. result = 0
  130. for j in xrange(int(iterations)):
  131. dig1, dig2 = inner.copy(), outer.copy()
  132. dig1.update(u)
  133. dig2.update(dig1.digest())
  134. u = dig2.digest()
  135. result ^= _bin_to_long(u)
  136. return _long_to_bin(result, hex_format_string)
  137. T = [F(x) for x in range(1, l)]
  138. return b''.join(T) + F(l)[:r]