|
| 1 | +/** |
| 2 | + * @author Matt C [me@mitt.dev] |
| 3 | + * @copyright Crown Copyright 2020 |
| 4 | + * @license Apache-2.0 |
| 5 | + */ |
| 6 | + |
| 7 | +import Operation from "../Operation.mjs"; |
| 8 | +import OperationError from "../errors/OperationError.mjs"; |
| 9 | +import Utils from "../Utils.mjs"; |
| 10 | +import forge from "node-forge/dist/forge.min.js"; |
| 11 | +import { MD_ALGORITHMS } from "../lib/RSA.mjs"; |
| 12 | + |
| 13 | +/** |
| 14 | + * RSA Encrypt operation |
| 15 | + */ |
| 16 | +class RSAEncrypt extends Operation { |
| 17 | + |
| 18 | + /** |
| 19 | + * RSAEncrypt constructor |
| 20 | + */ |
| 21 | + constructor() { |
| 22 | + super(); |
| 23 | + |
| 24 | + this.name = "RSA Encrypt"; |
| 25 | + this.module = "Ciphers"; |
| 26 | + this.description = "Encrypt a message with a PEM encoded RSA public key."; |
| 27 | + this.infoURL = "https://wikipedia.org/wiki/RSA_(cryptosystem)"; |
| 28 | + this.inputType = "string"; |
| 29 | + this.outputType = "ArrayBuffer"; |
| 30 | + this.args = [ |
| 31 | + { |
| 32 | + name: "RSA Public Key (PEM)", |
| 33 | + type: "text", |
| 34 | + value: "-----BEGIN RSA PUBLIC KEY-----" |
| 35 | + }, |
| 36 | + { |
| 37 | + name: "Encryption Scheme", |
| 38 | + type: "argSelector", |
| 39 | + value: [ |
| 40 | + { |
| 41 | + name: "RSA-OAEP", |
| 42 | + on: [2] |
| 43 | + }, |
| 44 | + { |
| 45 | + name: "RSAES-PKCS1-V1_5", |
| 46 | + off: [2] |
| 47 | + }, |
| 48 | + { |
| 49 | + name: "RAW", |
| 50 | + off: [2] |
| 51 | + }] |
| 52 | + }, |
| 53 | + { |
| 54 | + name: "Message Digest Algorithm", |
| 55 | + type: "option", |
| 56 | + value: Object.keys(MD_ALGORITHMS) |
| 57 | + } |
| 58 | + ]; |
| 59 | + } |
| 60 | + |
| 61 | + /** |
| 62 | + * @param {string} input |
| 63 | + * @param {Object[]} args |
| 64 | + * @returns {string} |
| 65 | + */ |
| 66 | + run(input, args) { |
| 67 | + const [pemKey, scheme, md] = args; |
| 68 | + |
| 69 | + if (pemKey.replace("-----BEGIN RSA PUBLIC KEY-----", "").length === 0) { |
| 70 | + throw new OperationError("Please enter a public key."); |
| 71 | + } |
| 72 | + try { |
| 73 | + // Load public key |
| 74 | + const pubKey = forge.pki.publicKeyFromPem(pemKey); |
| 75 | + // Encrypt message |
| 76 | + const eMsg = pubKey.encrypt(input, scheme, {md: MD_ALGORITHMS[md].create()}); |
| 77 | + return Utils.strToArrayBuffer(eMsg); |
| 78 | + } catch (err) { |
| 79 | + if (err.message === "RSAES-OAEP input message length is too long.") { |
| 80 | + throw new OperationError(`RSAES-OAEP input message length (${err.length}) is longer than the maximum allowed length (${err.maxLength}).`); |
| 81 | + } |
| 82 | + throw new OperationError(err); |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | +} |
| 87 | + |
| 88 | +export default RSAEncrypt; |
0 commit comments