Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hash_hmac (PHP) vs hex_hmac_sha1 (Javascript)

Tags:

javascript

php

Im new here and I have question.

Could you tell me why hex_hmac_sha1 (function in Javascript) is not working as well as hash_hmac (function in PHP).

If it's A-z letter its all ok but its not ok for other characters.

For example:

Javascript

<script type="text/javascript" src="https://online.ingbank.pl/mobi/js/sha1.js"></script>
<script>
document.write(hex_hmac_sha1("1492343027",'a')+"<br />");
document.write(hex_hmac_sha1("1492343027",'ą')+"<br />");
document.write(hex_hmac_sha1("1492343027",'c')+"<br />");
document.write(hex_hmac_sha1("1492343027",'ć')+"<br />");
</script>

output:

f75d4cbfbfda2476a9c92fff10fdf0e726ee06ab
206e608ecaf23a9575ca81a86e3afd72eca243a0
73e0dc1dd914b1386a5f2624883caad41025da07
86dc107aac5cb5c17a846defd651a3eb53d66a44

PHP

echo hash_hmac("sha1", 'a', "1492343027").'<br />'; 
echo hash_hmac("sha1", 'ą', "1492343027").'<br />'; 
echo hash_hmac("sha1", 'c', "1492343027").'<br />'; 
echo hash_hmac("sha1", 'ć', "1492343027").'<br />'; 

output:

f75d4cbfbfda2476a9c92fff10fdf0e726ee06ab
8b353bb4c891d73ae9be09d0653e2564e0dff243
73e0dc1dd914b1386a5f2624883caad41025da07
52278a6e8676e8f3c667082411cfa04519c4bab1

For 'a' and 'c' its all ok but what is going on with 'ą' and 'ć'?

Thanks for help

like image 859
Kamil Wiśniewski Avatar asked Aug 12 '26 07:08

Kamil Wiśniewski


1 Answers

The difference between the PHP and JS implementation is, that PHP handles the UTF-8 string as as 8-bit chars, while in JS each char is represented by Unicode.

Please give this a try:

hash_hmac("sha1", 'ą', "1492343027") == hex_hmac_sha1("1492343027",'\xC4\x85')

JSFIDDLE

UTF 8 hex from - http://www.charbase.com/0105-unicode-latin-small-letter-a-with-ogonek

JS

hex_hmac_sha1("1492343027",'ą')        = 206e608ecaf23a9575ca81a86e3afd72eca243a0
hex_hmac_sha1("1492343027",'\xC4\x85') = 8b353bb4c891d73ae9be09d0653e2564e0dff243

Escape your Unicode on JS side...

PHP

hash_hmac("sha1", 'ą', "1492343027");        = 8b353bb4c891d73ae9be09d0653e2564e0dff243
hash_hmac("sha1", "\xC4\x85", "1492343027"); = 8b353bb4c891d73ae9be09d0653e2564e0dff243
like image 154
Jens A. Koch Avatar answered Aug 13 '26 19:08

Jens A. Koch