angular使用md5CryptoJS-des加密

13次阅读

共计 1347 个字符,预计需要花费 4 分钟才能阅读完成。

在业务系统中,通常需要对用户的密码进行加密,再时行 http 的请求。加强系统登录的安全验证。

常用的加密方式有 MD5, Base64, CryptoJS 的 AES DES 等。下面介绍我常用的几种加密方法的使用:

MD5 加密

1. 安装模块 ts-md5

$ npm install ts-md5 --save

2. 使用 md5 进行加密

import {Md5} from 'ts-md5';
// ...

// 密码
password: string = "12345";

// 加密方法 - md5 加密
decode() {const passwordMd5 = Md5.hashStr(this.password).toString(); // 结果:827ccb0eea8a706c4c34a16891f84e7b}

Base64 加密

1. 安装模块 js-base64

$ npm install js-base64 --save

2. 使用 md5 进行加密

import {Base64} from 'js-base64';
// ...

// 密码
password: string = "12345";

// 加密方法 - Base64 加密
decode() {const passwordBase64 = Base64.encode(password); // 结果:MTIzNDU=
}

DES 加密

DES 对称加密,是一种比较传统的加密方式,其加密运算、解密运算使用的是同样的密钥 key,信息的发送者和信息的接收者在进行信息的传输与处理时,必须共同持有该密码(称为对称密码),是一种对称加密算法。

crypto-js Github: https://github.com/brix/crypt…

1. 安装模块 crypto-js

$ npm install crypto-js --save

2. 使用 DES 进行加密

import CryptoJS from 'crypto-js';
// ...

// 密钥
key: string = "abcdefg";
// 密码
password: string = "12345";

// 加密方法 - des 加密
decode() {
    // key 编码 
    const keyHex = CryptoJS.enc.Utf8.parse(this.key);
    console.log(keyHex.toString()); // 结果:61626364656667
    // 加密
    const passwordDES = CryptoJS.DES.encrypt(this.password, keyHex, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    }).toString();
    console.log(passwordDES); // 结果:zYGeIdaZpEM=
}

3. 使用 AES 进行加密

加密用法基本与 des 一致。

import CryptoJS from 'crypto-js';
// ...

// 密钥
key: string = "abcdefg";
// 密码
password: string = "12345";

// 加密方法 - des 加密
decode() {
    // 加密
    const passwordDES = CryptoJS.AES.encrypt(this.password, this.key).toString();
    console.log(passwordDES); 
}

正文完
 0