Need help verifying a signature with the Python Cryptography library
<p>I'm trying to verify a signature using the Python Cryptography library as stated
here <a href="https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/" rel="nofollow">https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/</a>
<a href="http://i.stack.imgur.com/I4INn.png" rel="nofollow"><img src="http://i.stack.imgur.com/I4INn.png" alt="enter image description here"></a></p>

<p>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.</p>

<pre><code>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
</code></pre>

<p>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.</p>

<p><code>verify</code> raises an exception or returns <code>None</code>. Accordingly, this code</p>

<pre><code>if verifier.verify():
    return 1
else:
    return 0
</code></pre>

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

python python-3.x rsa digital-signature