Sample code for 30+ languages & platforms
Lua Requires Chilkat v11.8.0+

Decrypt an S/MIME email and verify its signature

See more Email Object Examples

Register the recipient’s certificate and private key (from a PEM file) before opening signed-encrypted.eml. This workflow expects both encryption and a signature, so it checks both layers before reading the message. Cryptographic signature validity is one input to a signer-trust decision.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- Assumes Chilkat is unlocked. See Global Unlock Sample.

local email = chilkat.Email.new()
-- The recipient's certificate and private key are in a PEM file.  The 2nd argument of LoadPemFile
-- is the password of the private key.
local pem = chilkat.Pem.new()
local success = pem:load_pem_file("recipient.pem", "RECIPIENT_PASSWORD")
if not success then
    print(pem.last_error_text)
    return
end

success = email:add_pem_source(pem)
if not success then
    print(email.last_error_text)
    return
end

success = email:load_eml("signed-encrypted.eml")
if not success then
    print(email.last_error_text)
    return
end

if (not email.received_encrypted) or (not email.decrypted) then
    print("Expected a successfully decrypted S/MIME envelope.")
    return
end

if (not email.received_signed) or (not email.signatures_valid) then
    print("Expected a valid signature inside the envelope.")
    return
end

-- This message has one signer. Examine its certificate after verification.
local signer = chilkat.Cert.new()
success = email:last_signer_cert(0, signer)
if not success then
    print(email.last_error_text)
    return
end

print("Signer certificate: " .. signer.subject_dn)
print("Recovered subject: " .. email.subject)
print("Recovered attachments: " .. email.num_attachments)