1/*
2 Keyring Safe Box V0.0.1 Alpha
3 Encrypt and Decrypt keys using AWS KMS
4 http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/KMS.html
5 Requirements: aws-sdk reads in your aws credentials from ~/.aws/credentials
6
7 How to run:
8 node index encrypt --alias="twitterbot" --token="xxxxx"
9 node index decrypt --token="xxxasdasd"
10 */
11const AWS = require('aws-sdk');
12const kms = new AWS.KMS({ region: 'eu-west-1' });
13
14// Entrypoint
15const args = require('yargs')
16 .command('decrypt', 'Decrypt a token', (yargs) => { }, (argv) => {
17 const { token } = argv;
18 decrypt(token);
19 })
20 .command('encrypt', 'Encrypt a token', (yargs) => { }, (argv) => {
21 const { alias, token } = argv;
22 encrypt(token,alias);
23
24 })
25 .command('*', 'Encrypt a token', (yargs) => { }, (argv) => {
26 const { alias, token } = argv;
27 encrypt(token,alias);
28 })
29 .argv;
30
31function encrypt(plainText, alias) {
32 if(!plainText || !alias){
33 throw Error ('Missing Parameters');
34 process.exit(1);
35 }
36 const params = {
37 KeyId: `alias/${alias}`,
38 Plaintext: plainText
39 };
40 kms.encrypt(params).promise()
41 .then(data => {
42 const { CiphertextBlob } = data; // Base64 - binary into the ASCII character set.
43 const base64data = CiphertextBlob.toString('base64');
44 log(base64data)
45 })
46 .catch(err => {
47 log(err, err.stack);
48 });
49}
50
51function decrypt(cipherText) {
52 if(!cipherText){
53 throw Error ('Missing Parameters');
54 process.exit(1);
55 }
56 const params = {
57 CiphertextBlob: new Buffer(cipherText, 'base64')
58 };
59
60 kms.decrypt(params).promise()
61 .then(data => {
62 const { Plaintext } = data; // Base64 - binary into the ASCII character set.
63 const decryptedText = Plaintext.toString('ascii');
64 log(decryptedText)
65 })
66 .catch(err => {
67 log(err, err.stack);
68 });
69}
70
71function log(text){
72 console.log(text);
73}
Created on 11/1/2017