Skip to content

Instantly share code, notes, and snippets.

@shubham-sharmas
Created October 30, 2023 15:43
Show Gist options
  • Save shubham-sharmas/5141fd7d9a5471bbd5b448c1dabbbb66 to your computer and use it in GitHub Desktop.
Save shubham-sharmas/5141fd7d9a5471bbd5b448c1dabbbb66 to your computer and use it in GitHub Desktop.
Node.js child_process.fork() method example: forking hash_worker.js to generate password hash using node.js crypto module
const crypto = require('crypto');
process.on('message', (password) => {
crypto.randomBytes(32, (err, salt) => {
if (err) {
process.send({ error: err.message });
} else {
crypto.pbkdf2(password, salt, 10000, 64, 'sha512', (err, derivedKey) => {
if (err) {
process.send({ error: err.message });
} else {
process.send({ salt: salt.toString('hex'), hash: derivedKey.toString('hex') });
}
process.exit();
});
}
});
});
const { fork } = require('child_process');
const path = require('path');
const hashWorker = fork(path.join(__dirname, 'hash_worker.js'));
const passwordToHash = '$ecreT_Pa$$w0rd';
hashWorker.on('message', (message) => {
if (message.error) {
console.error('Error:', message.error);
} else if (message.hash) {
console.log('Hashed Password:', message.hash);
}
});
hashWorker.send(passwordToHash);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment