如何使用Python向证书颁发机构认证公钥?

2024-06-25 06:47:43 发布

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

import OpenSSL

key = ...
signature = ...
data = ...

x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, key)
OpenSSL.crypto.verify(x509, signature, data, 'sha1')

到目前为止,我能够毫无问题地完成所有这些。但是,这还不够安全,因为密钥本身是通过一个URL(我应该信任它)提供给我的,并且构建签名的方法是公开的。在

那么,假设密钥被“VeriSign Class 3 Code Signing 2010 CA”验证,有人能告诉我如何检查这是一个有效的声明吗?在

我想我需要在我的机器上本地安装VeriSign证书。假设我有,那我该怎么办?在

谢谢!在

*在JSON请求中,URL作为参数提供给我。当然,网址将是HTTPS,我可以检查域名等。但看起来我应该检查一下证书本身


Tags: keyimporturldata密钥loadcertificatecrypto
2条回答

也许我只是部分地回答了你的问题。您最大的担心似乎是您获取密钥的通道的安全性。您没有显示您如何获取该密钥的任何代码,但您说您通过HTTPS检索它,现在您希望通过证书验证来验证此连接的真实性。在

使用成熟的第三方web客户机框架requests,您可以轻松地做到这一点。在

引自the docs

Requests can verify SSL certificates for HTTPS requests, just like a web browser. To check a host’s SSL certificate, you can use the verify argument:

requests.get(url, verify=True)

同时:

You can pass verify the path to a CA_BUNDLE file with certificates of trusted CAs.

后者可能看起来像

^{pr2}$

如果您真的想控制(并降低复杂性),那么从http://www.symantec.com/page.jsp?id=roots加载正确的文件并采用verify='/path/to/cert.pem'方法。我想你需要http://www.symantec.com/content/en/us/enterprise/verisign/roots/Class-3-Public-Primary-Certification-Authority-G2.pem

你应该检查证书本身是对的。是的,您需要VeriSign根证书(以及任何其他中间证书,以拥有完整的信任链)来对证书进行签名以进行检查。在

当前的Symantec(VeriSign)根证书可以在zipfile中找到here。在

下载并解压缩zip文件,找到您希望信任的所有证书,并将它们(以pem格式)放在一个证书捆绑文件中。在

现在你需要做实际的验证。不幸的是,您需要的OpenSSL调用是X509_verify_certificate。我查看了pyopenssl和M2Crypto的源代码,但都没有公开该调用,因此没有直接的Python代码可以调用来验证这些包中的任何一个。在

但是,由于您使用的是pyopenssl,因此显然可以使用openssl库。因此,您可能已经或可以轻松地安装openssl命令行工具集。如果是这样,可以通过管道调用opensslverify命令,方法如下:

cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, key)
# the command like likes pem format
cert_pem = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)

# the bundle that you created from the zip extraction
certificate_bundle = 'verisign-root-bundle.pem'

# Pipe the cert to the openssl verify command and check the return code
# a return code of 0 is successful verify
import subprocess
p = subprocess.Popen(['openssl', 'verify', '-CAfile', certificate_bundle],
                     stdin=subprocess.PIPE)
p.communicate(input=cert_pem)
p.wait()
if (p.returncode == 0):
    print('Certificate Verified.')
else:
    print('Problem with certificate')

上面的管道运行命令

^{pr2}$

最后,如果您不熟悉openssl,那么显示证书的命令是

openssl x509 -inform PEM -text -in certificate.pem

希望这有帮助!在

相关问题 更多 >