Sample code for 30+ languages & platforms
Xbase++ Requires Chilkat v10.1.2+

Create PKCS7 Signed File (.p7m)

See more Encryption Examples

Demonstrates how to sign a file to create a .p7m that contains both the file contents and the signature.

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oCrypt
LOCAL oCertStore
LOCAL oJsonCN
LOCAL oCert
LOCAL cInFile
LOCAL cOutFile

nSuccess := 0

//  This example requires the Chilkat API to have been previously unlocked.
//  See Global Unlock Sample for sample code.

oCrypt := CreateObject("Chilkat.Crypt2")

oCertStore := CreateObject("Chilkat.CertStore")

//  Load a PFX file into a certificate store object.
nSuccess := oCertStore:LoadPfxFile("myPfx.pfx", "pfxPassword")
IF (nSuccess != 1)
    ? oCertStore:LastErrorText
    oCrypt:destroy()
    oCertStore:destroy()
    RETURN
ENDIF

//  Get the certificate by subject common name.
//  This should be the cert within the PFX that also
//  has a private key (also stored within the PFX).
oJsonCN := CreateObject("Chilkat.JsonObject")
oJsonCN:UpdateString("CN", "myCert")
oCert := CreateObject("Chilkat.Cert")
nSuccess := oCertStore:FindCert(oJsonCN, oCert)
IF (nSuccess == 0)
    ? oCertStore:LastErrorText
    oCrypt:destroy()
    oCertStore:destroy()
    oJsonCN:destroy()
    oCert:destroy()
    RETURN
ENDIF

//  Tell the crypt object to use the certificate for signing:
nSuccess := oCrypt:SetSigningCert(oCert)

//  Sign a file, producing a .p7m as output.
//  The input file is unchanged, the test.p7m contains the 
//  contents of the input file and the signature.
cInFile := "test.txt"
cOutFile := "testp7m"
nSuccess := oCrypt:CreateP7M(cInFile, cOutFile)
IF (nSuccess != 1)
    ? oCrypt:LastErrorText
    oCrypt:destroy()
    oCertStore:destroy()
    oJsonCN:destroy()
    oCert:destroy()
    RETURN
ENDIF

? "Success!"

oCrypt:destroy()
oCertStore:destroy()
oJsonCN:destroy()
oCert:destroy()