Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the hashlib and hmac are generating different hash values?

In Python 2.7,

my = "my"
key = "key"
print(hashlib.sha256(my + key).hexdigest())
print(hmac.new(my, key, hashlib.sha256).hexdigest())

output,

5e50f405ace6cbdf17379f4b9f2b0c9f4144c5e380ea0b9298cb02ebd8ffe511
15a55993a27e0de7a4c4daa67a7c219199a464ca283797f545b783cce07b38a5

or have I misunderstood?

like image 386
Er Dj Avatar asked Aug 04 '11 09:08

Er Dj


People also ask

What is the use of Hashlib?

This module implements a common interface to many different secure hash and message digest algorithms. Included are the FIPS secure hash algorithms SHA1, SHA224, SHA256, SHA384, and SHA512 (defined in FIPS 180-2) as well as RSA's MD5 algorithm (defined in internet RFC 1321).

What is Hashlib SHA256?

Python has a built-in library, hashlib , that is designed to provide a common interface to different secure hashing algorithms. The module provides constructor methods for each type of hash. For example, the . sha256() constructor is used to create a SHA256 hash.

Is Hashlib built into Python?

Hashlib is a Python library that provides the SHA-224, SHA-256, SHA-384, SHA-512 hash algorithms. Besides this Hashlib provides the platform optimized versions of MD5 and SHA1.


1 Answers

This is because hmac uses the provided key to generate a salt and make the hash more strong, while hashlib only hashes the provided message.

By looking at the hmac module source code, you will find how to achieve the same behaviour as hmac using the hashlib module, here the used algorithm (it's not the original one, i stripped some checkings to have just the interesting part):

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

The same directly using hmac:

import hashlib
import hmac

result = hmac.new(KEY, MESSAGE, hashlib.sha256).hexdigest()
print result # prints 2d93cbc1be167bcb1637a4a23cbff01a7878f0c50ee833954ea5221bb1b8c628

So when using hmac, it doesn't only hashes the given message using the specified hashing algorithm, it also uses the key to complexify the hash.

like image 99
mdeous Avatar answered Oct 16 '22 15:10

mdeous