All files / lib/Service PassmanCrypto.js

81.81% Statements 18/22
75% Branches 6/8
42.85% Functions 3/7
81.81% Lines 18/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59  3x 6x   3x 3x 3x 3x 3x   3x                       3x           3x                 3x           75x 75x 75x             3x 6x 6x     3x  
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PassmanCrypto = void 0;
const node_forge_1 = __importDefault(require("node-forge"));
const sjcl_1 = __importDefault(require("sjcl"));
const js_base64_1 = require("js-base64");
class PassmanCrypto {
    static generateRSAKeypair = (keyLength = 2048) => {
        return new Promise(function (resolve, reject) {
            // generate an RSA key pair asynchronously (uses web workers if available)
            // use workers: -1 to run a fast core estimator to optimize # of workers
            node_forge_1.default.pki.rsa.generateKeyPair({
                bits: keyLength,
                workers: 2
            }, (error, keypair) => {
                resolve({ error, keypair });
            });
        });
    };
    static rsaKeyPairToPEM = (keypair) => {
        return {
            privateKey: node_forge_1.default.pki.privateKeyToPem(keypair.privateKey),
            publicKey: node_forge_1.default.pki.publicKeyToPem(keypair.publicKey)
        };
    };
    static sjcl_encryption_config = {
        adata: "",
        iter: 1000,
        ks: 256,
        mode: 'ccm',
        ts: 64,
        //salt: [],
        //iv: []
    };
    static encryptString = (plainText, key) => {
        // todo: think about replacing aes-ccm from sjcl with the more modern and faster aes-gcm from forge
        // see https://crypto.stackexchange.com/questions/6842/how-to-choose-between-aes-ccm-and-aes-gcm-for-storage-volume-encryption
        // see https://github.com/digitalbazaar/forge#cipher
        // todo: try to use aes-ccm from jscrypto instead of the very outdated sjcl
        // see https://github.com/Hinaser/jscrypto/blob/master/API.md#aes
        let rp = {};
        const ct = sjcl_1.default.encrypt(key, plainText, PassmanCrypto.sjcl_encryption_config, rp);
        return js_base64_1.Base64.btoa(ct);
    };
    /**
     * @param b64EncCiphertext
     * @param key
     * @throws untyped sjcl exceptions
     */
    static decryptString = (b64EncCiphertext, key) => {
        const ciphertext = js_base64_1.Base64.atob(b64EncCiphertext);
        return sjcl_1.default.decrypt(key, ciphertext);
    };
}
exports.PassmanCrypto = PassmanCrypto;