In Android how to concatenate base64 encoded strings?
Please help me to solve this:
I have two strings for email-id and password like
String name = "firstname.lastname@example.org"; String pass = "abc";
I encode these two into Base64 string like
String encoded_name = new String(Base64.encode(name.getBytes(), 0)); String encoded_pass = new String(Base64.encode(pass.getBytes(), 0));
and I need to concatenate these two encoded strings with space like
String merge = encoded_name + " " + encoded_pass;
I checked this string in console by
System.out.print("Concatenate string= " + merge);
but in console I am getting result in two lines like this
11-18 00:25:29.898: INFO/System.out(1244): Merge= eHl6QGdtYWlsLmNvbQ== 11-18 00:25:29.908: INFO/System.out(1244): YWJj
Why is this happing the result is unexpected for me why it is not printing in a single line. please help me to solve this.
3 Solutions collect form web for “In Android how to concatenate base64 encoded strings?”
You should use the NO_WRAP flag as described in the Docs, the Base64 class will not add additional newlines.
NO_WRAP: Encoder flag bit to omit all line terminators (i.e., the output will be on one long line).
So change your lines to the following:
String encoded_name = new String(Base64.encode(name.getBytes(), Base64.NO_WRAP)); String encoded_pass = new String(Base64.encode(pass.getBytes(), Base64.NO_WRAP));
This will output the following:
11-17 19:16:51.283: INFO/System.out(354): Concatenate string= eHl6QGdtYWlsLmNvbQ== YWJj
Please have a look on Android Api reference Document. It will solve all other queries regarding Base64 encoding/decoding in android.
one more efficient way to solve your problem:
String encoded_name = Base64.encodeToString(name.getBytes("utf-8"), Base64.NO_WRAP); String encoded_pass = Base64.encodeToString(pass.getBytes("utf-8"), Base64.NO_WRAP);
11-17 10:55:27.492: V/BASE-64-.encodeToString(525): eHl6QGdtYWlsLmNvbQ== YWJj
Look at this doc, the mime section states that
MIME does not specify a fixed length for Base64-encoded lines, but it does specify a maximum line length of 76 characters. Additionally it specifies that any extra-alphabetic characters must be ignored by a compliant decoder, although most implementations use a CR/LF newline pair to delimit encoded lines.
You should only consider removing the last char of your first base 64 string, it seems to be a \n (a more generic method would be to test wether it is or not.)