-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerateKeyPair.js
40 lines (34 loc) · 1.92 KB
/
generateKeyPair.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Import the built-in crypto module for generating keys
const crypto = require('crypto');
const publicKeyToBase64 = require("publicKeyToBase64")
// Import the built-in fs module for writing keys to files
const fs = require('fs');
// Define a function to generate the key pair
function generateKeyPair() {
// Generate a new key pair using RSA algorithm with a modulus length of 2048 bits ( size of the key )
// RSA is related to the RS256, RS384, RS512 algorithms. We support the following algorithms: RS256, RS384, RS512, ECDSA256, ECDSA384, ECDSA512.
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
});
// Write the private key to a file named 'private_key.pem'
// The export function exports the key in the specified format (in this case, PKCS #1)
// PKCS#1 is a standard format that represents an RSA private key. It is widely used and compatible with many libraries and services.
fs.writeFileSync('private_key.pem', privateKey.export({
type: 'pkcs1',
format: 'pem'
}));
// Write the public key to a file named 'public_key.pem'
// The export function exports the key in the specified format (in this case, SPKI)
// We require the public key in 'spki' (Subject Public Key Info) format, as it's a standard format that
// includes the algorithm identifier along with the key data , which is important for properly reading and using the key.
fs.writeFileSync('public_key.pem', publicKey.export({
type: 'spki',
format: 'pem'
}));
// Log that the key pair was generated and saved to files
console.log('Key pair generated and saved to files "private_key.pem" and "public_key.pem".\n');
publicKeyToBase64()
console.log('\nRemember to save the console logged encoded string above to the .env file as per README env instructions!".');
}
// Execute the function to generate the key pair
generateKeyPair();