Python Base64 编码与 Java Base64 编码比较
以下是我用Python生成base64编码字符串的代码:
base64str = base64.encodestring('%s:' % getpass.getuser())
我想用Java得到相同的base64字符串。这里是我的Java代码片段:
String user = System.getProperty("user.name");
byte[] encoded_str = Base64.encodeBase64(user.getBytes());
String encoded_string = new String(encoded_str).trim();
但是我发现Python生成的字符串和Java生成的字符串不一样。我在使用“import org.apache.commons.codec.binary.Base64;”这个库。
有没有什么想法?
2 个回答
1
在Java中,String.getBytes()
这个方法并不能保证使用的字符集是什么。所以,建议使用String.getBytes(String)
这个方法,这样你就可以确保得到你想要的编码方式。
user.getBytes("UTF-8")
1
你的Python代码在调用Base64之前,会在输入的字符串后面加一个冒号。
>>> print '%s:' % 'test'
test:
当我在你的Java代码中也加上这个冒号时,我在测试中(Python和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);