Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Need Equivalent Python Script from JS

Please help me convert below JS code to Python.

const di_digest = CryptoJS.SHA1(di_plainTextDigest).toString(CryptoJS.enc.Base64);   

di_plainTextDigest is a String.

I tried a few Python methods, but they do not work:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

result = hashlib.sha1(di_plainTextDigest.encode())
hexd = result.hexdigest()
hexd_ascii = hexd.encode("ascii")
dig2 = base64.b64encode(hexd_ascii)
dig3 = dig2.decode("ascii")
print(dig3 )

>Solution :

To replicate the functionality of the JavaScript code in Python, you can use the hashlib and base64 modules as you have attempted to do. However, the difference between your Python code and the JavaScript code is in the encoding format used. In the JavaScript code, the di_plainTextDigest is encoded using the Base64 format, whereas in your Python code, you are encoding the SHA1 hash of di_plainTextDigest as a hex string before encoding it in Base64. To replicate the JavaScript code in Python, you can skip the hex encoding step and directly encode the SHA1 hash of di_plainTextDigest in Base64. Here is the Python code that should produce the same result as the JavaScript code:

import hashlib
import base64

di_plainTextDigest = "your plaintext digest"

sha1_hash = hashlib.sha1(di_plainTextDigest.encode())
base64_hash = base64.b64encode(sha1_hash.digest()).decode('ascii')

print(base64_hash)

Note that we are encoding the digest() of the sha1_hash object, instead of its hexdigest(). This is because hexdigest() returns a hex-encoded string, whereas we want to produce a Base64-encoded string. We also use the decode() method to convert the resulting bytes object to a string in ASCII format.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading