Search code examples
javascriptpythonbase64md5

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?


Solution

  • 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=='