ATM
ATM

Reputation: 3

HMAC python differs from HMAC php

Im migrating my lumen code to python, for hmac function I have this:

PHP

$hash = hash_hmac(
  'sha256',
  '[email protected]', 
  'message'
);

Python 3

import hmac
import hashlib

user_hash = hmac.new(b'[email protected]', b'message', hashlib.sha256).hexdigest()

The problem is that both results doesnt match:

PHP Output

413777aac2561ca3acd6d49c95df9ecae4c6e2f6bc9adc40bbb77650d7b4c459

Python Output

42879f50e909799d93b835a81a65c03cf78a56ef1c038ac75c8ab3f211d083ea

I guess the problem is how python 3 interpret string but I cant figure it out. Any help please?

Upvotes: 0

Views: 1224

Answers (1)

Daniel Pryden
Daniel Pryden

Reputation: 60917

The order of arguments to HMAC makes a difference:

>>> hmac.new(b'[email protected]', b'message', hashlib.sha256).hexdigest()
'42879f50e909799d93b835a81a65c03cf78a56ef1c038ac75c8ab3f211d083ea'

>>> hmac.new(b'message', b'[email protected]', hashlib.sha256).hexdigest()
'413777aac2561ca3acd6d49c95df9ecae4c6e2f6bc9adc40bbb77650d7b4c459'

In hmac.new, the first argument is the key (the starting key for the hash), and the second argument is the msg, the message to be digested.

Upvotes: 2

Related Questions