最全js方法,String字符串base64编码和types字节数组相互转换

做一个项目,用到加密,字节网上找的资料整理在这里,String字符串base64编码和types字节数组相互转换。

废话不多说代码贴上.

function stringToByte(str) {
            var bytes = new Array();
            var len, c;
            len = str.length;
            for(var i = 0; i < len; i++) {
                c = str.charCodeAt(i);
                if(c >= 0x010000 && c <= 0x10FFFF) {
                    bytes.push(((c >> 18) & 0x07) | 0xF0);
                    bytes.push(((c >> 12) & 0x3F) | 0x80);
                    bytes.push(((c >> 6) & 0x3F) | 0x80);
                    bytes.push((c & 0x3F) | 0x80);
                } else if(c >= 0x000800 && c <= 0x00FFFF) {
                    bytes.push(((c >> 12) & 0x0F) | 0xE0);
                    bytes.push(((c >> 6) & 0x3F) | 0x80);
                    bytes.push((c & 0x3F) | 0x80);
                } else if(c >= 0x000080 && c <= 0x0007FF) {
                    bytes.push(((c >> 6) & 0x1F) | 0xC0);
                    bytes.push((c & 0x3F) | 0x80);
                } else {
                    bytes.push(c & 0xFF);
                }
            }
            return bytes;
 
 
 }
 // utf8
 function byteToString(arr) {
             if(typeof arr === 'string') {
                 return arr;
             }
             var str = '',
                 _arr = arr;
             for(var i = 0; i < _arr.length; i++) {
                 var one = _arr[i].toString(2),
                     v = one.match(/^1+?(?=0)/);
                 if(v && one.length == 8) {
                     var bytesLength = v[0].length;
                     var store = _arr[i].toString(2).slice(7 - bytesLength);
                     for(var st = 1; st < bytesLength; st++) {
                         store += _arr[st + i].toString(2).slice(2);
                     }
                     str += String.fromCharCode(parseInt(store, 2));
                     i += bytesLength - 1;
                 } else {
                     str += String.fromCharCode(_arr[i]);
                 }
             }
             return str;
         }
/**
 * Convert the given string to byte array
 * 
 * @param {string} str the string to be converted to byte array
 * @returns {number[]}
 */
var str2bytes = function (str) {
    var i = 0;
    var ch = null;
    var hex = null;
    var encoded = encodeURIComponent(str);
    var length = encoded.length;
    var bytes = [];

    while (i < length) {
        ch = encoded.charAt(i++);
        if (ch === '%') {
            hex = encoded.charAt(i++)
            hex += encoded.charAt(i++);
            bytes.push(parseInt(hex, 16));
        } else {
            bytes.push(ch.charCodeAt(0));
        }
    }

    return bytes;
};

/**
 * Convert the given byte array to string
 * 
 * @param {number[]} bytes The byte array to be converted to string
 * @returns {string}
 */
var bytes2str = function (bytes) {
    var i = 0;
    var hex = null;
    var byte = 0;
    var hexArray = [];
    var length = bytes.length;

    while (i < length) {
        byte = bytes[i++];
        hex = byte.toString(16);
        hex = hex.length < 2 ? ('%0' + hex) : ('%' + hex);
        hexArray.push(hex);
    }

    return decodeURIComponent(hexArray.join(''));
};
function base64ArrayBuffer(arrayBuffer) {
  var base64    = ''
  var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='

  var bytes         = new Uint8Array(arrayBuffer)
  var byteLength    = bytes.byteLength
  var byteRemainder = byteLength % 3
  var mainLength    = byteLength - byteRemainder

  var a, b, c, d
  var chunk

  // Main loop deals with bytes in chunks of 3
  for (var i = 0; i < mainLength; i = i + 3) {
    // Combine the three bytes into a single integer
    chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]

    // Use bitmasks to extract 6-bit segments from the triplet
    a = (chunk & 16515072) >> 18 // 16515072 = (2^6 - 1) << 18
    b = (chunk & 258048)   >> 12 // 258048   = (2^6 - 1) << 12
    c = (chunk & 4032)     >>  6 // 4032     = (2^6 - 1) << 6
    d = chunk & 63               // 63       = 2^6 - 1

    // Convert the raw binary segments to the appropriate ASCII encoding
    base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]
  }

  // Deal with the remaining bytes and padding
  if (byteRemainder == 1) {
    chunk = bytes[mainLength]

    a = (chunk & 252) >> 2 // 252 = (2^6 - 1) << 2

    // Set the 4 least significant bits to zero
    b = (chunk & 3)   << 4 // 3   = 2^2 - 1

    base64 += encodings[a] + encodings[b] + '=='
  } else if (byteRemainder == 2) {
    chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]

    a = (chunk & 64512) >> 10 // 64512 = (2^6 - 1) << 10
    b = (chunk & 1008)  >>  4 // 1008  = (2^6 - 1) << 4

    // Set the 2 least significant bits to zero
    c = (chunk & 15)    <<  2 // 15    = 2^4 - 1

    base64 += encodings[a] + encodings[b] + encodings[c] + '='
  }
  
  return base64
}

