UNPKG

2.63 kBJavaScriptView Raw
1#!/usr/bin/env Node
2
3function passwdjs(lines, options) {
4 var bcrypt = require('bcryptjs');
5 var EventEmitter = require('events').EventEmitter;
6 var async = require('async');
7 var e = new EventEmitter();
8 async.mapSeries(lines, hash, function (err, results) {
9 e.emit('done', results);
10 })
11
12 function hash(line, cb) {
13 bcrypt.genSalt(options.rounds, function (err, salt) {
14 if (err) return cb(err);
15 if (line.length === 0) return cb();
16 bcrypt.hash(line, salt, function (err, hashed) {
17 if (err) return cb(err);
18 var out = (options.plaintext ? (line + options.separator) : "") + hashed;
19 e.emit('line', out);
20 return cb(null, out);
21 });
22 });
23 }
24 return e;
25}
26
27if (require.main === module) {
28 var command = require('commander')
29
30 command
31 .version('0.0.3')
32 .usage('[options]')
33 .description("Reads stdin and uses bcrypt to hash each line. Writes " +
34 "hash values to stdout one per line in the same order as the input lines.")
35
36 .option('-r, --rounds <n>', "Complexity factor for salt generation [10]", parseInt, 10)
37 .option('-p, --plaintext', "Include plaintext at beginning of line, sepated by ' '")
38 .option('-s, --separator <separator>', "Use as a separator between plaintext and hash [':']")
39
40 command.on('--help', function () {
41 console.log(' Examples:');
42 console.log('');
43 console.log(' $ cat file.txt | passwdjs -r 10 -p -s " "');
44 console.log(' $ echo "password" | passwdjs -r 15');
45 console.log('');
46 });
47
48 command.parse(process.argv);
49
50 var options = {
51 rounds: parseInt(command.rounds) || 10,
52 plaintext: command.plaintext || false,
53 separator: command.separator || ''
54 }
55
56 var data = "";
57 process.stdin.resume();
58 process.stdin.setEncoding('utf8');
59 process.stdin.on('data', function (chunk) {
60 data += chunk;
61 });
62 process.stdin.on('end', hashData);
63
64 function hashData() {
65 var lines = data.split('\n');
66 passwdjs(lines, options)
67 .on('line', function (hashed) {
68 process.stdout.write(hashed + '\n');
69 })
70 .on('done', function (results) {
71 process.exit(0);
72 })
73 .on('error', function (err) {
74 process.stderr.write(err);
75 process.exit(1);
76 })
77 }
78}
79
80module.exports = passwdjs;
\No newline at end of file