UNPKG

2.12 kBJavaScriptView Raw
1'use strict';
2
3const forge = require('node-forge');
4
5/**
6 * Generates public/private key pairs
7 *
8 * @function generateKeyPair
9 * @returns {Object} a forge pki object
10 */
11function generateKeyPair() {
12 const rsa = forge.pki.rsa;
13 console.log('Generating keys. It might take a few seconds!');
14 return rsa.generateKeyPair({ bits: 2048, e: 0x10001 });
15}
16
17/**
18 * Generates private/public keys and Upload them to a given bucket
19 *
20 * @param {string} bucket - the bucket to upload the keys to
21 * @param {string} key - the key (folder) to use for the uploaded files
22 * @param {Object} s3 - an instance of the AWS S3 class
23 * @returns {Promise} resolves `undefined` when upload is complete
24 */
25async function uploadKeyPair(bucket, key, s3) {
26 const pki = forge.pki;
27 const keyPair = generateKeyPair();
28 console.log('Keys Generated');
29
30 // upload the private key
31 const privateKey = pki.privateKeyToPem(keyPair.privateKey);
32 const params1 = {
33 Bucket: bucket,
34 Key: `${key}/private.pem`,
35 ACL: 'private',
36 Body: privateKey
37 };
38
39 // upload the public key
40 const publicKey = pki.publicKeyToPem(keyPair.publicKey);
41 const params2 = {
42 Bucket: bucket,
43 Key: `${key}/public.pub`,
44 ACL: 'private',
45 Body: publicKey
46 };
47
48 await s3.putObject(params1).promise();
49 await s3.putObject(params2).promise();
50
51 console.log('keys uploaded to S3');
52}
53
54/**
55 * Checks if the private/public key exists. If not, it
56 * generates and uploads them
57 *
58 * @param {string} stack - name of the stack
59 * @param {string} bucket - the bucket to upload the keys to
60 * @param {Object} s3 - an instance of AWS S3 class
61 * @returns {Promise} resolves `undefined` when complete
62 */
63async function crypto(stack, bucket, s3) {
64 const key = `${stack}/crypto`;
65
66 // check if files are generated
67 try {
68 await s3.headObject({
69 Key: `${key}/public.pub`,
70 Bucket: bucket
71 }).promise();
72
73 await s3.headObject({
74 Key: `${key}/private.pem`,
75 Bucket: bucket
76 }).promise();
77 } catch (e) {
78 await uploadKeyPair(bucket, key, s3);
79 }
80}
81
82module.exports = {
83 generateKeyPair,
84 uploadKeyPair,
85 crypto
86};