Python 3 - Extract public key from X509 certificate and encrypt it

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  # 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 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?

+4
1

, , , X.509 ASN.1, - DER. , , .. . ( ); , " " . , get_pubkey() , , asn1.

-, , , X.509 , " RSA", " RSA" .. " ", - OID . , RSA 2 : n e; , extract_publickey_2() , , , . , RSA , ASN.1, , , asn1.DerSequence.decode() RSA .

+4

Source: https://habr.com/ru/post/1539446/


All Articles