vue中使用cookies和crypto-js實現記住密碼和加密
阿新 • • 發佈:2018-12-10
不多BB,搞快、搞快、
使用crypto-js加解密
第一步,安裝
npm install crypto-js
第二步,在你需要的vue元件內import
import CryptoJS from "crypto-js";
第三步,使用
// Encrypt 加密 var cipherText = CryptoJS.AES.encrypt( "my message", "secretkey123" ).toString(); console.log(cipherText) // Decrypt 解密 var bytes = CryptoJS.AES.decrypt(cipherText, "secretkey123"); var originalText = bytes.toString(CryptoJS.enc.Utf8); console.log(originalText); // 'my message'
注意這個mymessage是字串,如果你要加密的使用者id(number型別)得先轉成字串
更多使用請訪問官方文件
記住密碼
- 實現原理是登入的時候,如果勾選了記住密碼(把‘記住密碼’狀態儲存到localstorage)就儲存賬號密碼到cookies;
- 之後進入登入頁面的時候,判斷是否記住了密碼(從localstorage判斷),如果記住密碼則匯出cookies到表單;
其中儲存使用setcookie方法,取出則使用getcookie方法。ok,我們來編寫方法
//設定cookie setCookie(portId, psw, exdays) { // Encrypt,加密賬號密碼 var cipherPortId = CryptoJS.AES.encrypt( portId+'', "secretkey123" ).toString(); var cipherPsw = CryptoJS.AES.encrypt(psw+'', "secretkey123").toString(); console.log(cipherPortId+'/'+cipherPsw)//列印一下看看有沒有加密成功 var exdate = new Date(); //獲取時間 exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //儲存的天數 //字串拼接cookie,為什麼這裡用了==,因為加密後的字串也有個=號,影響下面getcookie的字串切割,你也可以使用更炫酷的符號。 window.document.cookie = "currentPortId" + "==" + cipherPortId + ";path=/;expires=" + exdate.toGMTString(); window.document.cookie = "password" + "==" + cipherPsw + ";path=/;expires=" + exdate.toGMTString(); }, //讀取cookie getCookie: function() { if (document.cookie.length > 0) { var arr = document.cookie.split("; "); //這裡顯示的格式請根據自己的程式碼更改 for (var i = 0; i < arr.length; i++) { var arr2 = arr[i].split("=="); //根據==切割 //判斷查詢相對應的值 if (arr2[0] == "currentPortId") { // Decrypt,將解密後的內容賦值給賬號 var bytes = CryptoJS.AES.decrypt(arr2[1], "secretkey123"); this.currentPortId = bytes.toString(CryptoJS.enc.Utf8)-0; } else if (arr2[0] == "password") { // Decrypt,將解密後的內容賦值給密碼 var bytes = CryptoJS.AES.decrypt(arr2[1], "secretkey123"); this.password = bytes.toString(CryptoJS.enc.Utf8); } } } }, //清除cookie clearCookie: function() { this.setCookie("", "", -1); }
登入的方法如下:
login() { this.$http //請根據實際情況修改該方法 .post(...) .then(res => { if (res.data.code == "success") { if (this.rememberPsw == true) { //判斷使用者是否勾選了記住密碼選項rememberPsw,傳入儲存的賬號currentPortId,密碼password,天數30 this.setCookie(this.currentPortId, this.password, 30); }else{ this.clearCookie(); } //這裡是因為要在created中判斷,所以使用了localstorage比較簡單,當然你也可以直接根據cookie的長度or其他騷操作來判斷有沒有記住密碼。 localStorage.setItem("rememberPsw", this.rememberPsw); } else { //---- } }) .catch(err => { //---- }); },
最後要在created方法內判斷使用者是否記住了密碼來執行相關的操作
//判斷是否記住密碼
//**注意這裡的true是字串格式,因為Boolean存進localstorage中會變成String**
if (localStorage.getItem("rememberPsw") == 'true') {
this.rememberPsw = true;
this.getCookie();
}
最後,介面貼上,其中rememberPsw是記住密碼按鈕的v-model值,currentPortId是第一個框的v-model值,password就是第二個框的v-model值啦。
最後
我也是一個新手,寫得不好的地方請輕噴~有好的建議也可以評論告訴下~謝謝大家