(function() {
  var base64EncodeChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
  base64DecodeChars = new Array(( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), 62, ( - 1), ( - 1), ( - 1), 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), ( - 1), 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, ( - 1), ( - 1), ( - 1), ( - 1), ( - 1));
  this.base64encode = function(e) {
      var r, a, c, h, o, t;
      for (c = e.length, a = 0, r = ''; a < c;) {
          if (h = 255 & e.charCodeAt(a++), a == c) {
              r += base64EncodeChars.charAt(h >> 2),
              r += base64EncodeChars.charAt((3 & h) << 4),
              r += '==';
              break
          }
          if (o = e.charCodeAt(a++), a == c) {
              r += base64EncodeChars.charAt(h >> 2),
              r += base64EncodeChars.charAt((3 & h) << 4 | (240 & o) >> 4),
              r += base64EncodeChars.charAt((15 & o) << 2),
              r += '=';
              break
          }
          t = e.charCodeAt(a++),
          r += base64EncodeChars.charAt(h >> 2),
          r += base64EncodeChars.charAt((3 & h) << 4 | (240 & o) >> 4),
          r += base64EncodeChars.charAt((15 & o) << 2 | (192 & t) >> 6),
          r += base64EncodeChars.charAt(63 & t)
      }
      return r
  }
  this.base64decode = function(e) {
      var r, a, c, h, o, t, d;
      for (t = e.length, o = 0, d = ''; o < t;) {
          do r = base64DecodeChars[255 & e.charCodeAt(o++)];
          while (o < t && r == -1);
          if (r == -1) break;
          do a = base64DecodeChars[255 & e.charCodeAt(o++)];
          while (o < t && a == -1);
          if (a == -1) break;
          d += String.fromCharCode(r << 2 | (48 & a) >> 4);
          do {
              if (c = 255 & e.charCodeAt(o++), 61 == c) return d;
              c = base64DecodeChars[c]
          } while ( o < t && c == - 1 );
          if (c == -1) break;
          d += String.fromCharCode((15 & a) << 4 | (60 & c) >> 2);
          do {
              if (h = 255 & e.charCodeAt(o++), 61 == h) return d;
              h = base64DecodeChars[h]
          } while ( o < t && h == - 1 );
          if (h == -1) break;
          d += String.fromCharCode((3 & c) << 6 | h)
      }
      return d
  }
  this.hexToBase64 = function(str) {
      return base64encode(String.fromCharCode.apply(null, str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")));
  }
  this.Base64Tohex = function(str) {
      for (var i = 0,
      bin = base64decode(str.replace(/[ \r\n]+$/, "")), hex = []; i < bin.length; ++i) {
          var tmp = bin.charCodeAt(i).toString(16);
          if (tmp.length === 1) tmp = "0" + tmp;
          hex[hex.length] = tmp;
      }
      return hex.join("");
  },
  this.toBytes = function(str) {
     for (var bytes = [], c = 0; c < str.length; c += 2)
     bytes.push(parseInt(str.substr(c, 2), 16));
     return bytes;
  }
  
}) ();
//hexToBase64 Base64Tohex base64decode base64encode

var bytesToString = function(bytes){
    return hexToString(bytesToHex(bytes));
}


var  bytesToBase64 = function(bytes){
    return base64ArrayBuffer(bytes);
}

// Convert a byte array to a hex string
var bytesToHex = function(bytes) {
    for (var hex = [], i = 0; i < bytes.length; i++) {
        hex.push((bytes[i] >>> 4).toString(16));
        hex.push((bytes[i] & 0xF).toString(16));
    }
    return hex.join("");
}


var stringToBase64 = function(str){
    return base64encode(str); 
}

var stringToBytes = function(str){
  return hexToBytes(stringToHex(str));
}

// Convert a ASCII string to a hex string
var stringToHex = function(str) {
    return str.split("").map(function(c) {
        return ("0" + c.charCodeAt(0).toString(16)).slice(-2);
    }).join("");
}

var hexToBytes= function(hex) {
    for (var bytes = [], c = 0; c < hex.length; c += 2)
    bytes.push(parseInt(hex.substr(c, 2), 16));
    return bytes;
}

// Convert a hex string to a ASCII string
var hexToString = function(hexStr) {
    var hex = hexStr.toString();//force conversion
    var str = '';
    for (var i = 0; i < hex.length; i += 2)
        str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
    return str;
}

var hexToBase64 = function(hexStr){
  return hexToBase64(hexStr);
}

var base64ToString = function(base64str){
  return base64decode(base64str);
}

var base64ToHex = function(base64str){
  return Base64Tohex(base64str);
}

var base64ToBytes = function(base64str){
    return toBytes(base64str);
  //null
}

const 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 = 0;
        var c1 =0;
        var c2 =0;
        var c3 =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
    }
}

