【问题标题】:How to use CryptoJS with Angular 4如何在 Angular 4 中使用 CryptoJS
【发布时间】:2017-07-12 23:11:10
【问题描述】:

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

【问题讨论】:

    标签: angular cryptojs


    【解决方案1】:

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

    npm install crypto-js
    
    import * as crypto from 'crypto-js';
    

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

    【讨论】:

    • 我还要添加npm install @types/crypto-js 来拥有类型
    【解决方案2】:

    使用以下命令安装cryptoJS

    npm install crypto-js --save
    

    然后您可以构建 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);
      }
    }
    

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

    import { AESEncryptDecryptService } from '../services/aesencrypt-decrypt.service'; 
    
    
    constructor(private _AESEncryptDecryptService: AESEncryptDecryptService) { }
    

    使用加密/解密函数

    let encryptedText = _self._AESEncryptDecryptService.encrypt("Hello World");
    let decryptedText = _self._AESEncryptDecryptService.decrypt(encryptedText);
    

    【讨论】:

    • 这行得通!此外,我必须为 Typescript 运行 npm i --save-dev @types/crypto-js
    • 使用_self的目的是什么?
    【解决方案3】:

    文档位于https://cryptojs.gitbook.io/docs/ Angular 6 的导入应如下所示:

    import * as cryptoJS from 'crypto-js';
    

    【讨论】:

      猜你喜欢
      • 2017-04-23
      • 2017-11-26
      • 2019-01-02
      • 2019-11-07
      • 1970-01-01
      • 2018-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多