Search code examples
javascriptjwtcryptojs

CryptoJS : key.clamp is not a function


TypeError: key.clamp is not a function
  at Object.init (path/node_modules/crypto-js/hmac.js:58:18)

The error above occurs when I try to create JWT in Javascript with the relevant code below.

const CryptoJS = require('crypto-js');
var hash = CryptoJS.HmacSHA256(token.join("."), secret);

crypto-js/hmac.js:58:18 has key.clamp(); and I'm not sure what would be the best approach. I tried with HmacSHA512 but it returns the same error.

I'm running with npm 6.1.0 node v6.10.3 crypto-js ^3.1.9-1.


Solution

  • From their samples, secret (or key as they call it), should be a string.

    As such, using CryptoJS like this should work just fine:

    const token = "a,b"; // fake token
    const secret = CryptoJS.enc.Utf8.parse("mySecret"); //encode mySecret into UTF-8 as suggested in the comments
    const CryptoJS = require('crypto-js');
    var hash = CryptoJS.HmacSHA256(token.split(","), secret);
    console.log(hash);