hmac.py 912 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. """HMAC -- keyed hashing for message authentication, as described in rfc2104."""
  2. import sha
  3. BLEN = 64
  4. ipad = map(ord, "\x36" * BLEN)
  5. opad = map(ord, "\x5C" * BLEN)
  6. def hash(s):
  7. return sha.new(s).digest()
  8. def hmac(key, text):
  9. """Given strings 'key' and 'text', produce an HMAC digest."""
  10. # If the key is longer than BLEN, hash it first. The result must
  11. # be less than BLEN bytes. This depends on the hash function used;
  12. # sha1 and md5 are both OK.
  13. l = len(key)
  14. if l > BLEN:
  15. key = hash(key)
  16. l = len(key)
  17. # Pad the key with zeros to BLEN bytes.
  18. key = key + '\0' * (BLEN - l)
  19. key = map(ord, key)
  20. # Now compute the HMAC.
  21. l = map(lambda x, y: x ^ y, key, ipad)
  22. s = reduce(lambda x, y: x + chr(y), l, '')
  23. s = hash(s + text)
  24. l = map(lambda x, y: x ^ y, key, opad)
  25. t = reduce(lambda x, y: x + chr(y), l, '')
  26. s = hash(t + s)
  27. return s