Sample code for 30+ languages & platforms
Tcl

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

Tcl

load ./chilkat.dll

set success 0

set pfx [new_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.
set privKey [new_CkPrivateKey]

set success [CkPrivateKey_LoadPemFile $privKey "qa_data/private_key.pem"]
if {$success == 0} then {
    puts [CkPrivateKey_lastErrorText $privKey]
    delete_CkPfx $pfx
    delete_CkPrivateKey $privKey
    exit
}

#  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.
set cert [new_CkCert]

set success [CkCert_LoadFromFile $cert "qa_data/cert.pem"]
if {$success == 0} then {
    puts [CkCert_lastErrorText $cert]
    delete_CkPfx $pfx
    delete_CkPrivateKey $privKey
    delete_CkCert $cert
    exit
}

set chain [new_CkCertChain]

set success [CkCert_BuildCertChain $cert $chain]
if {$success == 0} then {
    puts [CkCert_lastErrorText $cert]
    delete_CkPfx $pfx
    delete_CkPrivateKey $privKey
    delete_CkCert $cert
    delete_CkCertChain $chain
    exit
}

#  Add the private key and its certificate chain to the PFX.
set success [CkPfx_AddPrivateKey $pfx $privKey $chain]
if {$success == 0} then {
    puts [CkPfx_lastErrorText $pfx]
    delete_CkPfx $pfx
    delete_CkPrivateKey $privKey
    delete_CkCert $cert
    delete_CkCertChain $chain
    exit
}

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

delete_CkPfx $pfx
delete_CkPrivateKey $privKey
delete_CkCert $cert
delete_CkCertChain $chain