How do I use PyOpenSSL to read a PFX file?
Asked Answered
O

1

3

How to use pyopenssl to read a pfx file? And how to sign an XML with this SSL certificate?

I'm still having trouble understanding how to read, but I also have no idea how to sign. I thought I'd use the pip signxml library but I do not know if that's the way.

My code so far:

import OpenSSL

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,
                p12.get_certificate().get_pubkey())

        print(public_key)

        return public_key

teste = load_public_key("certificates/myfile.pfx", 'mypass')

I need to read a script, sign any XML and get a string with that xml.

Owsley answered 22/7, 2019 at 21:38 Comment(1)
OpenSSL says now: DeprecationWarning: PKCS#12 support in pyOpenSSL is deprecated. You should use the APIs in cryptography.Fiesole
O
1

After some research I came to the following result:

from OpenSSL.crypto import *
import os

passwd = 'my_pass'
cd = 'my_folder'

p12 = load_pkcs12(open(cd + 'file.pfx', 'rb').read(), passwd)

pkey = p12.get_privatekey()
open(cd + 'pkey.pem', 'wb').write(dump_privatekey(FILETYPE_PEM, pkey))

cert = p12.get_certificate()
open(cd + 'cert.pem', 'wb').write(dump_certificate(FILETYPE_PEM, 
cert))

ca_certs = p12.get_ca_certificates()
ca_file = open(cd + 'ca.pem', 'wb')
for ca in ca_certs:
     ca_file.write(dump_certificate(FILETYPE_PEM, ca))
Owsley answered 29/7, 2019 at 22:45 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.