1. 概述
1.1 說明
crypto-js(GitHub)是谷歌開發的一個純JavaScript的加密算法類庫,可以非常方便的在前端進行其所支持的加解密操作。目前crypto-js已支持的算法有:MD5,SHA-1,SHA-256,AES,Rabbit,MARC4,HMAC,HMAC-MD5,HMAC-SHA1,HMAC-SHA256,PBKDF2。常用的加密方式有MD5和AES,使用時可以引用總文件,也可以單獨引用某一文件。
1.2 使用方式
直接引用:引入crypto-js文件。
安裝依賴:npm install crypto-js import CryptoJS from 'crypto-js'。
2. 示例
2.1 AES加解密(VUE項目)

<template>
<div style="width: 600px; margin: 0 auto">
<el-row>
<el-col :span="10">
<el-row>
<el-col :span="24">明文內容</el-col>
</el-row>
<el-row>
<el-col :span="24">
<el-input v-model="content" type="textarea" :rows="8"></el-input>
</el-col>
</el-row>
</el-col>
<el-col :span="4">
<div style="margin-top: 60px;">
<el-row style="margin-bottom: 10px;">
<el-col :span="24">
<el-button type="primary" @click="encryptFunction">加密</el-button>
</el-col>
</el-row>
<el-row>
<el-col :span="24">
<el-button type="primary" @click="unEncryptFunction">解密</el-button>
</el-col>
</el-row>
</div>
</el-col>
<el-col :span="10">
<el-row>
<el-col :span="24">密文內容</el-col>
</el-row>
<el-row>
<el-col :span="24">
<el-input v-model="encryptContent" type="textarea" :rows="8"></el-input>
</el-col>
</el-row>
</el-col>
</el-row>
</div>
</template>
<script>
import CryptoJS from 'crypto-js'
export default {
data() {
return {
content: null,
encryptContent: null,
encryptSecretKey: null
}
},
methods: {
/**
* 加密方法
**/
encryptFunction: function () {
this.$data.encryptSecretKey=null;
let objEncrypt = null;
objEncrypt = this.encryptByAES(this.$data.content);
if (objEncrypt) {
this.$data.encryptContent = objEncrypt.encryptContent;
this.$data.encryptSecretKey = objEncrypt.encryptSecretKey;
}
},
/**
* aes加密
* @param strEncrypt:需要加密的內容
* @return 返回加密后的內容與加密密鑰
**/
encryptByAES: function (strEncrypt) {
let aesSecretKey = '';//16長度隨機字符串
do {
aesSecretKey = Math.random().toString(36).substr(2) + Math.random().toString(36).substr(Math.floor(Math.random() * (12 - 5 + 1) + 5))
} while (aesSecretKey.length != 16);
let aesSecretUtf8 = CryptoJS.enc.Utf8.parse(aesSecretKey);
const iv = CryptoJS.enc.Base64.parse('******KKKKKKKKKKKKKKKKK******');
let aesEncrypt = CryptoJS.AES.encrypt(strEncrypt, aesSecretUtf8, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
let objReturn = {
encryptContent: aesEncrypt.toString(),
encryptSecretKey: aesSecretKey
};
return objReturn;
},
/**
* 解密方法
**/
unEncryptFunction: function () {
this.$data.content=this.unEncryptByAES( this.$data.encryptContent,this.$data.encryptSecretKey)
},
/**
* aes加密
* @param strEncrypt:需要解密的內容
* @param keyEncrypt:加密時用到的密鑰
* @return 返回解密后的內容
**/
unEncryptByAES: function (strEncrypt,keyEncrypt) {
let aesSecretUtf8 = CryptoJS.enc.Utf8.parse(keyEncrypt);
const iv = CryptoJS.enc.Base64.parse('******KKKKKKKKKKKKKKKKK******');
let aesUnEncrypt =CryptoJS.AES.decrypt(strEncrypt,aesSecretUtf8,
{
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
return aesUnEncrypt.toString(CryptoJS.enc.Utf8);
},
}
}
</script>
注意:加解密時,所使用的偏移量iv必須相同。
2.2 MD5
this.$data.encryptContent=CryptoJS.MD5(this.$data.content);
