2018-08-30 23:38:01 +02:00
|
|
|
/**
|
2020-04-06 14:35:14 +02:00
|
|
|
* @author Matt C [me@mitt.dev]
|
2018-08-30 23:38:01 +02:00
|
|
|
* @author gchq77703 []
|
|
|
|
* @copyright Crown Copyright 2018
|
2019-09-30 14:12:10 +02:00
|
|
|
* @license Apache-2.0
|
2018-08-30 23:38:01 +02:00
|
|
|
*/
|
|
|
|
|
2021-02-01 20:15:32 +01:00
|
|
|
import Operation from "../Operation.mjs";
|
|
|
|
import forge from "node-forge";
|
2021-02-09 16:00:35 +01:00
|
|
|
import { cryptNotice } from "../lib/Crypt.mjs";
|
2018-08-30 23:38:01 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Generate RSA Key Pair operation
|
|
|
|
*/
|
|
|
|
class GenerateRSAKeyPair extends Operation {
|
|
|
|
|
|
|
|
/**
|
|
|
|
* GenerateRSAKeyPair constructor
|
|
|
|
*/
|
|
|
|
constructor() {
|
|
|
|
super();
|
|
|
|
|
|
|
|
this.name = "Generate RSA Key Pair";
|
|
|
|
this.module = "Ciphers";
|
2021-02-09 16:00:35 +01:00
|
|
|
this.description = `Generate an RSA key pair with a given number of bits.<br><br>${cryptNotice}`;
|
2018-08-30 23:38:01 +02:00
|
|
|
this.infoURL = "https://wikipedia.org/wiki/RSA_(cryptosystem)";
|
|
|
|
this.inputType = "string";
|
|
|
|
this.outputType = "string";
|
|
|
|
this.args = [
|
|
|
|
{
|
|
|
|
name: "RSA Key Length",
|
|
|
|
type: "option",
|
|
|
|
value: [
|
|
|
|
"1024",
|
|
|
|
"2048",
|
|
|
|
"4096"
|
|
|
|
]
|
|
|
|
},
|
|
|
|
{
|
|
|
|
name: "Output Format",
|
|
|
|
type: "option",
|
|
|
|
value: [
|
|
|
|
"PEM",
|
|
|
|
"JSON",
|
|
|
|
"DER"
|
|
|
|
]
|
|
|
|
}
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param {string} input
|
|
|
|
* @param {Object[]} args
|
|
|
|
* @returns {string}
|
|
|
|
*/
|
|
|
|
async run(input, args) {
|
2018-08-31 12:25:05 +02:00
|
|
|
const [keyLength, outputFormat] = args;
|
2018-08-30 23:38:01 +02:00
|
|
|
|
|
|
|
return new Promise((resolve, reject) => {
|
2021-02-01 20:15:32 +01:00
|
|
|
forge.pki.rsa.generateKeyPair({
|
|
|
|
bits: Number(keyLength),
|
|
|
|
workers: -1,
|
|
|
|
workerScript: "assets/forge/prime.worker.min.js"
|
|
|
|
}, (err, keypair) => {
|
2018-08-31 12:25:05 +02:00
|
|
|
if (err) return reject(err);
|
2018-08-30 23:38:01 +02:00
|
|
|
|
|
|
|
let result;
|
|
|
|
|
2018-08-31 12:25:05 +02:00
|
|
|
switch (outputFormat) {
|
2018-08-30 23:38:01 +02:00
|
|
|
case "PEM":
|
|
|
|
result = forge.pki.publicKeyToPem(keypair.publicKey) + "\n" + forge.pki.privateKeyToPem(keypair.privateKey);
|
|
|
|
break;
|
|
|
|
case "JSON":
|
|
|
|
result = JSON.stringify(keypair);
|
|
|
|
break;
|
|
|
|
case "DER":
|
|
|
|
result = forge.asn1.toDer(forge.pki.privateKeyToAsn1(keypair.privateKey)).getBytes();
|
|
|
|
break;
|
2018-08-31 12:25:05 +02:00
|
|
|
}
|
2018-08-30 23:38:01 +02:00
|
|
|
|
|
|
|
resolve(result);
|
2018-08-31 12:25:05 +02:00
|
|
|
});
|
|
|
|
});
|
2018-08-30 23:38:01 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
export default GenerateRSAKeyPair;
|