Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I encode/decode short strings as Base64 using GWT?

Tags:

java

base64

gwt

I need to encode a short String as base 64 in GWT and decode the base 64 string on the server. Anyone have utility class or library for this?

like image 589
David Tinker Avatar asked Feb 12 '10 08:02

David Tinker


3 Answers

You can use native JavaScript for this on the client on all browsers except IE ≤ 9. On the server you can use one of the official classes.

Java/GWT:

private static native String b64decode(String a) /*-{
  return window.atob(a);
}-*/;

Encode is btoa.

like image 104
Janus Troelsen Avatar answered Oct 21 '22 16:10

Janus Troelsen


You can use the BaseEncoding class provided by Guava.

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/BaseEncoding.html

For example:

try {
  String encoded = BaseEncoding.base64().encode("foo".getBytes("UTF-8"))
} catch (UnsupportedEncodingException e) {
  GWT.log(e.getMessage());
}

And don't forget to add the following line to your GWT module XML:

<inherits name="com.google.common.io.Io"/>

The BaseEncoding class can be used on both the GWT client side and server side.

like image 35
Jake W Avatar answered Oct 21 '22 17:10

Jake W


You can have a look at https://github.com/mooreds/gwt-crypto

It provides base64 encoding to GWT.

Base64.encode(string.getBytes());

Add the import below :

import com.googlecode.gwt.crypto.bouncycastle.util.encoders.Base64;

Don't forget to add the following line to your GWT module XML:

<inherits name="com.googlecode.gwt.crypto.Crypto"/>    

Maven dependency

<dependency>
    <groupId>com.googlecode.gwt-crypto</groupId>
    <artifactId>gwt-crypto</artifactId>
    <version>2.3.0</version>
</dependency>
like image 3
Ronan Quillevere Avatar answered Oct 21 '22 18:10

Ronan Quillevere