在前端登录记住密码的时候需要前端来进行加密工作,接触到crypto这个js,使用还算简单,在这里记录一下
在vue框架中
安装crypto-js
npm install crypto-js --save-dev
utils.js
import CryptoJS from 'crypto-js'
/**
* 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保持一致
网友评论