All files / src/lib encryption.ts

100% Statements 27/27
100% Branches 0/0
100% Functions 5/5
100% Lines 27/27

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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75  1x   1x   1x   1x   1x   1x             4x 4x 64x       4x                   2x 2x 2x         2x 2x 2x       2x 2x 2x 2x             2x     1x       2x 2x 2x 2x 2x            
// @ts-ignore
import JSEncrypt from './js-encrypt.js';
// @ts-ignore
const AES = require('crypto-js/aes');
// @ts-ignore
const ENC_UTF8 = require('crypto-js/enc-utf8');
// @ts-ignore
const ENC_BASE64 = require('crypto-js/enc-base64');
// @ts-ignore
const CTR_MODE = require('crypto-js/mode-ctr');
// @ts-ignore
const PAD_NOPADDING = require('crypto-js/pad-nopadding');
export interface RSACipherOb {
    cipherText: string;
    iv: string;
    secretKey: string;
}
function generateRandomBytes (byteLength: number): string {
    let result = '';
    while (result.length < byteLength) {
        result += Math.random()
            .toString(36)
            .substr(2, 1);
    }
    return result;
}
 
function aesEncrypt (
    plaintext: string,
    keyString: string,
    ivString: string,
    mode: any,
    padding: any
): string {
    const key = ENC_UTF8.parse(keyString);
    const iv = ENC_UTF8.parse(ivString);
    const cipherResult = AES.encrypt(plaintext, key, {
        mode: mode,
        padding: padding,
        iv: iv
    });
    const ciphertext = cipherResult.ciphertext;
    const ciphertextBase64 = ciphertext.toString(ENC_BASE64);
    return ciphertextBase64;
}
 
function rsaEncrypt (plaintext: string, publicKey: string): string {
    const en = new JSEncrypt();
    en.setPublicKey(publicKey);
    const cipher = en.encrypt(plaintext);
    return cipher;
}
 
/**
 * AES-128-CTR
 */
function ctrEncrypt (plaintext: string, keyString: string, ivString: string): string {
    return aesEncrypt(plaintext, keyString, ivString, CTR_MODE, PAD_NOPADDING);
}
 
export function encryptByRSA (
    plaintext: string,
    publicKey: string
): RSACipherOb {
    const iv = generateRandomBytes(16);
    const aesKey = generateRandomBytes(16);
    const cipherText = ctrEncrypt(plaintext, aesKey, iv);
    const secretKey = rsaEncrypt(aesKey, publicKey);
    return {
        cipherText,
        iv,
        secretKey
    };
}