I am trying to create a script which verifies a signature using a public key.
The payload-signature input parameter has a format as follows:
t=1616635947,v=bhadkjl;fghklj;akdfnbkljnbkljfdnbklnbk
Where v is the timestamp when the signature is created and v is signature on the SHA512 hash of the string value of t + "." + payload. For example 1616635947.{randomdataqwertyuiop}
When I run my script I get the following error
Traceback (most recent call last):
File "C:\Users\me\PycharmProjects\pythonProject\main.py", line 48, in <module>
result = verify_signature(x_payload_signature, public_key, payload)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\me\PycharmProjects\pythonProject\main.py", line 26, in verify_signature
pkcs1_15.new(rsa_key).verify(h, signature)
File "C:\Users\me\PycharmProjects\pythonProject\venv\Lib\site-packages\Crypto\Signature\pkcs1_15.py", line 120, in verify
possible_em1 = [ _EMSA_PKCS1_V1_5_ENCODE(msg_hash, k, True) ]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\me\PycharmProjects\pythonProject\venv\Lib\site-packages\Crypto\Signature\pkcs1_15.py", line 191, in _EMSA_PKCS1_V1_5_ENCODE
digestAlgo = DerSequence([ DerObjectId(msg_hash.oid).encode() ])
^^^^^^^^^^^^
AttributeError: '_hashlib.HASH' object has no attribute 'oid'
Here is my code for reference
import base64
from hashlib import sha512
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
def verify_signature(payload_signature: str, pub_key: str, payload: str):
# create public key
key_der = base64.b64decode(pub_key)
rsa_key = RSA.importKey(key_der)
# split payload signature into timestamp and signature
parts = payload_signature.split(",")
timestamp = parts[0].split("=")[1]
sig_to_verify = parts[1][2:]
# Update signature object with 'timestamp.payload'
v = timestamp + "." + payload
message = v.encode("utf-8")
# Verify signature
signature = base64.b64decode(sig_to_verify)
h = sha512(message)
try:
pkcs1_15.new(rsa_key).verify(h, signature)
print("The signature is valid.")
except (ValueError, TypeError):
print("The signature is not valid.")