如何在 Angular 4 中使用 CryptoJS
How to use CryptoJS with Angular 4
当我不使用 Angular 4 时,我会为库添加 script
标签。即使我将 script
标签放入 index.html
文件中,它也无法识别 CryptoJS
。有没有办法使用图书馆或 Angular 等价物?
使用 NPM 安装并在组件文件中导入以下语句。
npm install crypto-js
import * as crypto from 'crypto-js';
现在您可以在组件文件中使用加密。
使用以下命令安装 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);
文档位于 https://cryptojs.gitbook.io/docs/ Angular 6 的导入应如下所示:
import * as cryptoJS from 'crypto-js';
当我不使用 Angular 4 时,我会为库添加 script
标签。即使我将 script
标签放入 index.html
文件中,它也无法识别 CryptoJS
。有没有办法使用图书馆或 Angular 等价物?
使用 NPM 安装并在组件文件中导入以下语句。
npm install crypto-js
import * as crypto from 'crypto-js';
现在您可以在组件文件中使用加密。
使用以下命令安装 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);
文档位于 https://cryptojs.gitbook.io/docs/ Angular 6 的导入应如下所示:
import * as cryptoJS from 'crypto-js';