I'm trying to interoperate with a Java server. As part of the protocol, I need to create a SHA1 hash of my content. For some reason, only the first 16 bytes of the hash digest are used, encoded in Base64. The message digest is an array of bytes in Java, and it's truncated to length 16 before being Base64 encoded.
How can I do the same in javascript on node? I'm using the built in node crypto, but the digest is not simply an array. How can I access the hash value and retrieve the first 16 bytes? The following code gives me 20 bytes:
var crypto = require('crypto');
var hash = crypto.createHash('sha1');
data = hash.update('This is the password', 'utf-8');
gen_hash= data.digest('base64');
console.log(gen_hash);
Instead of directly generating a Base64 encoded output you can return a Buffer, slice it to get the first 16 bytes and then encode it.
const crypto = require('crypto');
var hash = crypto.createHash('sha1');
data = hash.update('This is the password', 'utf-8');
gen_hash= data.digest().slice(0, 16).toString('base64');
console.log(gen_hash);
The Buffer of the hash looks like this before slicing:
<Buffer f2 ff c3 eb 0e 37 bb 19 91 0a 05 c0 88 d2 e6 0d 6a 0e d5 25>
result is:
8v/D6w43uxmRCgXAiNLmDQ==
your original code gave:
8v/D6w43uxmRCgXAiNLmDWoO1SU=