Angular使用crypto-js进行DES加密

一、首先需下载大包:npm install crypto-js

二、然后下载ts版本包:npm install --save @types/crypto-js

三、示例代码:

import { Injectable } from "@angular/core";
import { DES, mode, pad, enc } from 'crypto-js';

@Injectable()
export class CryptUtil {
  private keyHex: string;//密钥
  constructor() {
    this.keyHex = enc.Utf8.parse('LSand2019');
  }

  /**
   * DES加密
   * @param {string} data 待加密字符串
   * @description 用于对字符串加密
   * @return {String} 加密后的字符串
   */
  desEncrypt(data: string): string {
    let encrypted = DES.encrypt(datathis.keyHex, {
      mode: mode.ECB,
      padding: pad.Pkcs7
    })
    return encrypted.toString();
  }

  /**
   * DES解密
   * @param {String} data 待解密字符串
   * @description 用于对加密串的解密
   * @return {String} 解密后的字符串
   */
  desDecrypt(data: string): string {
    let decrypted = DES.decrypt(datathis.keyHex, {
      mode: mode.ECB,
      padding: pad.Pkcs7
    })
    return enc.Utf8.stringify(decrypted);
  }

}

四、效果演示:

console.log("des加密123456结果:"this.cryptUtil.desEncrypt('123456'));
console.log("des解密olCPKgwi0rk=结果:"this.cryptUtil.desDecrypt('olCPKgwi0rk='));
 
原文地址:https://www.cnblogs.com/54hsh/p/12755574.html