Speed HMAC.copy() by installing a secret backdoor argument to

HMAC.__init__().  Adapted from SF patch 895445 "hmac.HMAC.copy() speedup"
by Trevor Perrin, who reported that this approach increased throughput
of his hmac-intensive app by 30%.
This commit is contained in:
Tim Peters 2004-03-20 20:11:29 +00:00
parent 1515fc2a01
commit 934d31b1d3
1 changed files with 11 additions and 1 deletions

View File

@ -12,6 +12,11 @@ def _strxor(s1, s2):
# hashing module used. # hashing module used.
digest_size = None digest_size = None
# A unique object passed by HMAC.copy() to the HMAC constructor, in order
# that the latter return very quickly. HMAC("") in contrast is quite
# expensive.
_secret_backdoor_key = []
class HMAC: class HMAC:
"""RFC2104 HMAC class. """RFC2104 HMAC class.
@ -25,6 +30,10 @@ class HMAC:
msg: Initial input for the hash, if provided. msg: Initial input for the hash, if provided.
digestmod: A module supporting PEP 247. Defaults to the md5 module. digestmod: A module supporting PEP 247. Defaults to the md5 module.
""" """
if key is _secret_backdoor_key: # cheap
return
if digestmod is None: if digestmod is None:
import md5 import md5
digestmod = md5 digestmod = md5
@ -60,8 +69,9 @@ class HMAC:
An update to this copy won't affect the original object. An update to this copy won't affect the original object.
""" """
other = HMAC("") other = HMAC(_secret_backdoor_key)
other.digestmod = self.digestmod other.digestmod = self.digestmod
other.digest_size = self.digest_size
other.inner = self.inner.copy() other.inner = self.inner.copy()
other.outer = self.outer.copy() other.outer = self.outer.copy()
return other return other