1

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 ?

2
  • 2
    How to ask for help: don't say, "they are different," show the two different values. There are clues there... Commented Jul 21, 2014 at 18:59
  • As a side note, don't try to tag your question with as many tags as possible. Someone who's an expert in HTTP or Apache wouldn't be able to help you here, so there's no reason to use those tags. Just java, python, and base64 is all you want. Commented Jul 21, 2014 at 19:02

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

So this whole question is a simple typo.
@abarnert It's a little more subtle then a normal typo (because it's a String format issue), but you might certainly be of that opinion.
Thanks Elliott ! Python code owner is someone else and it didn't make any sense to include ":" after "%s". So it is not issue of typo but bad code practice.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.