From 2233b9a0949f50bdd974a2dcb4d76a54f9605d75 Mon Sep 17 00:00:00 2001 From: Matt Date: Mon, 6 Apr 2020 15:24:06 +0100 Subject: [PATCH] Comment and add error handling to generate and sign --- src/core/operations/GenerateRSAKeyPair.mjs | 2 +- src/core/operations/RSASign.mjs | 23 +++++++++++++++------- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/src/core/operations/GenerateRSAKeyPair.mjs b/src/core/operations/GenerateRSAKeyPair.mjs index a96948f2..57cfcdd0 100644 --- a/src/core/operations/GenerateRSAKeyPair.mjs +++ b/src/core/operations/GenerateRSAKeyPair.mjs @@ -56,7 +56,7 @@ class GenerateRSAKeyPair extends Operation { const [keyLength, outputFormat] = args; return new Promise((resolve, reject) => { - forge.pki.rsa.generateKeyPair({ bits: Number(keyLength), workers: -1, workerScript: "./assets/forge/prime.worker.min.js"}, (err, keypair) => { + forge.pki.rsa.generateKeyPair({ bits: Number(keyLength), workers: -1, workerScript: "assets/forge/prime.worker.min.js"}, (err, keypair) => { if (err) return reject(err); let result; diff --git a/src/core/operations/RSASign.mjs b/src/core/operations/RSASign.mjs index 980d59b3..812de813 100644 --- a/src/core/operations/RSASign.mjs +++ b/src/core/operations/RSASign.mjs @@ -6,6 +6,7 @@ */ import Operation from "../Operation"; +import OperationError from "../errors/OperationError"; import forge from "node-forge/dist/forge.min.js"; import { MD_ALGORITHMS } from "../lib/RSA.mjs"; @@ -52,13 +53,21 @@ class RSASign extends Operation { */ run(input, args) { const [key, password, mdAlgo] = args; - - const privateKey = forge.pki.decryptRsaPrivateKey(key, password); - const md = MD_ALGORITHMS[mdAlgo].create(); - md.update(input, "utf8"); - const signature = privateKey.sign(md); - - return signature.split("").map(char => char.charCodeAt()); + if (key.replace("-----BEGIN RSA PRIVATE KEY-----", "").length === 0) { + throw new OperationError("Please enter a private key."); + } + try { + const privateKey = forge.pki.decryptRsaPrivateKey(key, password); + // Generate message hash + const md = MD_ALGORITHMS[mdAlgo].create(); + md.update(input, "utf8"); + // Convert signature UTF-16 string to byteArray + const encoder = new TextEncoder(); + const signature = encoder.encode(privateKey.sign(md)); + return signature; + } catch (err) { + throw new OperationError(err); + } } }