1 | 'use strict';
|
2 |
|
3 | const forge = require('node-forge');
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | function 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 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 | async function uploadKeyPair(bucket, key, s3) {
|
26 | const pki = forge.pki;
|
27 | const keyPair = generateKeyPair();
|
28 | console.log('Keys Generated');
|
29 |
|
30 |
|
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 |
|
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 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 |
|
62 |
|
63 | async function crypto(stack, bucket, s3) {
|
64 | const key = `${stack}/crypto`;
|
65 |
|
66 |
|
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 |
|
82 | module.exports = {
|
83 | generateKeyPair,
|
84 | uploadKeyPair,
|
85 | crypto
|
86 | };
|