如何在Angular 4中使用CryptoJS

eca*_*ain 16 cryptojs angular

当我不使用Angular 4时,我只会script为库添加标签.即使我将script标签放在index.html文件中也无法识别CryptoJS.有没有办法使用库或Angular等价物?

Cha*_*oot 30

使用NPM安装并在组件文件中导入以下语句.

npm install crypto-js

import * as crypto from 'crypto-js';
Run Code Online (Sandbox Code Playgroud)

现在您可以在组件文件中使用加密.

  • 我还添加了“npm install @types/crypto-js”以具有类型 (7认同)

小智 17

使用以下命令安装cryptoJS

npm install crypto-js --save
Run Code Online (Sandbox Code Playgroud)

然后,您可以构建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);
  }
}
Run Code Online (Sandbox Code Playgroud)

在您的组件中,导入并注入此服务

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


constructor(private _AESEncryptDecryptService: AESEncryptDecryptService) { }
Run Code Online (Sandbox Code Playgroud)

使用加密/解密功能

let encryptedText = _self._AESEncryptDecryptService.encrypt("Hello World");
let decryptedText = _self._AESEncryptDecryptService.decrypt(encryptedText);
Run Code Online (Sandbox Code Playgroud)

  • 这有效!另外,我必须为 Typescript 运行 `npm i --save-dev @types/crypto-js` (2认同)