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

Sign a File to Create a .p7m File (using a PFX)

See more Encryption Examples

_LANGUAGE_ example to sign a file creating a .p7m file as output. The .p7m contains the signed contents of the original file. It can be verified and restored by calling VerifyP7M.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

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

local crypt = chilkat.Crypt2.new()

-- Use a digital certificate and private key from a PFX file (.pfx or .p12).
local signingCertSubject = "Acme Inc"
local pfxFilename = "/Users/chilkat/testData/pfx/acme.pfx"
local pfxPassword = "test123"

local certStore = chilkat.CertStore.new()
local success = certStore:load_pfx_file(pfxFilename, pfxPassword)
if not success then
    print(certStore.last_error_text)
    return
end

local jsonCN = chilkat.JsonObject.new()
jsonCN:update_string("CN", signingCertSubject)

local cert = chilkat.Cert.new()
success = certStore:find_cert(jsonCN, cert)
if not success then
    print("Failed to find certificate by subject common name.")
    return
end

-- Tell the crypt component to use this cert.
success = crypt:set_signing_cert(cert)

-- We can sign any type of file, creating a .p7m as output:
local inFile = "/Users/chilkat/testData/pdf/sample.pdf"
local outputFile = "/Users/chilkat/testData/p7m/sample.pdf.p7m"
success = crypt:create_p7_m(inFile, outputFile)
if not success then
    print(crypt.last_error_text)
    return
end

-- Verify and restore the original file:
success = crypt:set_verify_cert(cert)

inFile = outputFile
outputFile = "/Users/chilkat/testData/pdf/restored.pdf"

success = crypt:verify_p7_m(inFile, outputFile)
if not success then
    print(crypt.last_error_text)
    return
end

print("Success!")