简体   繁体   English

为什么我对相同文本的 python 和 java base64 编码有不同的结果?

[英]Why I have different results for python and java base64 encode for the same text?

I have two codes in python and java as following, but run them to different results, what happened?我在 python 和 java 中有两个代码如下,但是运行它们得到不同的结果,发生了什么?

python2.7 code: python2.7代码:

#encoding:utf-8
import json
import base64

st_test = {"test":"测试内容"}
body = json.dumps(st_test,ensure_ascii=False)
res = base64.b64encode(body)
prin res 
#eyJ0ZXN0IjogIua1i+ivleWGheWuuSJ9

Java code:爪哇代码:

import java.util.Base64;

body = "{\"test\":\"测试内容\"}";
String body64 = Base64.getEncoder().encodeToString(body.getBytes("UTF-8")) ;
System.out.println(body64);
//eyJ0ZXN0Ijoi5rWL6K+V5YaF5a65In0=

You have two different strings - Java doesn't have space after :您有两个不同的字符串 - Java在以下之后没有空格:

If I remove space如果我删除空间

body = body.replace(' ', '')

then I get the same code然后我得到相同的代码


import json
import base64

st_test = {"test": "测试内容"}
body = json.dumps(st_test, ensure_ascii=False)
print body

body = body.replace(' ', '')
print body

res = base64.b64encode(body)
print res
print (res == 'eyJ0ZXN0Ijoi5rWL6K+V5YaF5a65In0=')

Result结果

{"test": "测试内容"}
{"test":"测试内容"}
eyJ0ZXN0Ijoi5rWL6K+V5YaF5a65In0=
True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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