14
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.

Midori
  • 471
  • 1
  • 7
  • 11
  • I'm not able to reproduce, with `token = ["a","b"]` and `secret = "mySecret";`. What is the `typeof` of your `secret`? – Adelin Jul 09 '18 at 07:09
  • Thanks Adelin, `typeof` `secret` is object. – Midori Jul 09 '18 at 07:25
  • I'm not sure that's how they intended it to be. In all [their samples](https://github.com/brix/crypto-js), they are using a `string` – Adelin Jul 09 '18 at 07:26

1 Answers1

7

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);
Adelin
  • 7,809
  • 5
  • 37
  • 65
  • I'm geting `There was an error in evaluating the Pre-request Script: TypeError: r.clamp is not a function` do you know why? Just copied your example – JorgeeFG May 15 '20 at 19:45
  • This code is working for me. If it is not working for you, it is either because you are using a buggy version of crypto (try to update), or because you have an error in the code (try posting another question if that's the case) – Adelin May 17 '20 at 17:19
  • I have read somewhere that the problem was because I first need to encode mySecret into UTF-8. Then it worked – JorgeeFG May 17 '20 at 17:56
  • 3
    `CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(plainTextPassword));` but I'm using it for base64 encoding. Maybe I messed up your code haha – JorgeeFG May 17 '20 at 17:57