From Java Bytes [] & # 8594; Base64 & # 8594; Javascript ArrayBuffer & # 8594; Base64 & # 8594; Byte []

I'm having trouble sending data from Java to Javascript and vice versa.

I have tried this so far:

//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. } 

I really don't know how to do this more than ideas?

+4
source share
1 answer

Java

using 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); 

gives:

 "DAMEBQwiZA==" 

Javascript

use atob and btoa

 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==")); 

gives:

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

Note. If you do this in NodeJS, look at the atob package.

+6
source

All Articles