Sample code for 30+ languages & platforms
Xbase++

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 Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oPfx
LOCAL oSbPem
LOCAL nBLoaded
LOCAL cPemText
LOCAL cPassword

nSuccess := 0

oPfx := CreateObject("Chilkat.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.
oSbPem := CreateObject("Chilkat.StringBuilder")
nBLoaded := oSbPem:LoadFile("qa_data/identity.pem")
IF (nBLoaded != 1)
    ? "Failed to load the PEM file."
    oPfx:destroy()
    oSbPem:destroy()
    RETURN
ENDIF

cPemText := oSbPem:GetAsString()
IF (oSbPem:LastMethodSuccess == 0)
    ? oSbPem:LastErrorText
    oPfx:destroy()
    oSbPem:destroy()
    RETURN
ENDIF

//  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.
cPassword := "myPemPassword"
nSuccess := oPfx:LoadPem(cPemText, cPassword)
IF (nSuccess == 0)
    ? oPfx:LastErrorText
    oPfx:destroy()
    oSbPem:destroy()
    RETURN
ENDIF

? "Loaded " + Str(oPfx:NumPrivateKeys) + " private key(s)."

oPfx:destroy()
oSbPem:destroy()