Pyopenssl来验证文件signatu

2024-05-14 05:57:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用pyopenssl验证下载文件的签名和证书,但是文档不清楚,Google也帮不上忙。在

我有一个根CA证书在用户的机器,现在当用户下载文件,然后我会发送一个证书和签名连同它。首先我需要在机器上用rootCA验证证书,然后用文件验证签名

在openssl中,我可以使用以下命令来验证ca证书

openssl verify -CAfile <root_pem> <cert_pem>

并跟踪以验证文件

^{pr2}$

我正在寻找使用python实现它的等效方法,最好是pyopenssl


Tags: 文件用户文档命令机器googlepemca
1条回答
网友
1楼 · 发布于 2024-05-14 05:57:27

我还在学习OpenSSL,更不用说PyOpenSSL了。说到这里,我可以使用以下命令验证PyOpenSSL中的文件(您的第二个命令):

from OpenSSL.crypto import load_publickey, FILETYPE_PEM, verify, X509

with open(file_to_verify, 'rb') as f:
    file_data = f.read()

with open(signature_filename, 'rb') as f:
    signature = f.read()

with open(public_key_filename) as f:
    public_key_data = f.read()

# load in the publickey file, in my case, I had a .pem file.
# If the file starts with
#     "  -BEGIN PUBLIC KEY  -"
# then it is of the PEM type. The only other FILETYPE is
# "FILETYPE_ASN1".
pkey = load_publickey(FILETYPE_PEM, public_key_data)

# the verify() function expects that the public key is
# wrapped in an X.509 certificate
x509 = X509()
x509.set_pubkey(pkey)

# perform the actual verification. We need the X509 object,
# the signature to verify, the file to verify, and the
# algorithm used when signing.
verify(x509, signature, file_data, 'sha256')

如果验证成功,verify()函数将返回None,或者在出现错误时引发异常。在

相关问题 更多 >