SHA-based encryption function in Python

Bryan Olson bryanjugglercryptographer at yahoo.com
Wed Apr 24 16:17:34 EDT 2002


Paul Rubin wrote:

> Yes, but this encryption module is supposed to work in 1.5.2.
> 
> Also, the 2.2 hmac module is written in python and looks pretty slow.
[...]
> And it actually might be faster to use two separate hash-based auth
> keys than deal with the fancy HMAC padding, if a simple double hash
> has some vulnerabilities.


HMAC's is only a small additive constant slower than the hash function.  
For messages more than a few blocks long, it's not significant.  The
extra padding and additional hash function calls only deal with two blocks.

Below is single-call HMAC in Python.


| import sha
| import md5
| import string
|
|
| def xor_strings(s1, s2):
|     """Pass two strings of the same length; returns their
|     bit-wise exclusive or.
|     """
|     char_list = map(lambda x, y: chr(ord(x) ^ ord(y)), s1, s2)
|     return string.join(char_list, "")
|
| def hmac(message, key, hash_function, block_size):
|     """Generic HMAC, as per RFC 2104.  The hash function must
|     follow the usual Python new..update..digest interface.
|     """
|     if len(key) > block_size:
|         key = hash_function.new(key).digest()
|     ipad = chr(0x36) * block_size
|     opad = chr(0x5C) * block_size
|     key = key + chr(0) * (block_size - len(key))
|     hash1 = hash_function.new(xor_strings(key, ipad))
|     hash1.update(message)
|     hash2 = hash_function.new(xor_strings(key, opad))
|     hash2.update(hash1.digest())
|     return hash2.digest()
|
| def hmac_sha1(message, key):
|     return hmac(message, key, sha, 64)
|
| def hmac_md5(message, key):
|     return hmac(message, key, md5, 64)
|



More information about the Python-list mailing list