Hello I am trying to implement encryption in my application. I am using angular (angular-4) for the frontend and node js for the backend. Communication is done through socke
I used CryptoJS for AES encoding. And, node-forge for RSA encoding.
Part 1:
npm install --save node-forge
npm install --save crypto-js
npm install --save @types/crypto-js
npm install --save @types/node-forge
import { Injectable } from '@angular/core';
import * as forge from 'node-forge';
import * as CryptoJS from 'crypto-js';
/*
* forge: For RSA encryption
* CryptoJS: For AES encryption
*/
export interface AESKeys {
iv: string;
key: string;
}
@Injectable()
export class MyEncryptService {
constructor() {}
/**
* @param randomWordArray
* AES Key or IV generated in this service as Hex string
* @param pemKey
* the Public Key from "get_rsa_key" endpoint (separate http service)
* @returns
* a RSA encrypted random key/iv
*/
public getBase64Encrypted(randomWordArray, pemKey): string {
const pk = forge.pki.publicKeyFromPem(pemKey);
return forge.util.encode64(pk.encrypt(forge.util.hexToBytes(randomWordArray)));
}
/**
* @param text
* field input text
* @param randomKey
* random key generated from word array
* @param randomIv
* random iv generated from word array
* @returns
* encrypted text
*/
public encrypted(text, randomKey, randomIv): string {
const cipherText: any = CryptoJS.AES.encrypt(text, randomKey, {
iv: randomIv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.NoPadding
});
return cipherText.toString();
}
/**
* @param wordLength
* normally: IV = 16 or Key = 32
* @returns
* randomly generated 128bit (IV) or 256bit (Key) word array
*/
public getWordArray(wordLength): string {
return CryptoJS.lib.WordArray.random(wordLength);
}
}