Sample code for 30+ languages & platforms
Xbase++ Requires Chilkat v11.0.0+

Backup Windows Current User / Personal Certificates to a .zip

See more Certificates Examples

Demonstrates how to backup the certificates in the Windows registry-based Current User certificate store (in the "Personal" Logical Store as seen in certmgr.msc), to a zip archive. Certificates having an exportable private key are exported to .pfx files. Certificates with no private key, or with a non-exportable private key, are exported to .cer files.

Obviously, this example only runs on Windows computers.

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oCertStore
LOCAL nReadOnly
LOCAL cPfxPassword
LOCAL nAllSuccess
LOCAL nNumSuccess
LOCAL oZip
LOCAL oCertData
LOCAL oSbFilename
LOCAL oCert
LOCAL nNumCerts
LOCAL i
LOCAL nBHasPrivateKey

nSuccess := 0

oCertStore := CreateObject("Chilkat.CertStore")

nReadOnly := 1
nSuccess := oCertStore:OpenCurrentUserStore(nReadOnly)
IF (.NOT. nSuccess)
    ? oCertStore:LastErrorText
    oCertStore:destroy()
    RETURN
ENDIF

cPfxPassword := "secret"

nAllSuccess := 1
nNumSuccess := 0

oZip := CreateObject("Chilkat.Zip")
oZip:NewZip("qa_output/personalCerts.zip")

oCertData := CreateObject("Chilkat.BinData")
oSbFilename := CreateObject("Chilkat.StringBuilder")

//  Iterate over the certificates in the Current User store.
oCert := CreateObject("Chilkat.Cert")
nNumCerts := oCertStore:NumCertificates
i := 0
DO WHILE i < nNumCerts
    oCertStore:GetCert(i, oCert)
    ? "DN = " + oCert:SubjectDN

    oSbFilename:SetString("cert")
    oSbFilename:AppendInt(i + 1)

    nBHasPrivateKey := oCert:HasPrivateKey()
    IF ((nBHasPrivateKey == 1) .AND. (oCert:PrivateKeyExportable == 1))
        //  Export to a .pfx
        nSuccess := oCert:ExportToPfxBd(cPfxPassword, 1, oCertData)
        IF (nSuccess == 1)
            oSbFilename:Append(".pfx")
            oZip:AddBd(oSbFilename:GetAsString(), oCertData)
        ENDIF

    ELSE
        //  Export to a .cer
        nSuccess := oCert:ExportCertDerBd(oCertData)
        IF (nSuccess == 1)
            oSbFilename:Append(".cer")
            oZip:AddBd(oSbFilename:GetAsString(), oCertData)
        ENDIF

    ENDIF

    IF (nSuccess != 1)
        nAllSuccess := 0
    ELSE
        nNumSuccess := nNumSuccess + 1
    ENDIF

    i := i + 1
ENDDO

IF (nNumSuccess > 0)
    nSuccess := oZip:WriteZipAndClose()
    IF (nSuccess != 1)
        ? oZip:LastErrorText
        nAllSuccess := 0
    ENDIF

ENDIF

? "All success = " + Str(nAllSuccess)

oCertStore:destroy()
oZip:destroy()
oCertData:destroy()
oSbFilename:destroy()
oCert:destroy()