UNPKG

1.73 kBJavaScriptView Raw
1#!/usr/bin/env node
2
3var bcrypt = require('bcryptjs')
4var options = require('commander')
5options
6 .version('0.0.3')
7 .usage('[options]')
8 .description("Reads stdin and uses bcrypt to hash each line. Writes " +
9 "hash values to stdout one per line in the same order as the input lines.")
10 .option('-r, --rounds <n>', "Complexity factor for salt generation [10]", parseInt, 10)
11 .option('-p, --plaintext', "Include plaintext at beginning of line, sepated by ' '")
12 .option('-s, --separator <separator>', "Use as a separator between plaintext and hash [':']")
13
14options.on('--help', function () {
15 console.log(' Examples:');
16 console.log('');
17 console.log(' $ cat file.txt | passwdjs -r 10 -p -s " "');
18 console.log(' $ echo "password" | passwdjs -r 15');
19 console.log('');
20});
21
22options.parse(process.argv);
23
24var rounds = options.rounds || 10;
25var plaintext = options.plaintext;
26var separator = options.separator || ":";
27var data = "";
28
29process.stdin.resume();
30process.stdin.setEncoding('utf8');
31
32process.stdin.on('data', function (chunk) {
33 data += chunk;
34});
35
36process.stdin.on('end', function () {
37 var lines = data.split('\n');
38 lines.forEach(function (line) {
39 if (line.length > 0) {
40 var out = (plaintext ? (line + separator) : "") + hash(line, rounds) + '\n';
41 process.stdout.write(out);
42 }
43 })
44});
45
46function hash(passwd, rounds) {
47 var salt = bcrypt.genSaltSync(parseInt(rounds));
48 try {
49 return (bcrypt.hashSync(passwd, salt));
50 } catch (ex) {
51 console.log("Caught error");
52 process.stderr.write(JSON.stringify(ex));
53 process.exit(1);
54 }
55}
\No newline at end of file