Sample code for 30+ languages & platforms
Lianja

Add a Private Key and Certificate Chain to a PFX

See more PFX/P12 Examples

Demonstrates Pfx.AddPrivateKey, which adds a private key together with its certificate chain to 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 chain must contain at least one certificate; the certificate at index 0 is treated as the leaf. The chain is built here with Cert.BuildCertChain.

Chilkat Lianja Downloads

Lianja
llSuccess = .F.

loPfx = createobject("CkPfx")

//  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 private key.
loPrivKey = createobject("CkPrivateKey")
llSuccess = loPrivKey.LoadPemFile("qa_data/private_key.pem")
if (llSuccess = .F.) then
    ? loPrivKey.LastErrorText
    release loPfx
    release loPrivKey
    return
endif

//  Load the certificate and build its chain of authority.  The chain must contain at least one
//  certificate; the certificate at index 0 is treated as the leaf.
loCert = createobject("CkCert")
llSuccess = loCert.LoadFromFile("qa_data/cert.pem")
if (llSuccess = .F.) then
    ? loCert.LastErrorText
    release loPfx
    release loPrivKey
    release loCert
    return
endif

loChain = createobject("CkCertChain")
llSuccess = loCert.BuildCertChain(loChain)
if (llSuccess = .F.) then
    ? loCert.LastErrorText
    release loPfx
    release loPrivKey
    release loCert
    release loChain
    return
endif

//  Add the private key and its certificate chain to the PFX.
llSuccess = loPfx.AddPrivateKey(loPrivKey,loChain)
if (llSuccess = .F.) then
    ? loPfx.LastErrorText
    release loPfx
    release loPrivKey
    release loCert
    release loChain
    return
endif

? "Private key and certificate chain added to the PFX."


release loPfx
release loPrivKey
release loCert
release loChain