Base64 Encoding Example A Base64 encoder starts by chunking the binary stream into groupings of six characters: 100110 111010 001011 101001. Each of these groupings translates into the numbers 38, 58, 11, and 41.
In JavaScript there are two functions respectively for decoding and encoding Base64 strings: btoa() : creates a Base64-encoded ASCII string from a "string" of binary data ("btoa" should be read as "binary to ASCII"). atob() : decodes a Base64-encoded string("atob" should be read as "ASCII to binary").
A Base64 string will end with == if and only if the number of bytes it encodes, mod 3, equals 1. Do you see the pattern? It happens that 16-byte (128-bit) encryption keys are very commonly encoded in Base64, and since 16 mod 3 = 1, their encoding will end with == .
First:
Transmitting end:
text.getBytes(encodingName)
)Base64
classReceiving end:
Base64
classnew String(bytes, encodingName)
)So something like:
// Sending side
byte[] data = text.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, "UTF-8");
Or with StandardCharsets
:
// Sending side
byte[] data = text.getBytes(StandardCharsets.UTF_8);
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
// Receiving side
byte[] 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:
// encode
String ps = "techPass";
String tmp = Base64.encodeBytes(ps.getBytes());
// decode
String 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())
If you are using Kotlin than use like this
For Encode
val password = "Here Your String"
val data = password.toByteArray(charset("UTF-8"))
val base64 = Base64.encodeToString(data, Base64.DEFAULT)
For Decode
val datasd = Base64.decode(base64, Base64.DEFAULT)
val text = String(datasd, charset("UTF-8"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With