1

Problem

my command script generates sometimes different result then PHP hash_hmac command. Can somebody explain or show an example how it should be done.

The script generates username based on timestamp. An example of username that generates a different result: 1611134116:admin

Full Script

<?php
$secret="XXXXXXXXXXXX";
$user = "admin";
$ttl = 24 * 3600;  // Time to live
$time = time() + $ttl;
$username = $time . ':' . $user;
$password = base64_encode(hash_hmac('sha1', $username, $secret, true));
$password2 = base64_encode(hash_hmac('sha1', $username, $secret, true));

$result2 = base64_encode(hash_hmac('sha1', $username, $secret, true));
$result = exec("printf %s $(printf %s " . $username . " | openssl dgst -sha1 -hmac " . $secret . " -binary) | base64");

echo $username;
echo "<br><br>";
echo $result;
echo "<br>";
echo $result2;
echo "<br>";
echo ("Is equal: " . (($result === $result2) ? "true" : "false"));
echo "<br><br>";
echo $password;
echo "<br>";
echo $password2;
echo "<br>";
echo ("Is equal: " . (($password === $password2) ? "true" : "false"));

Problematic part

$result = exec("printf %s $(printf %s " . $username . " | openssl dgst -sha1 -hmac " . $secret . " -binary) | base64");

Note: that problem only occurs when output is generated as binary and that is really important for me.

I tried using echo -n and stopped using variables but the problem persists.

2
  • 1
    Why the double printf? Why not just printf %s " . $username . " | openssl dgst -sha1 -hmac " . $secret . " -binary | base64? – muru Jan 19 at 9:45
  • looks like inner printf output a binary string feeded to printf "%s", result is different than muru's proposal – Archemar Jan 19 at 11:04
1

muru's comment did the trick, the problem was related to incorrect usage of printf %s.

Working code

$result = exec("printf %s " . $username . " | openssl dgst -sha1 -hmac " . $secret . " -binary | base64");

Thank you for your time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.