From d5ffab1b42be6f6257cdc3472473aad91a4271e6 Mon Sep 17 00:00:00 2001 From: microshine Date: Sun, 17 Feb 2019 10:35:59 +0300 Subject: [PATCH] Add PEM cache to asymmetric keys --- src/keys/asymmetric.ts | 1 + src/mechs/ec/crypto.ts | 10 ++++++++-- src/mechs/rsa/crypto.ts | 10 ++++++++-- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/keys/asymmetric.ts b/src/keys/asymmetric.ts index 16cd5ab..2586ab4 100644 --- a/src/keys/asymmetric.ts +++ b/src/keys/asymmetric.ts @@ -3,5 +3,6 @@ import { CryptoKey } from "./key"; export abstract class AsymmetricKey extends CryptoKey { public abstract type: "public" | "private"; + public pem?: string; } diff --git a/src/mechs/ec/crypto.ts b/src/mechs/ec/crypto.ts index 11c69e3..bb98b1a 100644 --- a/src/mechs/ec/crypto.ts +++ b/src/mechs/ec/crypto.ts @@ -55,8 +55,11 @@ export class EcCrypto { const signer = crypto.createSign(cryptoAlg); signer.update(Buffer.from(data)); + if (!key.pem) { + key.pem = `-----BEGIN PRIVATE KEY-----\n${key.data.toString("base64")}\n-----END PRIVATE KEY-----`; + } const options = { - key: `-----BEGIN PRIVATE KEY-----\n${key.data.toString("base64")}\n-----END PRIVATE KEY-----`, + key: key.pem, }; const signature = signer.sign(options); @@ -75,8 +78,11 @@ export class EcCrypto { const signer = crypto.createVerify(cryptoAlg); signer.update(Buffer.from(data)); + if (!key.pem) { + key.pem = `-----BEGIN PUBLIC KEY-----\n${key.data.toString("base64")}\n-----END PUBLIC KEY-----`; + } const options = { - key: `-----BEGIN PUBLIC KEY-----\n${key.data.toString("base64")}\n-----END PUBLIC KEY-----`, + key: key.pem, }; const ecSignature = new asn.EcDsaSignature(); diff --git a/src/mechs/rsa/crypto.ts b/src/mechs/rsa/crypto.ts index 0c3e0b5..897fe7f 100644 --- a/src/mechs/rsa/crypto.ts +++ b/src/mechs/rsa/crypto.ts @@ -192,8 +192,11 @@ export class RsaCrypto { const signer = crypto.createSign(cryptoAlg); signer.update(Buffer.from(data)); + if (!key.pem) { + key.pem = `-----BEGIN PRIVATE KEY-----\n${key.data.toString("base64")}\n-----END PRIVATE KEY-----`; + } const options: INodeCryptoSignOptions = { - key: `-----BEGIN PRIVATE KEY-----\n${key.data.toString("base64")}\n-----END PRIVATE KEY-----`, + key: key.pem, }; if (algorithm.name.toUpperCase() === "RSA-PSS") { // @ts-ignore @@ -210,8 +213,11 @@ export class RsaCrypto { const signer = crypto.createVerify(cryptoAlg); signer.update(Buffer.from(data)); + if (!key.pem) { + key.pem = `-----BEGIN PUBLIC KEY-----\n${key.data.toString("base64")}\n-----END PUBLIC KEY-----`; + } const options: INodeCryptoSignOptions = { - key: `-----BEGIN PUBLIC KEY-----\n${key.data.toString("base64")}\n-----END PUBLIC KEY-----`, + key: key.pem, }; if (algorithm.name.toUpperCase() === "RSA-PSS") { // @ts-ignore