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?
Asked
Active
Viewed 6.0k times
3 Answers
56
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.

CharanRoot
- 6,181
- 2
- 27
- 45
-
12I'd also add `npm install @types/crypto-js` to have types – igor_c Aug 20 '19 at 11:17
-
this one worked for me on angular 14 **npm install @types/crypto-js** – Aazad R khan Dec 08 '22 at 04:42
26
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);

Yogesh Chaudhari
- 459
- 5
- 7
-
2This works! Additionally I had to run `npm i --save-dev @types/crypto-js` for Typescript – chris Mar 25 '22 at 15:54
-
-
It's been a long time since I posted this code. However, I believe I had assigned the reference of `this` to `_self` because this code was being called in the callback function where I was losing the reference of the class that imported the service. – Yogesh Chaudhari Jul 01 '22 at 13:57
0
Documentation is at https://cryptojs.gitbook.io/docs/ The import for Angular 6 should be the following:
import * as cryptoJS from 'crypto-js';

Steve Klock
- 115
- 1
- 8