前端js对字符串进行base64编码,后台Java进行解码

1. js编码(第一种方式,字符串中即使有中文,在Java后台也能正常解码)

encode64(value) {
  let typeValue = typeof value;
  if (typeValue == 'string' || typeValue == 'number') {
    return window.btoa(
      window.encodeURIComponent(value)
      .replace(/%([0-9A-F]{2})/g,
               function toSolidBytes(match, p1) {
                 return String.fromCharCode('0x' + p1);
               }
              )
    );
  } else {
    return value;
  }
}

2. js编码(第二种方式,这种方式如果字符串中有中文的话在Java后台解码后会乱码)

encode64(input) {
    // base64加密开始
    var keyStr = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv"
        + "wxyz0123456789+/" + "=";
    var output = "";
    var chr1, chr2, chr3 = "";
    var enc1, enc2, enc3, enc4 = "";
    var i = 0;
    do {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);
        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;
        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }
        output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2)
            + keyStr.charAt(enc3) + keyStr.charAt(enc4);
        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";
    } while (i < input.length);
    return output;
}

3. Java解码

public static byte[] decode(String str) {
byte[] data = str.getBytes();
int len = data.length;
ByteArrayOutputStream buf = new ByteArrayOutputStream(len);
int i = 0;
int b1, b2, b3, b4;

while (i < len) {
    do {
        b1 = base64DecodeChars[data[i++]];
    } while (i < len && b1 == -1);
    if (b1 == -1) {
        break;
    }

    do {
        b2 = base64DecodeChars[data[i++]];
    } while (i < len && b2 == -1);
    if (b2 == -1) {
        break;
    }
    buf.write((int) ((b1 << 2) | ((b2 & 0x30) >>> 4)));

    do {
        b3 = data[i++];
        if (b3 == 61) {
            return buf.toByteArray();
        }
        b3 = base64DecodeChars[b3];
    } while (i < len && b3 == -1);
    if (b3 == -1) {
        break;
    }
    buf.write((int) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));

    do {
        b4 = data[i++];
        if (b4 == 61) {
            return buf.toByteArray();
        }
        b4 = base64DecodeChars[b4];
    } while (i < len && b4 == -1);
    if (b4 == -1) {
        break;
    }
    buf.write((int) (((b3 & 0x03) << 6) | b4));
}

System.out.println(buf.toByteArray());
return buf.toByteArray();
}

你可能感兴趣的:(Web开发,前端,javascript,java)