Recreating A Cryptojs Hmac Using Python
The scenario is that I have a JS script that creates a HMAC for a user provided input and I want to compute the same HMAC for the same input using python. To make things clearer, c
Solution 1:
You are using a Base64 encoded value as secret in Javascript, whereas in Python you use the plain text secret.
<script>var secretAccessKeyBase64 = "secret";
var hash = CryptoJS.HmacSHA256("Message", secretAccessKeyBase64);
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
document.write(hashInBase64);
</script>
This prints out the same value as the Python code:
qnR8UCqJggD55PohusaBNviGoOJ67HC6Btry4qXLVZc=
Edit:
base64 returns a byte-object there is no need to convert it to hex()
:
stringToSign = "Test"
secretAccessKey = "bAvW5O18eSrxke4I7eFcrnrDJkN+wKQmx9aSHuMZQ0w="
secretAccessKeyBase64 = base64.b64decode(secretAccessKey)
keyBytes = secretAccessKeyBase64
stringToSignBytes = bytes(stringToSign, 'utf-8')
signatureHash = hmac.new(keyBytes, stringToSignBytes, digestmod=hashlib.sha256).digest()
signature = base64.b64encode(signatureHash)
print(signature)
Prints correctly:
b'b+1wRzDODA85vyDZkXByPIKO5qmnjCRNF5gZFi33/Ic='
Post a Comment for "Recreating A Cryptojs Hmac Using Python"