PureBasic
PureBasic
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 PureBasic Downloads
IncludeFile "CkCert.pb"
IncludeFile "CkPrivateKey.pb"
IncludeFile "CkCertChain.pb"
IncludeFile "CkPfx.pb"
Procedure ChilkatExample()
success.i = 0
pfx.i = CkPfx::ckCreate()
If pfx.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
; 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.
privKey.i = CkPrivateKey::ckCreate()
If privKey.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
success = CkPrivateKey::ckLoadPemFile(privKey,"qa_data/private_key.pem")
If success = 0
Debug CkPrivateKey::ckLastErrorText(privKey)
CkPfx::ckDispose(pfx)
CkPrivateKey::ckDispose(privKey)
ProcedureReturn
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.
cert.i = CkCert::ckCreate()
If cert.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
success = CkCert::ckLoadFromFile(cert,"qa_data/cert.pem")
If success = 0
Debug CkCert::ckLastErrorText(cert)
CkPfx::ckDispose(pfx)
CkPrivateKey::ckDispose(privKey)
CkCert::ckDispose(cert)
ProcedureReturn
EndIf
chain.i = CkCertChain::ckCreate()
If chain.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
success = CkCert::ckBuildCertChain(cert,chain)
If success = 0
Debug CkCert::ckLastErrorText(cert)
CkPfx::ckDispose(pfx)
CkPrivateKey::ckDispose(privKey)
CkCert::ckDispose(cert)
CkCertChain::ckDispose(chain)
ProcedureReturn
EndIf
; Add the private key and its certificate chain to the PFX.
success = CkPfx::ckAddPrivateKey(pfx,privKey,chain)
If success = 0
Debug CkPfx::ckLastErrorText(pfx)
CkPfx::ckDispose(pfx)
CkPrivateKey::ckDispose(privKey)
CkCert::ckDispose(cert)
CkCertChain::ckDispose(chain)
ProcedureReturn
EndIf
Debug "Private key and certificate chain added to the PFX."
CkPfx::ckDispose(pfx)
CkPrivateKey::ckDispose(privKey)
CkCert::ckDispose(cert)
CkCertChain::ckDispose(chain)
ProcedureReturn
EndProcedure