Need help verifying a signature with the Python Cryptography library

南笙酒味 提交于 2019-12-12 04:25:46

问题


I'm trying to verify a signature using the Python Cryptography library as stated here https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/

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.


回答1:


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.



来源:https://stackoverflow.com/questions/39402792/need-help-verifying-a-signature-with-the-python-cryptography-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!