简体   繁体   English

如何在 Angular 4 中使用 CryptoJS

[英]How to use CryptoJS with Angular 4

When I was not using Angular 4, I would just put the script tags for the library.当我不使用 Angular 4 时,我只会为库script标签。 Even when I put the script tags in the index.html file it is not recognizing CryptoJS .即使我将script标签放在index.html文件中,它也无法识别CryptoJS Is there a way to use the library or a Angular equivalent?有没有办法使用库或 Angular 等效项?

Install using NPM and import below statement in you component file.使用 NPM 安装并在组件文件中导入以下语句。

npm install crypto-js

import * as crypto from 'crypto-js';

now you can use crypto in your component file.现在您可以在组件文件中使用加密。

Use following command to install cryptoJS使用以下命令安装 cryptoJS

npm install crypto-js --save

You can then build a AESEncryptDecryptService service.然后您可以构建AESEncryptDecryptService服务。

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

Documentation is at https://cryptojs.gitbook.io/docs/ The import for Angular 6 should be the following:文档位于https://cryptojs.gitbook.io/docs/ Angular 6 的导入应如下所示:

import * as cryptoJS from 'crypto-js';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM