Sample code for 30+ languages & platforms
PowerBuilder

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 PowerBuilder Downloads

PowerBuilder
integer li_rc
integer li_Success
oleobject loo_Pfx
oleobject loo_PrivKey
oleobject loo_Cert
oleobject loo_Chain

li_Success = 0

loo_Pfx = create oleobject
li_rc = loo_Pfx.ConnectToNewObject("Chilkat.Pfx")
if li_rc < 0 then
    destroy loo_Pfx
    MessageBox("Error","Connecting to COM object failed")
    return
end if

//  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.
loo_PrivKey = create oleobject
li_rc = loo_PrivKey.ConnectToNewObject("Chilkat.PrivateKey")

li_Success = loo_PrivKey.LoadPemFile("qa_data/private_key.pem")
if li_Success = 0 then
    Write-Debug loo_PrivKey.LastErrorText
    destroy loo_Pfx
    destroy loo_PrivKey
    return
end if

//  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.
loo_Cert = create oleobject
li_rc = loo_Cert.ConnectToNewObject("Chilkat.Cert")

li_Success = loo_Cert.LoadFromFile("qa_data/cert.pem")
if li_Success = 0 then
    Write-Debug loo_Cert.LastErrorText
    destroy loo_Pfx
    destroy loo_PrivKey
    destroy loo_Cert
    return
end if

loo_Chain = create oleobject
li_rc = loo_Chain.ConnectToNewObject("Chilkat.CertChain")

li_Success = loo_Cert.BuildCertChain(loo_Chain)
if li_Success = 0 then
    Write-Debug loo_Cert.LastErrorText
    destroy loo_Pfx
    destroy loo_PrivKey
    destroy loo_Cert
    destroy loo_Chain
    return
end if

//  Add the private key and its certificate chain to the PFX.
li_Success = loo_Pfx.AddPrivateKey(loo_PrivKey,loo_Chain)
if li_Success = 0 then
    Write-Debug loo_Pfx.LastErrorText
    destroy loo_Pfx
    destroy loo_PrivKey
    destroy loo_Cert
    destroy loo_Chain
    return
end if

Write-Debug "Private key and certificate chain added to the PFX."


destroy loo_Pfx
destroy loo_PrivKey
destroy loo_Cert
destroy loo_Chain