简体   繁体   中英

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?

python2.7 code:

#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 :

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

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