使用crypto-js加解密
npm install crypto-js
import CryptoJS from “crypto-js”;
<el-form-item style="margin-bottom:0;border:0;">
<el-checkbox v-model="checked">Remember Password</el-checkbox>
</el-form-item>
<el-button
:loading="loading"
type="primary"
class="account-button"
@click.native.prevent="handleLogin"
>Sign In
</el-button>
loginForm: {
username: "",
password: ""
},
checked: true,
mounted() {
this.getCookie();
},
methods: {
handleLogin() {
this.$refs.loginForm.validate(valid => {
if (valid) {
if (this.checked === true) {
this.setCookie(this.loginForm.username, this.loginForm.password, 15);
} else {
this.clearCookie();
}
} else {
return false;
}
});
},
//设置cookie
setCookie(c_name, c_pwd, exdays) {
const text = CryptoJS.AES.encrypt(c_pwd, 'secret key 123');//使用CryptoJS方法加密
const exdate = new Date();
exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays);
//字符串拼接cookie
window.document.cookie =
"userName" + "=" + c_name + ";path=/;expires=" + exdate.toGMTString();
window.document.cookie =
"userPwd" + "=" + text + ";path=/;expires=" + exdate.toGMTString();
},
getCookie: function () {
if (document.cookie.length > 0) {
const arr = document.cookie.split("; ");
for (let i = 0; i < arr.length; i++) {
const arr2 = arr[i].split("=");
if (arr2[0] === "userName") {
this.loginForm.username = arr2[1];
} else if (arr2[0] === "userPwd") {
const bytes = CryptoJS.AES.decrypt(arr2[1].toString(), 'secret key 123');
const plaintext = bytes.toString(CryptoJS.enc.Utf8); //拿到解密后的密码(登录时输入的密码)
this.loginForm.password = plaintext;
}
}
}
},
//清除cookie
clearCookie: function () {
this.setCookie("", "", -1);
},
}