在前端登录记住密码的时候需要前端来进行加密工作,接触到crypto这个js,使用还算简单,在这里记录一下
在vue框架中
安装crypto-js
npm install crypto-js --save-dev
utils.js
import CryptoJS from 'crypto-js'
function getAesString(data,key,iv){//加密
var key = CryptoJS.enc.Utf8.parse(key);
var iv = CryptoJS.enc.Utf8.parse(iv);
var encrypted =CryptoJS.AES.encrypt(data,key,
{
iv:iv,
mode:CryptoJS.mode.CBC,
padding:CryptoJS.pad.Pkcs7
});
return encrypted.toString(); //返回的是base64格式的密文
}
function getDAesString(encrypted,key,iv){//解密
var key = CryptoJS.enc.Utf8.parse(key);
var iv = CryptoJS.enc.Utf8.parse(iv);
var decrypted =CryptoJS.AES.decrypt(encrypted,key,
{
iv:iv,
mode:CryptoJS.mode.CBC,
padding:CryptoJS.pad.Pkcs7
});
return decrypted.toString(CryptoJS.enc.Utf8);
}
/**
* CryptoJS加密
*/
var getAES = function(data){ //加密
var key = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; //密钥
var iv = '1234567812345678';
var encrypted = getAesString(data,key,iv); //密文
var encrypted1 = CryptoJS.enc.Utf8.parse(encrypted);
return encrypted;
}
/**
* CryptoJS解密
*/
var getDAes = function(data){//解密
var key = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; //密钥
var iv = '1234567812345678';
var decryptedStr = getDAesString(data,key,iv);
return decryptedStr;
}
/**
* 存储localStorage
*/
var setStore = (name, content) => {
if (!name) return;
if (typeof content !== 'string') {
content = JSON.stringify(content);
}
window.localStorage.setItem(name, content);
}
/**
* 获取localStorage
*/
var getStore = name => {
if (!name) return;
return window.localStorage.getItem(name);
}
/**
* 删除localStorage
*/
var removeStore = name => {
if (!name) return;
window.localStorage.removeItem(name);
}
export default {
getAES,
getDAes,
setStore,
getStore,
removeStore
}
component
<script>
import utils from '@/utils';
export default {
methods: {
remember() {
try {
let data = utils.getAES(JSON.stringify(this.formData));
utils.setStore('loginInfo', data);
} catch (err) {
console.log(err)
}
},
getRemember() {
try {
let crptyData = utils.getStore('loginInfo');
if (crptyData) {
let data = utils.getDAes(crptyData);
this.formData = JSON.parse(data);
} else {}
} catch (err) {
console.error(err.message);
}
},
notRemember() {
let data = utils.getStore('loginInfo');
if (data) {
utils.removeStore('loginInfo');
}
}
}
}
</script>
key和iv都可以更换,但是需要保证的是加解密的key和iv保持一致