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 6.7 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. """
  2. Django's standard crypto functions and utilities.
  3. """
  4. from __future__ import unicode_literals
  5. import binascii
  6. import hashlib
  7. import hmac
  8. import random
  9. import struct
  10. import time
  11. from django.conf import settings
  12. from django.utils import six
  13. from django.utils.encoding import force_bytes
  14. from django.utils.six.moves import range
  15. # Use the system PRNG if possible
  16. try:
  17. random = random.SystemRandom()
  18. using_sysrandom = True
  19. except NotImplementedError:
  20. import warnings
  21. warnings.warn('A secure pseudo-random number generator is not available '
  22. 'on your system. Falling back to Mersenne Twister.')
  23. using_sysrandom = False
  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. if hasattr(hmac, "compare_digest"):
  67. # Prefer the stdlib implementation, when available.
  68. def constant_time_compare(val1, val2):
  69. return hmac.compare_digest(force_bytes(val1), force_bytes(val2))
  70. else:
  71. def constant_time_compare(val1, val2):
  72. """
  73. Returns True if the two strings are equal, False otherwise.
  74. The time taken is independent of the number of characters that match.
  75. For the sake of simplicity, this function executes in constant time only
  76. when the two strings have the same length. It short-circuits when they
  77. have different lengths. Since Django only uses it to compare hashes of
  78. known expected length, this is acceptable.
  79. """
  80. if len(val1) != len(val2):
  81. return False
  82. result = 0
  83. if six.PY3 and isinstance(val1, bytes) and isinstance(val2, bytes):
  84. for x, y in zip(val1, val2):
  85. result |= x ^ y
  86. else:
  87. for x, y in zip(val1, val2):
  88. result |= ord(x) ^ ord(y)
  89. return result == 0
  90. def _bin_to_long(x):
  91. """
  92. Convert a binary string into a long integer
  93. This is a clever optimization for fast xor vector math
  94. """
  95. return int(binascii.hexlify(x), 16)
  96. def _long_to_bin(x, hex_format_string):
  97. """
  98. Convert a long integer into a binary string.
  99. hex_format_string is like "%020x" for padding 10 characters.
  100. """
  101. return binascii.unhexlify((hex_format_string % x).encode('ascii'))
  102. if hasattr(hashlib, "pbkdf2_hmac"):
  103. def pbkdf2(password, salt, iterations, dklen=0, digest=None):
  104. """
  105. Implements PBKDF2 with the same API as Django's existing
  106. implementation, using the stdlib.
  107. This is used in Python 2.7.8+ and 3.4+.
  108. """
  109. if digest is None:
  110. digest = hashlib.sha256
  111. if not dklen:
  112. dklen = None
  113. password = force_bytes(password)
  114. salt = force_bytes(salt)
  115. return hashlib.pbkdf2_hmac(
  116. digest().name, password, salt, iterations, dklen)
  117. else:
  118. def pbkdf2(password, salt, iterations, dklen=0, digest=None):
  119. """
  120. Implements PBKDF2 as defined in RFC 2898, section 5.2
  121. HMAC+SHA256 is used as the default pseudo random function.
  122. As of 2014, 100,000 iterations was the recommended default which took
  123. 100ms on a 2.7Ghz Intel i7 with an optimized implementation. This is
  124. probably the bare minimum for security given 1000 iterations was
  125. recommended in 2001. This code is very well optimized for CPython and
  126. is about five times slower than OpenSSL's implementation. Look in
  127. django.contrib.auth.hashers for the present default, it is lower than
  128. the recommended 100,000 because of the performance difference between
  129. this and an optimized implementation.
  130. """
  131. assert iterations > 0
  132. if not digest:
  133. digest = hashlib.sha256
  134. password = force_bytes(password)
  135. salt = force_bytes(salt)
  136. hlen = digest().digest_size
  137. if not dklen:
  138. dklen = hlen
  139. if dklen > (2 ** 32 - 1) * hlen:
  140. raise OverflowError('dklen too big')
  141. l = -(-dklen // hlen)
  142. r = dklen - (l - 1) * hlen
  143. hex_format_string = "%%0%ix" % (hlen * 2)
  144. inner, outer = digest(), digest()
  145. if len(password) > inner.block_size:
  146. password = digest(password).digest()
  147. password += b'\x00' * (inner.block_size - len(password))
  148. inner.update(password.translate(hmac.trans_36))
  149. outer.update(password.translate(hmac.trans_5C))
  150. def F(i):
  151. u = salt + struct.pack(b'>I', i)
  152. result = 0
  153. for j in range(int(iterations)):
  154. dig1, dig2 = inner.copy(), outer.copy()
  155. dig1.update(u)
  156. dig2.update(dig1.digest())
  157. u = dig2.digest()
  158. result ^= _bin_to_long(u)
  159. return _long_to_bin(result, hex_format_string)
  160. T = [F(x) for x in range(1, l)]
  161. return b''.join(T) + F(l)[:r]