Edge runtime for crypto functionality different from Node.js

I am trying to build a solution using Telegram oAuth. This requires some small amount of crypto transformation for validation from Telegram's servers. Recommendations which work use Node.js' crypto methods. I was able to convert these to crypto.subtle equivalents. Unfortunately, these crypto.subtle functions create different results when using Node.js vs. Cloudflare's Workers edge runtime. If anyone has suggestions, I would appreciate it. Below is my TypeScript code.

// Node.js original code:
const key = createHash('sha256').update(BOT_TOKEN).digest()
const result = createHmac('sha256', key).update(data).digest('hex')


// Edge runtime equivalent:
async function generateSha256ArrayBuffer(token: string) {
  const data = new TextEncoder().encode(token);
  return await crypto.subtle.digest('SHA-256', data);
}

async function generateHmacSha256HexString(key: ArrayBuffer, data: string) {
  const hmacKey = await crypto.subtle.importKey(
    'raw',
    key,
    { name: 'HMAC', hash: 'SHA-256' },
    false,
    ['sign']
  );

  const signatureBuffer = await crypto.subtle.sign(
    'HMAC',
    hmacKey,
    new TextEncoder().encode(data)
  );

  const signatureArray = Array.from(new Uint8Array(signatureBuffer));
  const signatureHex = signatureArray
    .map((b) => b.toString(16).padStart(2, '0'))
    .join('');

  return signatureHex;
}

// actual calls to functions
const key = await generateSha256ArrayBuffer(BOT_TOKEN) // this is different from the Node.js equivalent when run on edge, but is the same when run on Node.js
const result = await generateHmacSha256HexString(key, data)
Was this page helpful?