Amanda_Panda Amanda_Panda - 1 year ago 91
Python Question

Need help verifying a signature with the Python Cryptography library

I'm trying to verify a signature using the Python Cryptography library as stated
enter image description here

This is in the context of a client-server TCP chat app, and the client has calculated the signature, and sent it to the client to verify that it is indeed the correct server. The signature is passed to a function to verify.

def VerifySignature(signature):
with open("server_publickey.pem", "rb") as key_file:
public_key = serialization.load_pem_public_key(,
verifier = public_key.verifier(

message = b"the message that the server verified"
if verifier.verify():
return 1
return 0

I notice that 0 is being returned. According to the Cryptography specs, it looks like if the verifier.verify() fails it returns an exception, so I don't know how else to test this.

Answer Source

verify raises an exception or returns None. Accordingly, this code

if verifier.verify():
    return 1
    return 0

will always return 0 even though in reality the verification check has passed. You are correct that the proper way to use verify is to wrap it in a try block and handle the InvalidSignature exception in the event of failure.