PyOpenSSL "openssl check -CAfile root.crt client.crt" equivalent

I have two certificates: root.crtand client.crt, signed root.key.
I want to check what is client.crtreally signed root.key, for this, using openssl on the terminal, I like the following:

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

But when using pyOpenSSL, following the documentation and this blog post , I tried something like this:

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()  

But then I get this error:

X509StoreContextError: [2, 1, 'cannot obtain issuer certificate']

So what am I missing?

+6
source share
1 answer

, root.crt root, :

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

OpenSSL.crypto.load_certificate .

, X509Store.

, :

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


def parse_chain(chain):
    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 rc in parse_chain(file('root.crt').read()):
    store.add_cert(OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cr))

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

https://github.com/hynek/pem/blob/master/src/pem/_core.py#L115

+2

All Articles