Esto se debe a hmac
utiliza la proporcionan key
para generar un salt y hacer el hash más fuerte, mientras que hashlib
sólo hashes el mensaje proporcionado.
Al observar el módulo de source codehmac
, encontrará la forma de lograr el mismo comportamiento que hmac
utilizando el módulo hashlib
, aquí el algoritmo utilizado (que no es el original, i despojado algunas comprobaciones que tienen sólo la parte interesante) :
import hashlib
MESSAGE = "msg"
KEY = "key"
trans_5C = "".join ([chr (x^0x5C) for x in xrange(256)])
trans_36 = "".join ([chr (x^0x36) for x in xrange(256)])
outer = hashlib.sha256()
inner = hashlib.sha256()
KEY = KEY + chr(0) * (inner.block_size - len(KEY))
outer.update(KEY.translate(trans_5C))
inner.update(KEY.translate(trans_36))
inner.update(MESSAGE)
outer.update(inner.digest())
result = outer.hexdigest()
print result # prints 2d93cbc1be167bcb1637a4a23cbff01a7878f0c50ee833954ea5221bb1b8c628
La misma directamente utilizando hmac
:
import hashlib
import hmac
result = hmac.new(KEY, MESSAGE, hashlib.sha256).hexdigest()
print result # prints 2d93cbc1be167bcb1637a4a23cbff01a7878f0c50ee833954ea5221bb1b8c628
Así que cuando se utiliza hmac
, no sólo se tiene Es el mensaje dado usando el algoritmo hash especificado, también usa la clave para complejizar el hash.
Su respuesta está aquí http://stackoverflow.com/questions/2836100/what-is-the-difference-between-a-hash-and-mac-message-authentication-code – Kracekumar
ok gracias. er dj –