Python vs Matlab HMAC256

4 次查看(过去 30 天)
Chris Eguires
Chris Eguires 2021-1-9
回答: Pratik 2023-10-18
Hi all, I am trying to figure out why I have a discrepensy between my python code and my Matlab code. I am trying to get sign_char to match the python output signature_b64. I have spent hours trying different methods, and have had no luck. If there is anything obviously wrong, please let me know!
Matlab Code
secret = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
msg = '123'
hash256_class = System.Security.Cryptography.SHA256Managed.Create();
challenge_hash = uint8(hash256_class.ComputeHash(uint8(msg)));
secret_uint8 = matlab.net.base64decode(secret);
hmac256_class = System.Security.Cryptography.HMACSHA256(secret_uint8);
sign_uint8 = uint8(hmac256_class.ComputeHash(challenge_hash));
sign_char = matlab.net.base64encode(sign_uint8);
sign_char = uFpcDGx9zh1PBhdfDed+HaJjnfX7PxRt24weAj8DO8w=
Python Code
import hmac
import hashlib
import time
import base64
from requests.auth import AuthBase
secret_key = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
message1 = '123'
message = message1.encode('ascii')
hmac_key = base64.b64decode(secret_key)
signature = hmac.new(hmac_key, message, hashlib.sha256)
signature_b64 = base64.b64encode(signature.digest()).decode('utf-8')
signature_b64
Out[50]: 'ndwEJbmXr9Ym52jlaSD9530PHJj69dqb0Qow8NU5zR8='

回答(1 个)

Pratik
Pratik 2023-10-18
Hi Chris,
In my understanding you are trying to get the HMAC signature of a message using MATLAB and are trying to do the same with python. However, the output of both the code is not identical.
Upon reviewing both codes, I noticed that hashing for the message is absent in the Python code. To address this, I have added the necessary hashing for the message using 'hashlib' on lines 8-10 in the Python code as shown below:
import hashlib
import base64
import hmac
secret = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
msg = '123'
hash256_class = hashlib.sha256()
challenge_hash = hash256_class.update(msg.encode())
challenge_hash = hash256_class.digest()
secret_uint8 = base64.b64decode(secret)
signature = hmac.new(secret_uint8, challenge_hash, hashlib.sha256)
signature_b64 = base64.b64encode(signature.digest()).decode('utf-8')
print(signature_b64)
#Output: uFpcDGx9zh1PBhdfDed+HaJjnfX7PxRt24weAj8DO8w=
Please refer to the following Python documentation link for more information on ‘hashlib’:
Hope this helps!

类别

Help CenterFile Exchange 中查找有关 Call Python from MATLAB 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by