As the M2Crypto library is not available for Python 3, I'm looking for a way to read in an X509 certificate, extract the public key from it and use it for RSA encryption.
I currently have the following two functions:
from ssl import PEM_cert_to_DER_cert # standard library
from Crypto.Util import asn1 # http://pycrypto.org
from OpenSSL.crypto import * # https://pythonhosted.org/pyOpenSSL/
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 raises an IndexError
for some certificates, specially the ones that were not generated from command-line OpenSSL but rather some cryptographic library (python and c# libs were tested.) It works for command-line OpenSSL generated certificates.
I've examined the output of the second function and it wasn't identical to the first one, but the last 266 bytes of the output is equivalent:
extract_publickey_1(certstr)[-266:] == extract_publickey_2(certstr)[-266:]
returns True
.
My question is, what's going on here? Is there a solution to this?