Sample code for 30+ languages & platforms
Ruby Requires Chilkat v11.0.0+

Sign and encrypt an email with S/MIME

See more Email Object Examples

Use the sender’s signing PFX and the recipient’s public RSA certificate with with-attachments.eml, which has one recipient. Supply your own signing-key password from a credential store. Render to bytes to apply both S/MIME operations without connecting to SMTP.

Chilkat Ruby Downloads

Ruby
require 'chilkat'

success = false

#  Assumes Chilkat is unlocked. See Global Unlock Sample.

email = Chilkat::CkEmail.new()
success = email.LoadEml("with-attachments.eml")
if (success != true)
    print email.lastErrorText() + "\n";
    exit
end

signer = Chilkat::CkCert.new()
success = signer.LoadPfxFile("signer.pfx","SIGNER_PASSWORD")
if (success != true)
    print signer.lastErrorText() + "\n";
    exit
end

recipient = Chilkat::CkCert.new()
success = recipient.LoadFromFile("recipient.cer")
if (success != true)
    print recipient.lastErrorText() + "\n";
    exit
end

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

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

email.put_SigningHashAlg("sha256")
email.put_Pkcs7CryptAlg("aes")
email.put_Pkcs7KeyLength(256)
email.put_OaepPadding(true)
email.put_OaepHash("sha256")
email.put_OaepMgfHash("sha256")
email.put_SendSigned(true)
email.put_SendEncrypted(true)
mail = Chilkat::CkMailMan.new()
rendered = Chilkat::CkBinData.new()
success = mail.RenderToMimeBd(email,rendered)
if (success != true)
    print mail.lastErrorText() + "\n";
    exit
end

success = rendered.WriteFile("signed-encrypted.eml")
if (success != true)
    print "Failed: rendered.WriteFile." + "\n";
    exit
end

print "Saved signed-encrypted.eml." + "\n";