|
| 1 | +const AES = require('crypto-js/aes.js'); |
| 2 | +const CryptoJS = require('crypto-js/crypto-js.js'); |
| 3 | +/** |
| 4 | + * A class that handles `encryption-*` web events in the renderer process |
| 5 | + * and performs data encryption/decryption. |
| 6 | + * |
| 7 | + * TODO: consider spawning another process for data encryption / decryption. |
| 8 | + * Compare gain/loss on running encryption/decryption in separate process |
| 9 | + * and check whether data passing from process to another process is more costly. |
| 10 | + */ |
| 11 | +class EncryptionService { |
| 12 | + constructor() { |
| 13 | + this._decodeHandler = this._decodeHandler.bind(this); |
| 14 | + this._encodeHandler = this._encodeHandler.bind(this); |
| 15 | + } |
| 16 | + |
| 17 | + listen() { |
| 18 | + window.addEventListener('encryption-decode', this._decodeHandler); |
| 19 | + window.addEventListener('encryption-encode', this._encodeHandler); |
| 20 | + } |
| 21 | + |
| 22 | + unlisten() { |
| 23 | + window.removeEventListener('encryption-decode', this._decodeHandler); |
| 24 | + window.removeEventListener('encryption-encode', this._encodeHandler); |
| 25 | + } |
| 26 | + |
| 27 | + _decodeHandler(e) { |
| 28 | + const { method } = e.detail; |
| 29 | + e.detail.result = this.decode(method, e.detail); |
| 30 | + } |
| 31 | + |
| 32 | + _encodeHandler(e) { |
| 33 | + const { method } = e.detail; |
| 34 | + e.detail.result = this.encode(method, e.detail); |
| 35 | + } |
| 36 | + |
| 37 | + async encode(method, opts) { |
| 38 | + switch (method) { |
| 39 | + case 'aes': return await this.encodeAes(opts.data, opts.passphrase); |
| 40 | + default: throw new Error(`Unknown encryption method`); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + async encodeAes(data, passphrase) { |
| 45 | + // Todo: this looks really dangerous to run file encryption in the main |
| 46 | + // thread (of the renderer process). Consider other options. |
| 47 | + const encrypted = AES.encrypt(data, passphrase); |
| 48 | + return encrypted.toString(); |
| 49 | + } |
| 50 | + |
| 51 | + async decode(method, opts) { |
| 52 | + switch (method) { |
| 53 | + case 'aes': return await this.decodeAes(opts.data, opts.passphrase); |
| 54 | + default: throw new Error(`Unknown decryption method`); |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + async decodeAes(data, passphrase) { |
| 59 | + if (!passphrase === undefined) { |
| 60 | + passphrase = prompt('Enter password to open the file.'); |
| 61 | + } |
| 62 | + const bytes = AES.decrypt(data, passphrase); |
| 63 | + return bytes.toString(CryptoJS.enc.Utf8); |
| 64 | + } |
| 65 | +} |
| 66 | +exports.EncryptionService = EncryptionService; |
0 commit comments