HMAC function does not always return the same value


#1

I am trying to use HMAC from crypto.hash library.
Testing by continually calling the HMAC function with the same message and key values sometimes gives different results …

CODE EXAMPLE ::

import streams
from crypto.hash import sha3 as sha3
from crypto.hash import hmac as hmac

streams.serial()

def getHash(message, key):
…hh = hmac.HMAC(key, sha3.SHA3())
…hh.update(message)
…return hh.hexdigest()

message = ‘The Test Message’
key = bytes([ 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,
0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,
0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,
0x18,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f ])

x = 1

while True:
…print(str(x) + ’ HMAC: '+ getHash(message,key))
…x += 1
…sleep(500)

OUTPUT ::::

1 HMAC: 4601192CE077BB9FAA56CC38A32448618D2CEE01FFF8031C10E38C28709FDF08
2 HMAC: CC4CCE062DFB48F9ED7640C73894929E107A29083B2063AF8D2D70B928F58DBD
3 HMAC: CC4CCE062DFB48F9ED7640C73894929E107A29083B2063AF8D2D70B928F58DBD
4 HMAC: 5A8BC9256AF2D3D3A5F3215EE652C2F6712B018ECC06E9F55C0CE78B0D6164A5
5 HMAC: CC4CCE062DFB48F9ED7640C73894929E107A29083B2063AF8D2D70B928F58DBD
6 HMAC: CC4CCE062DFB48F9ED7640C73894929E107A29083B2063AF8D2D70B928F58DBD
7 HMAC: CC4CCE062DFB48F9ED7640C73894929E107A29083B2063AF8D2D70B928F58DBD
8 HMAC: CC4CCE062DFB48F9ED7640C73894929E107A29083B2063AF8D2D70B928F58DBD
9 HMAC: CC4CCE062DFB48F9ED7640C73894929E107A29083B2063AF8D2D70B928F58DBD
10 HMAC: CC4CCE062DFB48F9ED7640C73894929E107A29083B2063AF8D2D70B928F58DBD
11 HMAC: CC4CCE062DFB48F9ED7640C73894929E107A29083B2063AF8D2D70B928F58DBD
12 HMAC: CC4CCE062DFB48F9ED7640C73894929E107A29083B2063AF8D2D70B928F58DBD
13 HMAC: CC4CCE062DFB48F9ED7640C73894929E107A29083B2063AF8D2D70B928F58DBD
14 HMAC: CC4CCE062DFB48F9ED7640C73894929E107A29083B2063AF8D2D70B928F58DBD
15 HMAC: 5A8BC9256AF2D3D3A5F3215EE652C2F6712B018ECC06E9F55C0CE78B0D6164A5

Note that output is different at lines 1,4,15

I think that CC4CCE … is the correct value but a different value appears at random intervals in the output.

This is running on ESP32 [PyCOM WiPy3]
Any ideas about what is happening or am I doing something stupid ???


#2

Hi @w1bworx!
Sounds like there’s a bug, I’m going to investigate the issue and let you know as soon as possible.

Thanks,
Antonio


#3

Hi @w1bworx,

you can check for the correctness of HMAC here and sadly the correct hmac should be 0a29e8423e38f690571c64a65dc5549c5232eb8e378af3c653cd165c765849d1.

The bug is probably in the Cifra library that we use for crypto hashes. I filed a bug report on their github, but in the meantime you can fix by manually modifying the following file: your-home-folder/.zerynth2/dist/r2.3.0/stdlib/crypto/hash/csrc/cifra/src/chash.h on Linux/Mac or c:\users\your-user-name\zerynth2\dist\r2.3.0\stdlib\crypto\hash\csrc\cifra\src\chash.h on Windows.

The line to change is 109, from:

#define CF_CHASH_MAXBLK 128

to

#define CF_CHASH_MAXBLK 144

Then the hmac is the correct one and always the same!