在前端登錄記住密碼的時(shí)候需要前端來(lái)進(jìn)行加密工作,接觸到crypto這個(gè)js芦疏,使用還算簡(jiǎn)單,在這里記錄一下
在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;
}
/**
* 存儲(chǔ)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保持一致