JavaScript加解密库(crypto-js)
1. 概述
1.1 说明
crypto-js()是⾕歌开发的⼀个纯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 >
<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 >
<el-row >
<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>
字符串长度js</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.$ptSecretKey=null;
let objEncrypt = null;
objEncrypt = ptByAES(this.$t);
if (objEncrypt) {
this.$ptContent = ptContent;
this.$ptSecretKey = ptSecretKey;
}
},
/**
* 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 = Utf8.parse(aesSecretKey);
const iv = Base64.parse('******KKKKKKKKKKKKKKKKK******');
let aesEncrypt = pt(strEncrypt, aesSecretUtf8, {
iv: iv,
mode: de.CBC,
padding: CryptoJS.pad.Pkcs7
});
let objReturn = {
encryptContent: String(),
encryptSecretKey: aesSecretKey
};
return objReturn;
},
/**
* 解密⽅法
**/
unEncryptFunction: function () {
this.$t=this.unEncryptByAES( this.$ptContent,this.$ptSecretKey)
},
/**
* aes加密
* @param strEncrypt:需要解密的内容
* @param keyEncrypt:加密时⽤到的密钥
* @return 返回解密后的内容
**/
unEncryptByAES: function (strEncrypt,keyEncrypt) {
let aesSecretUtf8 = Utf8.parse(keyEncrypt);
const iv = Base64.parse('******KKKKKKKKKKKKKKKKK******');
let aesUnEncrypt =CryptoJS.AES.decrypt(strEncrypt,aesSecretUtf8,
{
iv: iv,
mode: de.CBC,
padding: CryptoJS.pad.Pkcs7
});
Utf8);
},
}
}
</script>
注意:加解密时,所使⽤的偏移量iv必须相同。
2.2 MD5
this.$ptContent=CryptoJS.MD5(this.$t);
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论