function encodeUtf8(text) {
        const code = encodeURIComponent(text);
        const bytes = [];
        for (var i = 0; i < code.length; i++) {
            const c = code.charAt(i);
            if (c === '%') {
                const hex = code.charAt(i + 1) + code.charAt(i + 2);
                const hexVal = parseInt(hex, 16);
                bytes.push(hexVal);
                i += 2;
            } else bytes.push(c.charCodeAt(0));
        }
        return bytes;
}
   
function decodeUtf8(bytes) {
        var encoded = "";
        for (var i = 0; i < bytes.length; i++) {
            encoded += '%' + bytes[i].toString(16);
        }
        return decodeURIComponent(encoded);
}
function strToBytesUTF8(str) {
    let utf8 = [];
    for (let i = 0; i < str.length; i++) {
        let charcode = str.charCodeAt(i);
        if (charcode < 0x80) utf8.push(charcode);
        else if (charcode < 0x800) {
            utf8.push(0xc0 | (charcode >> 6),
                      0x80 | (charcode & 0x3f));
        }
        else if (charcode < 0xd800 || charcode >= 0xe000) {
            utf8.push(0xe0 | (charcode >> 12),
                      0x80 | ((charcode>>6) & 0x3f),
                      0x80 | (charcode & 0x3f));
        }
        // surrogate pair
        else {
            i++;
            // UTF-16 encodes 0x10000-0x10FFFF by
            // subtracting 0x10000 and splitting the
            // 20 bits of 0x0-0xFFFFF into two halves
            charcode = 0x10000 + (((charcode & 0x3ff)<<10)
                      | (str.charCodeAt(i) & 0x3ff));
            utf8.push(0xf0 | (charcode >>18),
                      0x80 | ((charcode>>12) & 0x3f),
                      0x80 | ((charcode>>6) & 0x3f),
                      0x80 | (charcode & 0x3f));
        }
    }
    return utf8;
}
    

 module.exports = {
     stringToByte,
    byteToString,
    str2bytes,
    bytes2str,
    base64ArrayBuffer,
    bytesToString,
    bytesToBase64,
    bytesToHex,
    stringToBase64,
    stringToBytes,
    stringToHex,
    hexToBytes,
    hexToString,
    hexToBase64,
    base64ToString,
    base64ToHex,
    base64ToBytes,
    Base64,
    encodeUtf8,
    decodeUtf8,
    strToBytesUTF8
 }

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值