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

Ruby
require 'chilkat'

success = false

#  Assumes Chilkat is unlocked. See Global Unlock Sample.

email = Chilkat::CkEmail.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.
pem = Chilkat::CkPem.new()
success = pem.LoadPemFile("recipient.pem","RECIPIENT_PASSWORD")
if (success != true)
    print pem.lastErrorText() + "\n";
    exit
end

success = email.AddPemSource(pem)
if (success != true)
    print email.lastErrorText() + "\n";
    exit
end

success = email.LoadEml("signed-encrypted.eml")
if (success != true)
    print email.lastErrorText() + "\n";
    exit
end

if ((email.get_ReceivedEncrypted() != true) or (email.get_Decrypted() != true))
    print "Expected a successfully decrypted S/MIME envelope." + "\n";
    exit
end

if ((email.get_ReceivedSigned() != true) or (email.get_SignaturesValid() != true))
    print "Expected a valid signature inside the envelope." + "\n";
    exit
end

#  This message has one signer. Examine its certificate after verification.
signer = Chilkat::CkCert.new()
success = email.LastSignerCert(0,signer)
if (success != true)
    print email.lastErrorText() + "\n";
    exit
end

print "Signer certificate: " + signer.subjectDN() + "\n";
print "Recovered subject: " + email.subject() + "\n";
print "Recovered attachments: " + email.get_NumAttachments().to_s() + "\n";