从Java byte[] -> Base64 -> Javascript ArrayBuffer -> Base64 -> Byte[]

4

我遇到了从Java向Javascript发送数据以及相反方向的问题。

目前我尝试了以下方法:

//a function I found online I use it to convert the decoded version of the java base64 byte[] to an ArrayBuffer
    function str2ab(str) {
      var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
      var bufView = new Uint16Array(buf);
      for (var i=0, strLen=str.length; i<strLen; i++) {
        bufView[i] = str.charCodeAt(i);
      }
      return buf;
    }

function ab2str(buf) {
  return String.fromCharCode.apply(null, new Uint16Array(buf));//retuns a different value than what I put into the buffer.
}

我真的不知道该怎么做了,还有什么想法吗?
1个回答

6

Java

使用 import com.sun.org.apache.xml.internal.security.utils.Base64; 来进行操作。

byte[] b = new byte[] { 12, 3, 4, 5, 12 , 34, 100 };
String encoded = Base64.encode(b);

产生:
"DAMEBQwiZA=="

JavaScript

使用 atobbtoa 方法。

var stringToByteArray = function(str) {
    var bytes = [];
    for (var i = 0; i < str.length; ++i) {
        bytes.push(str.charCodeAt(i));
    }
    return bytes;
};
var decoded = stringToByteArray(atob("DAMEBQwiZA=="));

输出:

[ 12, 3, 4, 5, 12 , 34, 100 ]

注意:如果您在NodeJS中执行此操作,请查看atob软件包。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接