简体   繁体   English

如何在 pyOpenSSL 中验证证书签名?

[英]How to verify certificate signature in pyOpenSSL?

I have two certificates, a root.crt that was used to sign client.crt .我有两个证书,一个用于签署client.crtroot.crt

I want to verify that the client.crt was indeed signed by root.key .我想验证client.crt确实由root.key签名。

Using openssl on terminal, it works like this:在终端上使用 openssl,它的工作原理是这样的:

$ openssl verify -CAfile root.crt client.crt  
> client.crt: OK  

However using pyOpenSSL - following the documentation and this blog post - I tried something like this:但是使用 pyOpenSSL - 按照文档这篇博客文章- 我尝试了这样的事情:

client_cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, file('client.crt').read())

root_cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, file('root.crt').read())  

store = OpenSSL.crypto.X509Store()  
store.add_cert(root_cert)  

ctx = OpenSSL.crypto.X509StoreContext(store, client_cert)
ctx.verify_certificate()  

I get this error:我收到此错误:

    > X509StoreContextError: [2, 1, 'unable to get issuer certificate']

What am I missing?我错过了什么?

The issue is that my root.crt is not really root, but a chain of certificates:问题是我的root.crt不是真正的 root,而是一个证书链:

-----BEGIN CERTIFICATE----- 
...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE----- 
...
-----END CERTIFICATE-----

And OpenSSL.crypto.load_certificate just loads the first one.OpenSSL.crypto.load_certificate只加载第一个。

The solution is to extract all certificates in the chain file and add them to the X509Store .解决方案是提取链文件中的所有证书并将它们添加到X509Store

The code solution looks like this:代码解决方案如下所示:

_PEM_RE = re.compile(b'-----BEGIN CERTIFICATE-----\r?.+?\r?-----END CERTIFICATE-----\r?\n?', re.DOTALL)


def parse_chain(chain):
    # returns a list of certificates
    return [c.group() for c in _PEM_RE.finditer(chain)]


client_cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, file('server.crt').read())

store = OpenSSL.crypto.X509Store()
for cert in parse_chain(file('root.crt').read()):
    store.add_cert(OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert))

ctx = OpenSSL.crypto.X509StoreContext(store, client_cert)
ctx.verify_certificate()

Adapted from https://github.com/hynek/pem/blob/master/src/pem/_core.py#L115改编自https://github.com/hynek/pem/blob/master/src/pem/_core.py#L115

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM