Does anyone know how to decode and encode a string in Base64 using the Base64. I am using the following code, but it\'s not working.
String source = \"passwo
For API level 26+
String encodedString = Base64.getEncoder().encodeToString(byteArray);
Ref: https://developer.android.com/reference/java/util/Base64.Encoder.html#encodeToString(byte[])
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"))
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())
'java.util.Base64' class provides functionality to encode and decode the information in Base64 format.
How to get Base64 Encoder?
Encoder encoder = Base64.getEncoder();
How to get Base64 Decoder?
Decoder decoder = Base64.getDecoder();
How to encode the data?
Encoder encoder = Base64.getEncoder();
String originalData = "java";
byte[] encodedBytes = encoder.encode(originalData.getBytes());
How to decode the data?
Decoder decoder = Base64.getDecoder();
byte[] decodedBytes = decoder.decode(encodedBytes);
String decodedStr = new String(decodedBytes);
You can get more details at this link.
for android API byte[]
to Base64String
encoder
byte[] data=new byte[];
String Base64encodeString=android.util.Base64.encodeToString(data, android.util.Base64.DEFAULT);