Sample code for 30+ languages & platforms
Chilkat2-Python

Load Identities from PEM Text

See more PFX/P12 Examples

Demonstrates Pfx.LoadPem, which loads one or more certificate/private-key identities from PEM-formatted text and builds the contents of the Pfx object.

The file path is relative to the application's current working directory. An absolute path may also be used. Supply the path appropriate to your own environment.

Background. The password decrypts any encrypted private keys in the PEM. This builds a PFX in memory from PEM material, which can then be serialized to PKCS#12.

Chilkat Chilkat2-Python Downloads

Chilkat2-Python
import sys
import chilkat2

success = False

pfx = chilkat2.Pfx()

# The file path is relative to the application's current working directory.  An absolute path
# may also be used.  Supply the path appropriate to your own environment.
# Load the PEM text (certificates and private keys) into a string.
sbPem = chilkat2.StringBuilder()
bLoaded = sbPem.LoadFile("qa_data/identity.pem")
if (bLoaded != True):
    print("Failed to load the PEM file.")
    sys.exit()

pemText = sbPem.GetAsString()
if (sbPem.LastMethodSuccess == False):
    print(sbPem.LastErrorText)
    sys.exit()

# The password decrypts any encrypted private keys in the PEM (use an empty string if none are
# encrypted).  A password should come from a secure source rather than being hard-coded.
password = "myPemPassword"
success = pfx.LoadPem(pemText,password)
if (success == False):
    print(pfx.LastErrorText)
    sys.exit()

print("Loaded " + str(pfx.NumPrivateKeys) + " private key(s).")