Since the M2Crypto library is not available for Python 3, I am looking for a way to read in the X509 certificate, extract the public key from it, and use it to encrypt RSA.
I currently have the following two functions:
from ssl import PEM_cert_to_DER_cert
from Crypto.Util import asn1
from OpenSSL.crypto import *
def extract_publickey_1(certstr):
""" from http://stackoverflow.com/questions/12911373 """
der = PEM_cert_to_DER_cert(certstr)
cert = asn1.DerSequence()
cert.decode(der)
tbs = asn1.DerSequence()
tbs.decode(cert[0])
return tbs[6]
def extract_publickey_2(certstr):
return dump_privatekey(FILETYPE_ASN1,
load_certificate(FILETYPE_PEM, certstr).get_pubkey())
The first function calls IndexErrorfor some certificates, especially those that were not created from the OpenSSL command line, but rather some cryptographic library (python and C # libs have been tested.) It works for generated OpenSSL certificates on the command line.
I examined the output of the second function and was not identical to the first, but the last 266 bytes of output are equivalent:
extract_publickey_1(certstr)[-266:] == extract_publickey_2(certstr)[-266:]
returns True.
My question is: what is going on here? Is there a solution for this?