How to use CryptoJS with Angular 4

十年热恋 提交于 2019-12-20 11:52:53

问题


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?


回答1:


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.




回答2:


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);



回答3:


Documentation is at https://cryptojs.gitbook.io/docs/ The import for Angular 6 should be the following:

import * as cryptoJS from 'crypto-js';


来源:https://stackoverflow.com/questions/45068925/how-to-use-cryptojs-with-angular-4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!