当前位置: 首页 > 工具软件 > js-base64 > 使用案例 >

js中base64编码

吴均
2023-12-01

1. 使用 Buffer对象

Buffer.from(JSON.stringify(jwtHeader)).toString('base64')

2. 使用base64js.js

/**
 * base64js  Uint8Array 8位无符号整数,长度1个字节,
 * base64js.byteLength(base64Str)   base64字符串转为字节数组的长度
 * base64js.toByteArray(base64Str) base64字符串转为字节数组
 * base64js.fromByteArray(bytes)   字节数组转为base64字符串
 */
(function (r) {
  if (typeof exports === "object" && typeof module !== "undefined") {
    module.exports = r()
  } else {
    if (typeof define === "function" && define.amd) {
      define([], r)
    } else {
      var e;
      if (typeof window !== "undefined") {
        e = window
      } else {
        if (typeof global !== "undefined") {
          e = global
        } else {
          if (typeof self !== "undefined") {
            e = self
          } else {
            e = this
          }
        }
      }
      e.base64js = r()
    }
  }
})(function () {
  var r, e, t;
  return function r(e, t, n) {
    function o(i, a) {
      if (!t[i]) {
        if (!e[i]) {
          var u = typeof require == "function" && require;
          if (!a && u) {
            return u(i, !0)
          }
          if (f) {
            return f(i, !0)
          }
          var d = new Error("Cannot find module '" + i + "'");
          throw d.code = "MODULE_NOT_FOUND", d
        }
        var c = t[i] = {
          exports: {}
        };
        e[i][0].call(c.exports, function (r) {
          var t = e[i][1][r];
          return o(t ? t : r)
        }, c, c.exports, r, e, t, n)
      }
      return t[i].exports
    }

    var f = typeof require == "function" && require;
    for (var i = 0; i < n.length; i++) {
      o(n[i])
    }
    return o
  }({
    "/": [function (r, e, t) {
      t.byteLength = c;
      t.toByteArray = v;
      t.fromByteArray = s;
      var n = [];
      var o = [];
      var f = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
      var i = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
      for (var a = 0, u = i.length; a < u; ++a) {
        n[a] = i[a];
        o[i.charCodeAt(a)] = a
      }
      o["-".charCodeAt(0)] = 62;
      o["_".charCodeAt(0)] = 63;

      function d(r) {
        var e = r.length;
        if (e % 4 > 0) {
          throw new Error("Invalid string. Length must be a multiple of 4")
        }
        return r[e - 2] === "=" ? 2 : r[e - 1] === "=" ? 1 : 0
      }

      function c(r) {
        return r.length * 3 / 4 - d(r)
      }

      function v(r) {
        var e, t, n, i, a;
        var u = r.length;
        i = d(r);
        a = new f(u * 3 / 4 - i);
        t = i > 0 ? u - 4 : u;
        var c = 0;
        for (e = 0; e < t; e += 4) {
          n = o[r.charCodeAt(e)] << 18 | o[r.charCodeAt(e + 1)] << 12 | o[r.charCodeAt(e + 2)] << 6 | o[r.charCodeAt(e + 3)];
          a[c++] = n >> 16 & 255;
          a[c++] = n >> 8 & 255;
          a[c++] = n & 255
        }
        if (i === 2) {
          n = o[r.charCodeAt(e)] << 2 | o[r.charCodeAt(e + 1)] >> 4;
          a[c++] = n & 255
        } else {
          if (i === 1) {
            n = o[r.charCodeAt(e)] << 10 | o[r.charCodeAt(e + 1)] << 4 | o[r.charCodeAt(e + 2)] >> 2;
            a[c++] = n >> 8 & 255;
            a[c++] = n & 255
          }
        }
        return a
      }

      function l(r) {
        return n[r >> 18 & 63] + n[r >> 12 & 63] + n[r >> 6 & 63] + n[r & 63]
      }

      function h(r, e, t) {
        var n;
        var o = [];
        for (var f = e; f < t; f += 3) {
          n = (r[f] << 16) + (r[f + 1] << 8) + r[f + 2];
          o.push(l(n))
        }
        return o.join("")
      }

      function s(r) {
        var e;
        var t = r.length;
        var o = t % 3;
        var f = "";
        var i = [];
        var a = 16383;
        for (var u = 0, d = t - o; u < d; u += a) {
          i.push(h(r, u, u + a > d ? d : u + a))
        }
        if (o === 1) {
          e = r[t - 1];
          f += n[e >> 2];
          f += n[e << 4 & 63];
          f += "=="
        } else {
          if (o === 2) {
            e = (r[t - 2] << 8) + r[t - 1];
            f += n[e >> 10];
            f += n[e >> 4 & 63];
            f += n[e << 2 & 63];
            f += "="
          }
        }
        i.push(f);
        return i.join("")
      }
    }, {}]
  }, {}, [])("/")
});

字符串编码

/**
 * utf8字符串转为字节数组 同java中 String.getBytes(utf8Str)
 * @param utf8Str
 * @returns {[]}
 */
var utf8StrToBytes = function (utf8Str) {
    var ens = encodeURIComponent(utf8Str);
    var es = unescape(ens);
    var esLen = es.length;
    // Convert
    var words = [];
    for (var i = 0; i < esLen; i++) {
        words[i] = es.charCodeAt(i);
    }
    return words;
}
/**
 * 字节数组转为utf8字符串  同java中 new String(bytes)
 * @param bytesArray
 * @returns {string}
 */
var bytesToUtf8Str = function (bytesArray) {
    var utf8Byte = bytesArray;
    var latin1Chars = [];
    for (var i = 0; i < utf8Byte.length; i++) {
        latin1Chars.push(String.fromCharCode(utf8Byte[i]));
    }
    return decodeURIComponent(escape(latin1Chars.join('')));
}

测试

base64.fromByteArray(utf8StrToBytes('打快点快点')) // 5omT5b+r54K55b+r54K5
//同Java中 org.apache.commons.codec
Base64.encodeBase64String("打快点快点".getBytes()) // 5omT5b+r54K55b+r54K5

3. js中类似java中byte强转int类型

/**
 * int 转 byte, js中int转byte(-128—127)
 * @param i 整数
 */
var intToByte = function(i) {
  var b = i & 0xFF;
  var c = 0;
  if (b >= 128) {
    c = b % 128;
    c = -1 * (128 - c);
  } else {
    c = b;
  }
  return c
}
```

 类似资料: