简体   繁体   中英

Python Base64 encoding Vs Java Base64 encoding

Following is my python code to generate base64 encoded string:

base64str = base64.encodestring('%s:' % getpass.getuser())

I want same base64str using Java. Here is my Java code snippet:

String user = System.getProperty("user.name");
byte[] encoded_str = Base64.encodeBase64(user.getBytes());
String encoded_string = new String(encoded_str).trim();

Somehow python encoded string is different than Java. I'm using "import org.apache.commons.codec.binary.Base64;" library.

Any idea ?

Your python code appends a colon to the input String before calling Base64

>>> print '%s:' % 'test'
test:

When I add the colon to your java code, I am able to get the same result in my testing (python and Java),

String user = System.getProperty("user.name") + ":";
byte[] encoded_str = Base64.encodeBase64(user
    .getBytes());
String encoded_string = new String(encoded_str)
    .trim();
System.out.println(encoded_string);

String.getBytes() in Java doesn't guarantee the character set used. Use String.getBytes(String) instead to always be sure that you get the encoding you want.

user.getBytes("UTF-8")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM