How to use CryptoJS with Angular 4

后端 未结 3 1174
礼貌的吻别
礼貌的吻别 2020-12-30 02:54

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 fi

3条回答
  •  一向
    一向 (楼主)
    2020-12-30 03:08

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

提交回复
热议问题