Use cookies and crypto-js in vue to remember passwords and encryption

Use crypto-js encryption and decryption


The first step is to install

npm install crypto-js

The second step is to import in the vue component you need

import CryptoJS from “crypto-js”;

The third step is to use

    // 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'

Note that this mymessage is a string, if you want to encrypt the user id (number type), you must first convert it into a string

For more usage, please visit the official document

Remember password

  1. The realization principle is that when logging in, if you check the remember password (save the "remember password" state to localstorage), save the account password to cookies;
  2. After entering the login page, judge whether the password is remembered (judging from localstorage), if the password is remembered, export cookies to the form;

The setcookie method is used for saving, and the getcookie method is used for taking out.
ok, let's write the method

//设置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);
          } 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); 
    }

The method of login is as follows:

 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 => {
    
    
          //----
        });
    },

Finally, it is necessary to determine whether the user has remembered the password in the created hook function to perform related operations

//判断是否记住密码
//**注意这里的true是字符串格式,因为Boolean存进localstorage中会变成String**
 created() {
    
    
    //判断是否记住密码
    if (localStorage.getItem("rememberPsw") == 'true') {
    
    
      this.getCookie();
    }
  }

Finally, the interface is posted, where rememberPsw is the v-model value of the remember password button, currentPortId is the v-model value of the first box, and password is the v-model value of the second box.

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_43248623/article/details/108419391