3

How to convert a base64 String to byte array with Gwt client side code?

This link shows a encode decode, for base64 but not to byte[] array

https://snipt.net/tweakt/gwt-base64/

quarks
  • 33,478
  • 73
  • 290
  • 513
  • Since GWT client code gets cross-compiled into javascript, there aren't many classes around that supports this on the client side. [This link suggests using ByteBuffer](http://stackoverflow.com/questions/14141432/bytebuffer-to-string-in-gwt), which is not [emulated for client use](http://www.gwtproject.org/doc/latest/RefJreEmulation.html). But you can try using the [custom implemented ByteBuffer from here](https://code.google.com/p/quake2-gwt-port/source/browse/src/com/google/gwt/corp/emul/java/nio/ByteBuffer.java). But you should probably be doing this conversion on the server anyways. – Churro Sep 08 '13 at 20:10

2 Answers2

7

You have two options:

1- Use native JS methods btoa and atob, and convert the returned string to a java byte[] array:

 native String btoa(String b64) /*-{
    return btoa(b64);
 }-*/;
 ...
 byte[] result = btoa(myBase64Data).getBytes();

2- Use a pure java implementation of Base64 algorithm. You can just copy the Base64Utils.java included in the gwt-user.jar, and copy it to your client package, and use its methods:

 import my.project.namespace.client.Base64Utils;
 ...
 byte[] result = Base64Utils.fromBase64(myBase64Data);

Normally I use #1 for IE10, FF and webkit browsers, and #2 for old IE.

Manolo Carrasco Moñino
  • 9,723
  • 1
  • 22
  • 27
  • Please note that option #1 and #2 will not produce the same results in some cases as Base64Utils.java uses "URL-safe" encoding. – dagge Feb 03 '15 at 10:54
2

Try to use this library https://code.google.com/p/gwt-crypto

It was successful for me.

Nick V
  • 1,591
  • 1
  • 11
  • 7