In Android, how to concatenate base64 encoded strings?

Please help me solve this problem:

I have two lines for email id and password like

String name = " xyz@gmail.com "; String pass = "abc"; 

I encode these two into a Base64 string, for example

 String encoded_name = new String(Base64.encode(name.getBytes(), 0)); String encoded_pass = new String(Base64.encode(pass.getBytes(), 0)); 

, and I need to combine these two encoded lines with space, e.g.

 String merge = encoded_name + " " + encoded_pass; 

I checked this line on the console

 System.out.print("Concatenate string= " + merge); 

but in the console I get the result in two lines, such as

 11-18 00:25:29.898: INFO/System.out(1244): Merge= eHl6QGdtYWlsLmNvbQ== 11-18 00:25:29.908: INFO/System.out(1244): YWJj 

Why this happens, the result is unexpected for me, why it does not print on one line. please help me solve this.

thanks

+6
source share
3 answers

You must use the NO_WRAP flag, as described in Docs , the Base64 class will not add additional newline characters.

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)); 

As a result, you get the following:

 11-17 19:16:51.283: INFO/System.out(354): Concatenate string= eHl6QGdtYWlsLmNvbQ== YWJj 
+20
source

Please see the Android Api Reference Document . It will solve all other questions regarding Base64 encoding / decoding in android.

Another effective 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); 

out put: -

 11-17 10:55:27.492: V/BASE-64-.encodeToString(525): eHl6QGdtYWlsLmNvbQ== YWJj 
+1
source

Check out this document , the mime section states that

MIME does not specify a fixed length for Base64 encoded strings, but specifies a maximum string length of 76 characters. In addition, he indicates that any characters with an extra alphabet should be ignored by a compatible decoder, although most implementations use a pair of newline CR / LF lines to distinguish between encoded lines.

You should consider removing the last char of your first 64 base line, it looks like \ n (a more general method is to check if it is.)

Regards, StΓ©phane

0
source

Source: https://habr.com/ru/post/901742/


All Articles