1. Introduction of base64

Base64:64 characters are selected as A basic character set (a-z, A-z, 0-9, +, /, plus the “=” as A placeholder, which is actually 65 characters), and all other symbols are converted to characters in this character set.

Coding rules:

  1. By grouping each three bytes as a group, there are 24 binary bits.
  2. Divide the 24 bits into four groups of six bits each.
  3. Add two 00’s to the front of each group to expand to 32 binary bits, or four bytes.
  4. According to the following table, the corresponding symbol of each byte after expansion is obtained, which is the encoding value of Base64.

What if the bytes are less than three? In the case of 2 bytes, divide the 2 bytes into 3 groups (6,6,4) according to the above rules, and add two zeros after the last group. This results in a three-digit Base64 encoding, followed by a “=” at the end.

Eg: "Ma"This string is two bytes, can be converted into three groups 00010011, 00010110, 00000100, corresponding Base64 values are T, W, E, and add a" =".No, so"Ma"Base64 encoding is TWE=.Copy the code

In the case of 1 byte, the 8 bits of the 1 byte are converted into 2 groups (6,2) according to the above rules. The last group is preceded by 2 zeros and followed by 4 zeros. This results in a two-digit Base64 encoding, followed by two “=” signs at the end.

Eg: "M"This letter is a byte, can be converted into two groups 00010011, 00010000, corresponding Base64 values are T, Q, and add two" ="No, so"M"Base64 encoding is TQ==.Copy the code

How to decode:

  1. Find the ASCII value for each character in a group of 4.
  2. Write the four ASCII values in binary form, removing the first two 00’s from each binary;
  3. Divide the remaining 24 bits into three parts, that is, three bytes;
  4. Find the ASCII value table (table below) to find the character for each byte;

2. Base64 encoding and decoding are realized in Vue

Using jS-Base64 plug-in implementation

2.1 installation

npm install --save js-base64
Copy the code

2.2 Introduction and Use

<script>
export default {
  data() {
    return {
      encodeTxt:'Front-end development'.decodeTxt:'5YmN56uv5byA5Y+R'}; },methods: {
    base64Test(){
      let Base64 = require('js-base64').Base64; / / introduction
      console.log('Code:' + Base64.encode(this.encodeTxt))
      console.log('Decode:' + Base64.decode(this.decodeTxt))  
    }
  },
  mounted(){
    this.base64Test(); }}; </script>Copy the code

2.3 the effect

3. Btoa and ATOB functions of window objects are implemented

The 3.1 window.atob() function is used to decode base64-encoded data

var encoded_str = "VGhpcyBpcyBhIHN0cmluZw==";
var str = atob(encoded_str);
console.log(str); // This is a string
Copy the code

3.2 Window.btoa () converts ASCII strings or binary data to base64-encoded strings

var str = "This is a string";
var encoded_str = btoa(str);
console.log(encoded_str); // VGhpcyBpcyBhIHN0cmluZw==
Copy the code

Note: It is not applicable to decryption with Chinese, i.e. window.btoa and window.atob do not support Chinese, and IE9 does not support ATOB and BTOA

Fix: BTOA does not support Unicode character encodings

When encoding, encodeURIComponent is used to encode string first, and then Base64 encoding is carried out by BTOA. When decoding, first use ATOB to decode Base64 encoded string, and then use decodeURIComponent to decode string;

var str = "Hello, China's";
var encoded_str = btoa(encodeURIComponent(str));
var decoded_str = decodeURIComponent(atob(encoded_str));

console.log(encoded_str); // aGVsbG8lMkMlRTQlQjglQUQlRTUlOUIlQkQ=
console.log(decoded_str); // Hello, China inserts the code slice here
Copy the code

4. Method of base64 encoding and decoding (support Chinese) by JS

      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}}returnT}};var str = 'hello';

      var enstr = Base64.encode(str); 
      console.log(enstr); // 5L2g5aW9

      var destr = Base64.decode(enstr);
      console.log(destr); / / how are you
Copy the code

5. Base64 encoding and decoding method in Node

5.1 Common Strings

/ / code
new Buffer(String).toString('base64');
/ / decoding
new Buffer(base64Str, 'base64').toString();
Copy the code

5.2 Hex

/ / code
new Buffer(String.'base64').toString('hex');
/ / decoding
new Buffer(base64Str, 'hex').toString('utf8');
Copy the code

5.3 the picture

const fs = require('fs');
/ / code
function base64_encode(file) {
    let bitmap = fs.readFileSync(file);
    return new Buffer(bitmap).toString('base64');
}
/ / decoding
function base64_decode(base64str, file) {
    var bitmap = new Buffer(base64str, 'base64');
    fs.writeFileSync(file, bitmap);
}
Copy the code