How to check for Python, the key associated with the certificate or not
Question: I know that the blocks modulus in the certificate and private key must be the
same if they are related. But how this can be checked by using Python? I am
looking for a solution to the OpenSSL library, but I found none. Please tell
me the solution, how to understand what the certificate and private key
associated with using Python. If the private key is not encrypted in the
format PEM, a certificate in PEM format. Preferably using standard libraries.
Without using OpenSSL through the subprocess  
Thanks.


Answer: There is a Python interface to the OpenSSL library : pyOpenSSL currently in
version 0.13.1.

EDIT : The answer to the question...

**Verify that a private key matches a certificate with PyOpenSSL** :

    
    
    import OpenSSL.crypto
    from Crypto.Util import asn1
    
    c=OpenSSL.crypto
    
    # The certificate - an X509 object
    cert=...
    
    # The private key - a PKey object
    priv=...
    
    pub=cert.get_pubkey()
    
    # Only works for RSA (I think)
    if pub.type()!=c.TYPE_RSA or priv.type()!=c.TYPE_RSA:
        raise Exception('Can only handle RSA keys')
    
    # This seems to work with public as well
    pub_asn1=c.dump_privatekey(c.FILETYPE_ASN1, pub)
    priv_asn1=c.dump_privatekey(c.FILETYPE_ASN1, priv)
    
    # Decode DER
    pub_der=asn1.DerSequence()
    pub_der.decode(pub_asn1)
    priv_der=asn1.DerSequence()
    priv_der.decode(priv_asn1)
    
    # Get the modulus
    pub_modulus=pub_der[1]
    priv_modulus=priv_der[1]
    
    if pub_modulus==priv_modulus:
        print('Match')
    else:
        print('Oops')
    

_(Source :<http://www.v13.gr/blog/?p=325>)_

