web-dev-qa-db-fra.com

Comment utiliser Node.js Crypto pour créer un hachage HMAC-SHA1?

Je veux créer un hash de I love cupcakes (signé avec la clé abcdeg)

Comment créer ce hachage en utilisant Node.js Crypto?

187
user847495

Documentation pour crypto: http://nodejs.org/api/crypto.html

var crypto = require('crypto')
  , text = 'I love cupcakes'
  , key = 'abcdeg'
  , hash

hash = crypto.createHmac('sha1', key).update(text).digest('hex')
336
Ricardo Tomasi

Il y a quelques années, il a été dit que update() et digest() étaient des méthodes héritées et que la nouvelle approche de streaming API a été introduite. Maintenant, les docs disent que l'une ou l'autre méthode peut être utilisée. Par exemple:

var crypto    = require('crypto');
var text      = 'I love cupcakes';
var secret    = 'abcdeg'; //make this your secret!!
var algorithm = 'sha1';   //consider using sha256
var hash, hmac;

// Method 1 - Writing to a stream
hmac = crypto.createHmac(algorithm, secret);    
hmac.write(text); // write in to the stream
hmac.end();       // can't read from the stream until you call end()
hash = hmac.read().toString('hex');    // read out hmac digest
console.log("Method 1: ", hash);

// Method 2 - Using update and digest:
hmac = crypto.createHmac(algorithm, secret);
hmac.update(text);
hash = hmac.digest('hex');
console.log("Method 2: ", hash);

Testé sur les nœuds v6.2.2 et v7.7.2

Voir https://nodejs.org/api/crypto.html#crypto_class_hmac . Donne plus d'exemples d'utilisation de l'approche de la diffusion en continu.

93
Adam Griffiths

La solution de Gwerder ne fonctionnera pas car hash = hmac.read(); se produit avant la finalisation du flux. Ainsi, les problèmes d'AngraX. De plus, l'instruction hmac.write n'est pas nécessaire dans cet exemple.

Au lieu de cela, faites ceci:

var crypto    = require('crypto');
var hmac;
var algorithm = 'sha1';
var key       = 'abcdeg';
var text      = 'I love cupcakes';
var hash;

hmac = crypto.createHmac(algorithm, key);

// readout format:
hmac.setEncoding('hex');
//or also commonly: hmac.setEncoding('base64');

// callback is attached as listener to stream's finish event:
hmac.end(text, function () {
    hash = hmac.read();
    //...do something with the hash...
});

Plus formellement, si vous le souhaitez, la ligne

hmac.end(text, function () {

pourrait être écrit

hmac.end(text, 'utf8', function () {

parce que dans cet exemple, le texte est une chaîne utf

21
Dave