UNPKG

1.96 kBPlain TextView Raw
1#!/usr/bin/env node
2
3'use strict'
4
5var fs = require('fs')
6
7var stdin = require('get-stdin')
8var eccrypto = require('eccrypto')
9
10var command = process.argv[0]
11var script = process.argv[1]
12var private_key = process.argv[2]
13var iv = process.argv[3]
14var ephem = process.argv[4]
15var mac = process.argv[5]
16var cipher = process.argv[6]
17
18var pk, m
19
20function 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
35if (!(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
42try {
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
56stdin.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})