Sample code for 30+ languages & platforms
PowerBuilder 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 PowerBuilder Downloads

PowerBuilder
integer li_rc
long li_Success
oleobject loo_Email
oleobject loo_Pem
oleobject loo_Signer

li_Success = 0

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

loo_Email = create oleobject
li_rc = loo_Email.ConnectToNewObject("Chilkat.Email")
if li_rc < 0 then
    destroy loo_Email
    MessageBox("Error","Connecting to COM object failed")
    return
end if
//  The recipient's certificate and private key are in a PEM file.  The 2nd argument of LoadPemFile
//  is the password of the private key.
loo_Pem = create oleobject
li_rc = loo_Pem.ConnectToNewObject("Chilkat.Pem")

li_Success = loo_Pem.LoadPemFile("recipient.pem","RECIPIENT_PASSWORD")
if li_Success <> 1 then
    Write-Debug loo_Pem.LastErrorText
    destroy loo_Email
    destroy loo_Pem
    return
end if

li_Success = loo_Email.AddPemSource(loo_Pem)
if li_Success <> 1 then
    Write-Debug loo_Email.LastErrorText
    destroy loo_Email
    destroy loo_Pem
    return
end if

li_Success = loo_Email.LoadEml("signed-encrypted.eml")
if li_Success <> 1 then
    Write-Debug loo_Email.LastErrorText
    destroy loo_Email
    destroy loo_Pem
    return
end if

if (loo_Email.ReceivedEncrypted <> 1) OR (loo_Email.Decrypted <> 1) then
    Write-Debug "Expected a successfully decrypted S/MIME envelope."
    destroy loo_Email
    destroy loo_Pem
    return
end if

if (loo_Email.ReceivedSigned <> 1) OR (loo_Email.SignaturesValid <> 1) then
    Write-Debug "Expected a valid signature inside the envelope."
    destroy loo_Email
    destroy loo_Pem
    return
end if

//  This message has one signer. Examine its certificate after verification.
loo_Signer = create oleobject
li_rc = loo_Signer.ConnectToNewObject("Chilkat.Cert")

li_Success = loo_Email.LastSignerCert(0,loo_Signer)
if li_Success <> 1 then
    Write-Debug loo_Email.LastErrorText
    destroy loo_Email
    destroy loo_Pem
    destroy loo_Signer
    return
end if

Write-Debug "Signer certificate: " + loo_Signer.SubjectDN
Write-Debug "Recovered subject: " + loo_Email.Subject
Write-Debug "Recovered attachments: " + string(loo_Email.NumAttachments)


destroy loo_Email
destroy loo_Pem
destroy loo_Signer