How can I get the sha1 hash of a string in node.js?


Question

I'm trying to create a websocket server written in node.js

To get the server to work I need to get the SHA1 hash of a string.

What I have to do is explained in Section 5.2.2 page 35 of the docs.

NOTE: As an example, if the value of the "Sec-WebSocket-Key" header in the client's handshake were "dGhlIHNhbXBsZSBub25jZQ==", the server would append thestring "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" to form the string "dGhlIHNhbXBsZSBub25jZQ==258EAFA5-E914-47DA-95CA-C5AB0DC85B11". The server would then take the SHA-1 hash of this string, giving the value 0xb3 0x7a 0x4f 0x2c 0xc0 0x62 0x4f 0x16 0x90 0xf6 0x46 0x06 0xcf 0x38 0x59 0x45 0xb2 0xbe 0xc4 0xea. This value is then base64-encoded, to give the value "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", which would be returned in the "Sec-WebSocket-Accept" header.

1
93
3/17/2015 9:59:15 PM

Accepted Answer

See the crypto.createHash() function and the associated hash.update() and hash.digest() functions:

const crypto = require('crypto')
  , shasum = crypto.createHash('sha1');
shasum.update('foo');
console.log(shasum.digest('hex'));
// "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33"
215
7/16/2019 4:34:00 PM

Obligatory: SHA1 is broken, you can make collisions with the AWS credits of the average startup accelerator cohort but to answer your question:

var getSHA1ofJSON = function(input){
    return crypto.createHash('sha1').update(JSON.stringify(input)).digest('hex')
}

Then:

getSHA1ofJSON('whatever')

or

getSHA1ofJSON(['whatever'])

or

getSHA1ofJSON({'this':'too'})

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon