Base 64 encode and decode example code
First:
- Choose an encoding. UTF-8 is generally a good choice; stick to an encoding which will definitely be valid on both sides. It would be rare to use something other than UTF-8 or UTF-16.
Transmitting end:
- Encode the string to bytes (e.g.
text.getBytes(encodingName)
) - Encode the bytes to base64 using the
Base64
class - Transmit the base64
Receiving end:
- Receive the base64
- Decode the base64 to bytes using the
Base64
class - Decode the bytes to a string (e.g.
new String(bytes, encodingName)
)
So something like:
// Sending sidebyte[] data = text.getBytes("UTF-8");String base64 = Base64.encodeToString(data, Base64.DEFAULT);// Receiving sidebyte[] data = Base64.decode(base64, Base64.DEFAULT);String text = new String(data, "UTF-8");
Or with StandardCharsets
:
// Sending sidebyte[] data = text.getBytes(StandardCharsets.UTF_8);String base64 = Base64.encodeToString(data, Base64.DEFAULT);// Receiving sidebyte[] data = Base64.decode(base64, Base64.DEFAULT);String text = new String(data, StandardCharsets.UTF_8);
To anyone else who ended up here while searching for info on how to decode a string encoded with Base64.encodeBytes()
, here was my solution:
// encodeString ps = "techPass";String tmp = Base64.encodeBytes(ps.getBytes());// decodeString ps2 = "dGVjaFBhC3M=";byte[] tmp2 = Base64.decode(ps2); String val2 = new String(tmp2, "UTF-8");
Also, I'm supporting older versions of Android so I'm using Robert Harder's Base64 library from http://iharder.net/base64
For Kotlin mb better to use this:
fun String.decode(): String { return Base64.decode(this, Base64.DEFAULT).toString(charset("UTF-8"))}fun String.encode(): String { return Base64.encodeToString(this.toByteArray(charset("UTF-8")), Base64.DEFAULT)}
Example:
Log.d("LOGIN", "TEST")Log.d("LOGIN", "TEST".encode())Log.d("LOGIN", "TEST".encode().decode())