"""HMAC (Keyed-Hashing for Message Authentication) Python module.Implements the HMAC algorithm as described by RFC 2104."""import warnings as _warningsfrom _operator import _compare_digest as compare_digesttry:import _hashlib as _hashopensslexcept ImportError:_hashopenssl = None_openssl_md_meths = Noneelse:_openssl_md_meths = frozenset(_hashopenssl.openssl_md_meth_names)import hashlib as _hashlibtrans_5C = bytes((x ^ 0x5C) for x in range(256))trans_36 = bytes((x ^ 0x36) for x in range(256))# The size of the digests returned by HMAC depends on the underlying# hashing module used. Use digest_size from the instance of HMAC instead.digest_size = Noneclass HMAC:"""RFC 2104 HMAC class. Also complies with RFC 4231.This supports the API for Cryptographic Hash Functions (PEP 247)."""blocksize = 64 # 512-bit HMAC; can be changed in subclasses.def __init__(self, key, msg = None, digestmod = None):"""Create a new HMAC object.key: key for the keyed hash object.msg: Initial input for the hash, if provided.digestmod: A module supporting PEP 247. *OR*A hashlib constructor returning a new hash object. *OR*A hash name suitable for hashlib.new().Defaults to hashlib.md5.Implicit default to hashlib.md5 is deprecated since Python3.4 and will be removed in Python 3.8.Note: key and msg must be a bytes or bytearray objects."""if not isinstance(key, (bytes, bytearray)):raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)if digestmod is None:_warnings.warn("HMAC() without an explicit digestmod argument ""is deprecated since Python 3.4, and will be removed ""in 3.8",DeprecationWarning, 2)digestmod = _hashlib.md5if callable(digestmod):self.digest_cons = digestmodelif isinstance(digestmod, str):self.digest_cons = lambda d=b'': _hashlib.new(digestmod, d)else:self.digest_cons = lambda d=b'': digestmod.new(d)self.outer = self.digest_cons()self.inner = self.digest_cons()self.digest_size = self.inner.digest_sizeif hasattr(self.inner, 'block_size'):blocksize = self.inner.block_sizeif blocksize < 16:_warnings.warn('block_size of %d seems too small; using our ''default of %d.' % (blocksize, self.blocksize),RuntimeWarning, 2)blocksize = self.blocksizeelse:_warnings.warn('No block_size attribute on given digest object; ''Assuming %d.' % (self.blocksize),RuntimeWarning, 2)blocksize = self.blocksize# self.blocksize is the default blocksize. self.block_size is# effective block size as well as the public API attribute.self.block_size = blocksizeif len(key) > blocksize:key = self.digest_cons(key).digest()key = key.ljust(blocksize, b'0円')self.outer.update(key.translate(trans_5C))self.inner.update(key.translate(trans_36))if msg is not None:self.update(msg)@propertydef name(self):return "hmac-" + self.inner.namedef update(self, msg):"""Update this hashing object with the string msg."""self.inner.update(msg)def copy(self):"""Return a separate copy of this hashing object.An update to this copy won't affect the original object."""# Call __new__ directly to avoid the expensive __init__.other = self.__class__.__new__(self.__class__)other.digest_cons = self.digest_consother.digest_size = self.digest_sizeother.inner = self.inner.copy()other.outer = self.outer.copy()return otherdef _current(self):"""Return a hash object for the current state.To be used only internally with digest() and hexdigest()."""h = self.outer.copy()h.update(self.inner.digest())return hdef digest(self):"""Return the hash value of this hashing object.This returns a string containing 8-bit data. The object isnot altered in any way by this function; you can continueupdating the object after calling this function."""h = self._current()return h.digest()def hexdigest(self):"""Like digest(), but returns a string of hexadecimal digits instead."""h = self._current()return h.hexdigest()def new(key, msg = None, digestmod = None):"""Create a new hashing object and return it.key: The starting key for the hash.msg: if available, will immediately be hashed into the object's startingstate.You can now feed arbitrary strings into the object using its update()method, and can ask for the hash value at any time by calling its digest()method."""return HMAC(key, msg, digestmod)def digest(key, msg, digest):"""Fast inline implementation of HMACkey: key for the keyed hash object.msg: input messagedigest: A hash name suitable for hashlib.new() for best performance. *OR*A hashlib constructor returning a new hash object. *OR*A module supporting PEP 247.Note: key and msg must be a bytes or bytearray objects."""if (_hashopenssl is not None andisinstance(digest, str) and digest in _openssl_md_meths):return _hashopenssl.hmac_digest(key, msg, digest)if callable(digest):digest_cons = digestelif isinstance(digest, str):digest_cons = lambda d=b'': _hashlib.new(digest, d)else:digest_cons = lambda d=b'': digest.new(d)inner = digest_cons()outer = digest_cons()blocksize = getattr(inner, 'block_size', 64)if len(key) > blocksize:key = digest_cons(key).digest()key = key + b'\x00' * (blocksize - len(key))inner.update(key.translate(trans_36))outer.update(key.translate(trans_5C))inner.update(msg)outer.update(inner.digest())return outer.digest()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。