Amanda_Panda Amanda_Panda - 1 month ago 13
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
here https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/
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(
key_file.read(),
#password=None,
backend=default_backend()
)
verifier = public_key.verifier(
signature,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)

message = b"the message that the server verified"
verifier.update(message)
if verifier.verify():
return 1
else:
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

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

if verifier.verify():
    return 1
else:
    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.

Comments