js parses the data in jwt, converts base64 to json, and points that need attention

jwt front-end analysis

​When we do front-end and back-end separation projects, we need to save jwt on the front end, and sometimes we need to parse the data in jwt. There are many ways to use third-party components on the Internet, but the native method of js can also be solved. Although there are Compatibility and other issues, but a modification is also available.
Our jwt data carrier is encrypted with base64, so we only need to base64 decode the string of the carrier! But
note: the character table corresponding to base64 has a total of 64 characters, including 26 letters of upper and lower case , 10 Arabic numerals, + sign and / sign; attached: (There is also a '=' sign generally used for suffixes). Then for some output in base64 format, some non-compliant characters need to be replaced.

Convert base64 to json

Method 1:
(Generally split the jwt string to get valuable base64 characters to parse)
It can be done like this (the most elegant solution)
need to convert '_', '-' otherwise it will not be parsed

var userinfo = JSON.parse(decodeURIComponent(escape(window.atob('base64字符串'.replace(/-/g, "+").replace(/_/g, "/"))))); //解析,需要吧‘_’,'-'进行转换否则会无法解析

The base64 code for everyone to test:

eyJzdWIiOiJkZWZhdWx0IiwidXBuIjoiYWRtaW4iLCJpc3MiOiJDTj10aG9yb3VnaCIsImlhdCI6MTY4NDE0NzUwNSwiZXhwIjoxNjg0MjA3NTA1LCJ1c2VySWQiOiIxIiwidXNlck5hbWUiOiLns7vnu5_nrqHnkIblkZgiLCJ1c2VyVHlwZSI6IjAiLCJyZWZyZXNoVG9rZW4iOiJhZWE5NmY4Yy1jNDM1LTRhNmUtYThlMS02OGI2ZWQwODNhMDciLCJqdGkiOiJhY2FjYmEwYy04Nzc4LTQzZTMtYjVjMC1iNjQ5ZTAxMTlmMmYifQ

Method 2:
Write a utils to parse and generate base64 code by yourself:

var Base64 = {
    
    
        _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

        encode: function(e) {
    
    
          var t = "";
          var n, r, i, s, o, u, a;
          var f = 0;
          e = Base64._utf8_encode(e);
          while (f < e.length) {
    
    
            n = e.charCodeAt(f++);
            r = e.charCodeAt(f++);
            i = e.charCodeAt(f++);
            s = n >> 2;
            o = (n & 3) << 4 | r >> 4;
            u = (r & 15) << 2 | i >> 6;
            a = i & 63;
            if (isNaN(r)) {
    
    
              u = a = 64
            } else if (isNaN(i)) {
    
    
              a = 64
            }
            t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a)
          }
          return t
        },

        decode: function(e) {
    
    
          var t = "";
          var n, r, i;
          var s, o, u, a;
          var f = 0;
          e = e.replace(/[^A-Za-z0-9+/=]/g, "");
          while (f < e.length) {
    
    
            s = this._keyStr.indexOf(e.charAt(f++));
            o = this._keyStr.indexOf(e.charAt(f++));
            u = this._keyStr.indexOf(e.charAt(f++));
            a = this._keyStr.indexOf(e.charAt(f++));
            n = s << 2 | o >> 4;
            r = (o & 15) << 4 | u >> 2;
            i = (u & 3) << 6 | a;
            t = t + String.fromCharCode(n);
            if (u != 64) {
    
    
              t = t + String.fromCharCode(r)
            }
            if (a != 64) {
    
    
              t = t + String.fromCharCode(i)
            }
          }
          t = Base64._utf8_decode(t);
          return t
        },

        _utf8_encode: function(e) {
    
    
          e = e.replace(/rn/g, "n");
          var t = "";
          for (var n = 0; n < e.length; n++) {
    
    
            var r = e.charCodeAt(n);
            if (r < 128) {
    
    
              t += String.fromCharCode(r)
            } else if (r > 127 && r < 2048) {
    
    
              t += String.fromCharCode(r >> 6 | 192);
              t += String.fromCharCode(r & 63 | 128)
            } else {
    
    
              t += String.fromCharCode(r >> 12 | 224);
              t += String.fromCharCode(r >> 6 & 63 | 128);
              t += String.fromCharCode(r & 63 | 128)
            }
          }
          return t
        },

        _utf8_decode: function(e) {
    
    
          var t = "";
          var n = 0;
          var r = c1 = c2 = 0;
          while (n < e.length) {
    
    
            r = e.charCodeAt(n);
            if (r < 128) {
    
    
              t += String.fromCharCode(r);
              n++
            } else if (r > 191 && r < 224) {
    
    
              c2 = e.charCodeAt(n + 1);
              t += String.fromCharCode((r & 31) << 6 | c2 & 63);
              n += 2
            } else {
    
    
              c2 = e.charCodeAt(n + 1);
              c3 = e.charCodeAt(n + 2);
              t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
              n += 3
            }
          }
          return t
        }
      };

Usage:
generate:

var enstr = Base64.encode(JSON.stringify({
    
    
                                "sub": "default",
                                "upn": "admin",
                                "iss": "CN=thorough",
                                "iat": 1684147505,
                                "exp": 1684207505,
                                "userId": "1",
                                "userName": "系统管理员",
                                "userType": "0",
                                "refreshToken": "aea96f8c-c435-4a6e-a8e1-68b6ed083a07",
                                "jti": "acacba0c-8778-43e3-b5c0-b649e0119f2f"
                              })); 
console.log(enstr); 

Crack:

var destr = Base64.decode(enstr);
console.log(JSON.parse(destr)); 

insert image description here


Method 3:
Use library files:js-base64
npm install --save js-base64

import {
    
    decode} from 'js-base64'
console.log("解密:",decode('eyJraWQiOiJkZWZhdWx0IiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ'));

You can check their documentation for more: https://www.npmjs.com/package/js-base64

The above base64 analysis principle:

If you are coding by primitive means
, pay attention

const txt = new Buffer('文字').toString('base64');
//encodeURIComponent() 函数可以把字符串作为 URI 组件进行编码并且不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码
const urltxt = encodeURIComponent(txt);
console.log(urltxt)
 
//所对应的,在需要将base64转为utf-8,须提前用decodeURIComponent()进行一次解码,才可以保证解码成功,不乱码
//decodeURIComponent()函数可对 encodeURIComponent() 函数编码的 URI 进行解码。
const zurltxt = new Buffer(decodeURIComponent(urltxt), 'base64').toString('utf8');
console.log(zurltxt)

Right now

encodeURIComponent():把字符串作为URI 组件进行编码
decodeURIComponent():对 encodeURIComponent() 函数编码的 URI 进行解码

You can try to use the original btoa, atob to encode Chinese.

Experience this encoding mode, Chinese can also be encoded and parsed normally

let msg = {
    
    name:"勇敢牛牛",age:18};
let base64 = btoa(unescape(encodeURIComponent(JSON.stringify(msg))));
console.log(base64);
let Tmsg =  decodeURIComponent(escape(atob(base64)));
console.log(JSON.parse(Tmsg));


或者封装成一个函数
// 使用utf-8字符集进行base64编码
function utoa(str) {
    
    
    return btoa(unescape(encodeURIComponent(str)));
}
// 使用utf-8字符集解析base64字符串 
function atou(str) {
    
    
    return decodeURIComponent(escape(atob(str)));
}

atou function: In fact, the key to this function is to convert a Latin character to a utf-8 character. The
method here can be analyzed in detail, and you can see it here:
programming accomplishment

Guess you like

Origin blog.csdn.net/m0_46672781/article/details/130699330