Need Equivalent of SHA1 function in python

Question:

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 not working. Example

 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 )
Asked By: Prudhvi

||

Answers:

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.

Answered By: Mustafa Kapuz