0

I am trying to call an API written in PHP that generates a token using the following method:

base64_encode(hash_hmac("sha256", "<api-key>", "<email>:<gmdate('y-m-d H')>"))

In JavaScript (Node.js), I attempted to generate the same token with this code:

import crypto from "crypto";

function generateToken(apiKey, email) {
  const timestamp = new Date().toISOString().slice(0, 13).replace("T", " ");
  const data = `${email}:${timestamp}`;

  const hash = crypto.createHmac("sha256", apiKey).update(data).digest("hex");
  return Buffer.from(hash).toString("base64");
}

// Example usage
const apiKey = "your-api-key";
const email = "[email protected]";
const token = generateToken(apiKey, email);

console.log(token);

However, the output of this function does not match the token generated by the PHP code, and I am unable to authenticate the API request.

6
  • 1
    Won't the timestamps be different? Commented Apr 3 at 2:51
  • I passed the same email, API key, and timestamp, but the output is still different. I think the issue is with the encoding method. Commented Apr 3 at 3:05
  • 1
    You're not passing the timestamp though, you're generating it from the current system time Commented Apr 3 at 3:10
  • It should be possible to achieve the requirement in the browser (and Node.js, Deno, and Bun, et al.) using Web Cryptography API. Commented Apr 3 at 3:16
  • 1
    You might have the args mixed up. The PHP function signature is hash_hmac(algo, data, secretKey). The JS is createHmac(algo, secretKey) with the data passed to update(). You're passing apiKey to PHP's data param but passing it to JS's secretKey param Commented Apr 3 at 3:18

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.