vue使用crypto-js对数据进行加解密
1, 创建DES加密和解密方法
// 导入
import CryptoJS from 'crypto-js'
/**
* DES加密函数
* data: 需要加密的数据
* key: 加密的key
* */
export function encrypt(data, key = '123456') {
// 将密钥转换为UTF-8编码的字节数组
key = CryptoJS.enc.Utf8.parse(key);
// 使用DES算法对数据进行加密
var encrypted = CryptoJS.DES.encrypt(data, key, {
iv: '', // 初始化向量为空
mode: CryptoJS.mode.ECB, // 使用ECB模式
padding: CryptoJS.pad.Pkcs7 // 使用PKCS7填充方式
});
return encrypted.toString(); // 返回加密后的字符串
}
/**
* DES解密函数
* content: 需要解密的数据
* key: 解密用的key
*/
export function decrypt(content, key = '123456') {
// 将密钥转换为UTF-8编码的字节数组
key = CryptoJS.enc.Utf8.parse(key);
// 使用DES算法对内容进行解密
// 去除换行符
var bytes = CryptoJS.DES.decrypt(content.replace(/(\r\n|\n|\r)/gm, ""), key, {
iv: '', // 初始化向量为空
mode: CryptoJS.mode.ECB, // 使用ECB模式
padding: CryptoJS.pad.Pkcs7 // 使用PKCS7填充方式
});
// 将解密后的字节数组转换为UTF-8编码的字符串,并返回
var decryptResult = bytes.toString(CryptoJS.enc.Utf8);
return decryptResult.toString();
}`
2, 在页面中使用
```java
imoport {encrypt, decrypt} from '@/uitls/index.js'
export script{
data(){
return {
list: [
{
label: '需要加密的数据',
key: 'test1',
password: '123456'
}
]
}
},
methods: {
// 循环list加密
loopEncryption(){
this.list.forEach(item=>{
item.password = encrypt(item.password, item.key)
})
},
// 循环list解密
loopDecrypt(){
this.list.forEach(item=>{
item.password = decrypt(item.password, item.key)
})
}
}
}