1 | #!/usr/bin/env node
|
2 |
|
3 | 'use strict'
|
4 |
|
5 | var fs = require('fs')
|
6 |
|
7 | var stdin = require('get-stdin')
|
8 | var eccrypto = require('eccrypto')
|
9 |
|
10 | var command = process.argv[0]
|
11 | var script = process.argv[1]
|
12 | var private_key = process.argv[2]
|
13 | var iv = process.argv[3]
|
14 | var ephem = process.argv[4]
|
15 | var mac = process.argv[5]
|
16 | var cipher = process.argv[6]
|
17 |
|
18 | var pk, m
|
19 |
|
20 | function d(private_key, message) {
|
21 | eccrypto.decrypt(private_key, message).then(function(decrypted) {
|
22 | process.stdout.write(JSON.stringify({
|
23 | decrypted: decrypted.toString('hex')
|
24 | }), function() {
|
25 | process.exit(0)
|
26 | })
|
27 | }).catch(function(err) {
|
28 | process.stdout.write(JSON.stringify({
|
29 | eccrypto_error: JSON.stringify(err)
|
30 | }))
|
31 | process.exit(1)
|
32 | })
|
33 | }
|
34 |
|
35 | if (!(private_key && iv && ephem && mac)) {
|
36 | process.stdout.write(JSON.stringify({
|
37 | error: 'private key, iv, ephem or mac not given'
|
38 | }))
|
39 | process.exit(1)
|
40 | }
|
41 |
|
42 | try {
|
43 | pk = Buffer(private_key, 'hex')
|
44 | m = {
|
45 | iv: Buffer(iv, 'hex'),
|
46 | ephemPublicKey: Buffer(ephem, 'hex'),
|
47 | mac: Buffer(mac, 'hex')
|
48 | }
|
49 | } catch (err) {
|
50 | process.stdout.write(JSON.stringify({
|
51 | error: 'private key, iv, ephem, or mac is not hexadecimal'
|
52 | }))
|
53 | process.exit(1)
|
54 | }
|
55 |
|
56 | stdin.buffer().then(function(s) {
|
57 | if (s.length) {
|
58 | m.ciphertext = Buffer(s.toString().trim(), 'hex')
|
59 | d(pk, m)
|
60 | } else if (!cipher) {
|
61 | process.stdout.write(JSON.stringify({
|
62 | error: 'cipher not given'
|
63 | }))
|
64 | process.exit(1)
|
65 | } else {
|
66 | fs.readFile(cipher, function(err, buffer) {
|
67 | if (buffer && buffer.length) {
|
68 | m.ciphertext = Buffer(buffer.toString().trim(), 'hex')
|
69 | d(pk, m)
|
70 | } else if (err && cipher.length) {
|
71 | try {
|
72 | m.ciphertext = Buffer(cipher, 'hex')
|
73 | d(pk, m)
|
74 | } catch (err) {
|
75 | process.stdout.write(JSON.stringify({
|
76 | error: 'cipher is not hexadecimal'
|
77 | }))
|
78 | process.exit(1)
|
79 | }
|
80 | } else {
|
81 | process.exit(1)
|
82 | }
|
83 | })
|
84 | }
|
85 | })
|