简体   繁体   中英

Convert md5 hash code of javascript to Python return different result

Currently, I have the following Javascript code that required to be converted to Python code

var requestContent = CryptoJS.MD5('{ "agentSessionId": "1622024176" }');
var requestContentBase64String = requestContent.toString(CryptoJS.enc.Base64);

this return the following result bwtSmXFDxoG4cb0HDrZbhQ==

On the other hand, I wrote the following Python code:

request_content = hashlib.md5('{ "agentSessionId": "1622024176" }').encode('utf-8')).hexdigest()
request_content_base64_string = base64.b64encode(request_content.encode())

but it returned a different result NmYwYjUyOTk3MTQzYzY4MWI4NzFiZDA3MGViNjViODU=

Can someone tell me why these 2 return different results when both do 2 jobs of md5 hashing and encode to base64 string and how do I go about changing the Python code for it to work?

Try this (I changed hexdigest to digest):

import hashlib, base64
# JAVA version: bwtSmXFDxoG4cb0HDrZbhQ==
request_content = hashlib.md5('{ "agentSessionId": "1622024176" }'.encode('utf-8')).digest()
request_content_base64_string = base64.b64encode(request_content)
print(request_content_base64_string)

Result:

b'bwtSmXFDxoG4cb0HDrZbhQ=='

change ur python code to this:

import hashlib
import base64

magic = '{ "agentSessionId": "1622024176" }'
magic = hashlib.md5(magic.encode())
magic = magic.digest()
magic1= base64.b64encode(magic)
encodedStr = str(magic1, "utf-8")
print(encodedStr)

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