Skip to content
Advertisement

WebCrypto JS SHA256 HMAC Mismatch

I have two scripts that generate a SHA256 HMAC, with a plaintext message and Base64 encoded key. One is written in PHP and the other in JavaScript. The PHP script returns the correct HMAC, but for some reason the JS version does not. What is causing this?

Here are the code samples, with a redacted (still similar in nature) key.

PHP

JavaScript

This script, returns MTYxNDExNzczNzQ2NztFdXcwQ1l0bTBTMkdIdnZ2ZnN2ZGFkTEFDMGVPbVlJeHFzZk9PQWExS1BzPQ==

JS

JavaScript

Which returns MTYxNDExNzczNzQ2NztBeGxFRVJCTzVYWm5KN2ZHNCtoeWlxalJ0VmxZQmJpekNUSEwzcldMQVhzPQ==

Why are these seemingly identical scripts returning different results?

Advertisement

Answer

It have to do with the differences in handling binary arrays or strings in php/javascript. If you change base64_decode($key) to $key (php) and atob(key) to key (javascript) it works fine.

Edit:

The error is in unescape(encodeURIComponent(str)), just remove the functions and change to str and it should work.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement