import * as NodeRSA from 'node-rsa'; import { GenericKeypair } from './GenericKeypair'; export class RsaKeypair extends GenericKeypair { public keyPair : NodeRSA; //Import keypair constructor(publicKeyData ?: string, privateKeyData ?: string) { super(); if(publicKeyData == undefined && privateKeyData == undefined) { this.keyPair = new NodeRSA({b:2048}); } else { //Set the format for what to expect let format : NodeRSA.Format = "pkcs1-private-pem"; if(privateKeyData == undefined) { format = "pkcs1-public-pem"; } let Keydata = ((publicKeyData)?publicKeyData:"")+((privateKeyData)?privateKeyData:""); this.keyPair = new NodeRSA(Keydata, format); } } public Encrypt(input : string) : string { if(!this.keyPair.isPrivate()) { console.log("Warning: Tried to encrypt without a private key being imported!"); return ""; } return this.keyPair.encryptPrivate(input, 'base64'); } public Decrypt(input: string) : string { if(!this.keyPair.isPublic()) { console.log("Warning: Tried to decrypt without a public key being imported!"); return ""; } return this.keyPair.decryptPublic(input).toString('utf8'); } public Sign(dataToSign : string) : string { if(!this.keyPair.isPrivate()) { console.log("Warning: Tried to sign without a private key being imported!"); return ""; } return this.keyPair.sign(dataToSign, 'base64'); } public Verify(dataToCheck : string, signatureToVerify : string) : boolean { if(!this.keyPair.isPublic()) { console.log("Warning: Tried to verify without a public key being imported!"); return false; } return this.keyPair.verify(dataToCheck, signatureToVerify, undefined, 'base64'); } public GetPublicKey() : string { if(!this.keyPair.isPublic()) { return undefined; } return this.keyPair.exportKey('pkcs1-public-pem'); } public GetPrivateKey() : string { if(!this.keyPair.isPrivate()) { return undefined; } return this.keyPair.exportKey('pkcs1-private-pem'); } }