Search code examples
pythongoogle-cloud-platformpublic-key-encryptionpempfx

Getting Public Key from a .pfx Certficate in Python


I do this to process a pfx certificate, by writing out a pem file.

How can I also pull out the public_key? I noticed there is no get_publickey() method for the p12 object.

import contextlib
import OpenSSL.crypto
import os
import requests
import ssl
import tempfile
pfx_password = 'thiscertpassword' 
tpem = 'temppem.pem' 
pfxfile = 'fts.pfx' 


f_pem = open(tpem, 'wb')
pfx = open(pfxfile, 'rb').read()
p12 = OpenSSL.crypto.load_pkcs12(pfx, pfx_password)

f_pem.write(OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, 
p12.get_privatekey()))
#f_pem.write(OpenSSL.crypto.dump_publickey(OpenSSL.crypto.FILETYPE_PEM,  
p12.get_publickey()))  # NO SUCH METHOD 
f_pem.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, 
p12.get_certificate()))

Solution

  • Example code to extract the Public Key suitable to be written to a file or for futher processing such as valdating a Signed-JWT. The important point is that the Public Key is extracted from the Certificate.

    I use this code with Google Service Account P12 Credentials.

    The Public Key that this code generates will look like this:

    b'-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFDEADbeefMIIBCgKCAQEA5vFQucW2JW2WBhLI3dB0\n8OIkgCJPJDxoJ65kphmFSB2ZWsejV/iSecoIBYLyD2+HdHJm8pUgOOy05lm07gei\n0BRqLNYtUk2nlQIMoLPXxv23+VOWdpN/mYUsRhRwB13Aq4BybxObq+c7b08YWitI\nEtPmSEv+YkKlpcGzQcfctT7GNjjBqWuUuM1dxAqJll6JIEGAWEsDeTh9YOqnBnRb\nAWxI62D9/9bVnLkRWv0S9gfOZLuboVBhBSbHQyjbeefDeAd1J6nToug7wdxC66r1\n55lLzf9Ow9KPlsj30d6Alv59xX9QEU3MfIEfyxGiIHNTX6g8A3XUHOtgdmDyVB//\nXwIDAQAB\n-----END PUBLIC KEY-----\n'
    

    Python 3.x code:

    import OpenSSL.crypto
    
    def load_public_key(pfx_path, pfx_password):
            ''' Read the public key and return as PEM encoded '''
    
            # print('Opening:', pfx_path)
            with open(pfx_path, 'rb') as f:
                    pfx_data = f.read()
    
            # print('Loading PFX contents:')
            pfx = OpenSSL.crypto.load_pkcs12(pfx_data, pfx_password)
    
            public_key = OpenSSL.crypto.dump_publickey(
                    OpenSSL.crypto.FILETYPE_PEM,
                    pfx.get_certificate().get_pubkey())   # Change to pfx.
    
            print(public_key)
    
            return public_key