Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use CryptoJS with Angular 4

When I was not using Angular 4, I would just put the script tags for the library. Even when I put the script tags in the index.html file it is not recognizing CryptoJS. Is there a way to use the library or a Angular equivalent?

like image 919
ecain Avatar asked Jul 12 '17 23:07

ecain


People also ask

What is CryptoJS used for?

CryptoJS is a growing collection of standard and secure cryptographic algorithms implemented in JavaScript using best practices and patterns. They are fast, and they have a consistent and simple interface.

What is IV in CryptoJS?

In case of AES-256 - block size is, obviously, 256 bits, which is 32 bytes, which is exactly what you get by CryptoJS. enc. Base64. parse() of 22 byte Base64 string. According to specification and algorithm, IV is exactly block size length, which is 32 bytes with AES-256.


2 Answers

Install using NPM and import below statement in you component file.

npm install crypto-js

import * as crypto from 'crypto-js';

now you can use crypto in your component file.

like image 200
CharanRoot Avatar answered Oct 21 '22 18:10

CharanRoot


Use following command to install cryptoJS

npm install crypto-js --save

You can then build a AESEncryptDecryptService service.

import { Injectable } from '@angular/core';
import * as CryptoJS from 'crypto-js';

@Injectable({
  providedIn: 'root'
})
export class AESEncryptDecryptService {

  secretKey = "YourSecretKeyForEncryption&Descryption";
  constructor() { }

  encrypt(value : string) : string{
    return CryptoJS.AES.encrypt(value, this.secretKey.trim()).toString();
  }

  decrypt(textToDecrypt : string){
    return CryptoJS.AES.decrypt(textToDecrypt, this.secretKey.trim()).toString(CryptoJS.enc.Utf8);
  }
}

In your component, Import & Inject this service

import { AESEncryptDecryptService } from '../services/aesencrypt-decrypt.service'; 


constructor(private _AESEncryptDecryptService: AESEncryptDecryptService) { }

Use encrypt / decrypt functions

let encryptedText = _self._AESEncryptDecryptService.encrypt("Hello World");
let decryptedText = _self._AESEncryptDecryptService.decrypt(encryptedText);
like image 22
Yogesh Chaudhari Avatar answered Oct 21 '22 20:10

Yogesh Chaudhari