需要帮助以Python密码学库验证签名 [英] Need help verifying a signature with the Python Cryptography library

查看:166
本文介绍了需要帮助以Python密码学库验证签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python密码学库来验证签名,如此处
所述

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

这是在客户端服务器TCP聊天应用程序的上下文中,客户端已计算出签名,并将其发送给客户端以验证它确实是正确的服务器。签名被传递给函数进行验证。

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

我注意到正在返回0。根据密码学规范,看起来好像verifier.verify()失败会返回异常,所以我不知道该如何测试。

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.

推荐答案

verify 引发异常或返回 None 。因此,此代码

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

if verifier.verify():
    return 1
else:
    return 0

始终返回0,即使实际上验证检查已通过。您是正确的,使用 verify 的正确方法是将其包装在try块中并处理 InvalidSignature 异常,失败的事件。

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.

这篇关于需要帮助以Python密码学库验证签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