10

I'm trying to port the following php code to javascript on node.js:

$mac = hash_hmac('SHA256', 'string', 'secret', true);
$coded = base64_encode($mac);

I've tried the following:

var Crypto = require('crypto');
var code = Crypto.util.bytesToBase64(Crypto.HMAC(Crypto.SHA256, 'string', 'secret', { asBytes: true }));

I get the error:

TypeError: Object #Object has no method 'HMAC'

I'm new to node.js, what am I doing wrong?

Update:

var code = Crypto.createHmac('SHA256', secret_key).update(to_encode).digest('base64');

0

2 Answers 2

10

You want to use the createHmac function instead.

Crypto.createHmac("SHA256", 'secret').update('string').digest('base64')
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I get "Must give hashtype string as argument".
@Alex Sorry, the docs aren't that great, so I couldn't figure out what exactly it wanted. Hopefully this gets you in the right direction.
Crypto.SHA256 should be 'SHA256'. Thanks!
0

The method is called createHmac

> Crypto = require('crypto');
{ Credentials: [Function: Credentials],
  createCredentials: [Function],
  Hash: [Function],
  createHash: [Function],
  Hmac: [Function],
  createHmac: [Function],
  Cipher: [Function],
  createCipher: [Function],
  createCipheriv: [Function],
  Decipher: [Function],
  createDecipher: [Function],
  createDecipheriv: [Function],
  Sign: [Function],
  createSign: [Function],
  Verify: [Function],
  createVerify: [Function],
  DiffieHellman: [Function],
  createDiffieHellman: [Function],
  pbkdf2: [Function],
  randomBytes: [Function],
  pseudoRandomBytes: [Function],
  rng: [Function],
  prng: [Function] }

2 Comments

@Alex It is probably for an older version of node

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.