crypto-js(GitHub)是谷歌開發的一個純JavaScript的加密算法類庫,能夠很是方便的在前端進行其所支持的加解密操做。目前crypto-js已支持的算法有:MD5,SHA-1,SHA-256,AES,Rabbit,MARC4,HMAC,HMAC-MD5,HMAC-SHA1,HMAC-SHA256,PBKDF2。經常使用的加密方式有MD5和AES,使用時能夠引用總文件,也能夠單獨引用某一文件。前端
直接引用:引入crypto-js文件。git
安裝依賴:npm install crypto-js import CryptoJS from 'crypto-js'。github
<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必須相同。算法
this.$data.encryptContent=CryptoJS.MD5(this.$data.content);