PageRenderTime 55ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/hmac.py

https://gitlab.com/unofficial-mirrors/cpython
Python | 144 lines | 101 code | 10 blank | 33 comment | 6 complexity | a275f336dee2f94e4735e5946e68f474 MD5 | raw file
  1. """HMAC (Keyed-Hashing for Message Authentication) Python module.
  2. Implements the HMAC algorithm as described by RFC 2104.
  3. """
  4. import warnings as _warnings
  5. from _operator import _compare_digest as compare_digest
  6. import hashlib as _hashlib
  7. trans_5C = bytes((x ^ 0x5C) for x in range(256))
  8. trans_36 = bytes((x ^ 0x36) for x in range(256))
  9. # The size of the digests returned by HMAC depends on the underlying
  10. # hashing module used. Use digest_size from the instance of HMAC instead.
  11. digest_size = None
  12. class HMAC:
  13. """RFC 2104 HMAC class. Also complies with RFC 4231.
  14. This supports the API for Cryptographic Hash Functions (PEP 247).
  15. """
  16. blocksize = 64 # 512-bit HMAC; can be changed in subclasses.
  17. def __init__(self, key, msg = None, digestmod = None):
  18. """Create a new HMAC object.
  19. key: key for the keyed hash object.
  20. msg: Initial input for the hash, if provided.
  21. digestmod: A module supporting PEP 247. *OR*
  22. A hashlib constructor returning a new hash object. *OR*
  23. A hash name suitable for hashlib.new().
  24. Defaults to hashlib.md5.
  25. Implicit default to hashlib.md5 is deprecated and will be
  26. removed in Python 3.6.
  27. Note: key and msg must be a bytes or bytearray objects.
  28. """
  29. if not isinstance(key, (bytes, bytearray)):
  30. raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)
  31. if digestmod is None:
  32. _warnings.warn("HMAC() without an explicit digestmod argument "
  33. "is deprecated.", PendingDeprecationWarning, 2)
  34. digestmod = _hashlib.md5
  35. if callable(digestmod):
  36. self.digest_cons = digestmod
  37. elif isinstance(digestmod, str):
  38. self.digest_cons = lambda d=b'': _hashlib.new(digestmod, d)
  39. else:
  40. self.digest_cons = lambda d=b'': digestmod.new(d)
  41. self.outer = self.digest_cons()
  42. self.inner = self.digest_cons()
  43. self.digest_size = self.inner.digest_size
  44. if hasattr(self.inner, 'block_size'):
  45. blocksize = self.inner.block_size
  46. if blocksize < 16:
  47. _warnings.warn('block_size of %d seems too small; using our '
  48. 'default of %d.' % (blocksize, self.blocksize),
  49. RuntimeWarning, 2)
  50. blocksize = self.blocksize
  51. else:
  52. _warnings.warn('No block_size attribute on given digest object; '
  53. 'Assuming %d.' % (self.blocksize),
  54. RuntimeWarning, 2)
  55. blocksize = self.blocksize
  56. # self.blocksize is the default blocksize. self.block_size is
  57. # effective block size as well as the public API attribute.
  58. self.block_size = blocksize
  59. if len(key) > blocksize:
  60. key = self.digest_cons(key).digest()
  61. key = key.ljust(blocksize, b'\0')
  62. self.outer.update(key.translate(trans_5C))
  63. self.inner.update(key.translate(trans_36))
  64. if msg is not None:
  65. self.update(msg)
  66. @property
  67. def name(self):
  68. return "hmac-" + self.inner.name
  69. def update(self, msg):
  70. """Update this hashing object with the string msg.
  71. """
  72. self.inner.update(msg)
  73. def copy(self):
  74. """Return a separate copy of this hashing object.
  75. An update to this copy won't affect the original object.
  76. """
  77. # Call __new__ directly to avoid the expensive __init__.
  78. other = self.__class__.__new__(self.__class__)
  79. other.digest_cons = self.digest_cons
  80. other.digest_size = self.digest_size
  81. other.inner = self.inner.copy()
  82. other.outer = self.outer.copy()
  83. return other
  84. def _current(self):
  85. """Return a hash object for the current state.
  86. To be used only internally with digest() and hexdigest().
  87. """
  88. h = self.outer.copy()
  89. h.update(self.inner.digest())
  90. return h
  91. def digest(self):
  92. """Return the hash value of this hashing object.
  93. This returns a string containing 8-bit data. The object is
  94. not altered in any way by this function; you can continue
  95. updating the object after calling this function.
  96. """
  97. h = self._current()
  98. return h.digest()
  99. def hexdigest(self):
  100. """Like digest(), but returns a string of hexadecimal digits instead.
  101. """
  102. h = self._current()
  103. return h.hexdigest()
  104. def new(key, msg = None, digestmod = None):
  105. """Create a new hashing object and return it.
  106. key: The starting key for the hash.
  107. msg: if available, will immediately be hashed into the object's starting
  108. state.
  109. You can now feed arbitrary strings into the object using its update()
  110. method, and can ask for the hash value at any time by calling its digest()
  111. method.
  112. """
  113. return HMAC(key, msg, digestmod)