1.安装
npm install crypto-js
//或者
yarn add crypto-js
2.引用
import CryptoJS from 'crypto-js'
3.使用
加密方式很多,但是今天我要介绍的却是自定义md5加密,这样可以和后端加密出来的密文一致。如果你的项目也需要这种加密,不妨试一试。
话不多说,直接上代码!
定义封装的方法
setMd5Hash(ciphertext) {
let ct = '';
let i = 0;
for (let v = 0; v < ciphertext.length; ++v) {
let c = ciphertext.charCodeAt(v); // 获取字符的 Unicode 编码值
ct += String(c + i++); // 将字符编码值与 i 相加后转换回字符
}
const md5Cipher = CryptoJS.MD5(ct).toString(CryptoJS.enc.Hex);
return md5Cipher;
},
调用
this.form.data.password = this.setMd5Hash(this.form.data.password);
实现效果: