Sample code for 30+ languages & platforms
Xbase++

Encrypt MIME for Multiple Recipients

See more MIME Examples

Demonstrates encrypting the current MIME entity for several recipients at once. A certificate is added for each recipient with AddEncryptCert, and EncryptN then produces a single CMS/PKCS #7 message that each recipient can independently decrypt.

The file paths are relative to the application's current working directory. Absolute paths may also be used. Supply the paths appropriate to your own environment.

Background. When a message targets more than one recipient, each recipient's certificate is added to the internal list and EncryptN wraps the message key separately for each one. Any single recipient can then decrypt with their own private key.

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oMime
LOCAL oCert1
LOCAL oCert2

nSuccess := 0

oMime := CreateObject("Chilkat.Mime")
nSuccess := oMime:SetBodyFromPlainText("This message will be encrypted.")
IF (nSuccess == 0)
    ? oMime:LastErrorText
    oMime:destroy()
    RETURN
ENDIF

//  Add a certificate for each intended recipient.  Every recipient receives an independently
//  wrapped copy of the message key.
oCert1 := CreateObject("Chilkat.Cert")
nSuccess := oCert1:LoadFromFile("qa_data/recipient1.cer")
IF (nSuccess == 0)
    ? oCert1:LastErrorText
    oMime:destroy()
    oCert1:destroy()
    RETURN
ENDIF

nSuccess := oMime:AddEncryptCert(oCert1)
IF (nSuccess == 0)
    ? oMime:LastErrorText
    oMime:destroy()
    oCert1:destroy()
    RETURN
ENDIF

oCert2 := CreateObject("Chilkat.Cert")
nSuccess := oCert2:LoadFromFile("qa_data/recipient2.cer")
IF (nSuccess == 0)
    ? oCert2:LastErrorText
    oMime:destroy()
    oCert1:destroy()
    oCert2:destroy()
    RETURN
ENDIF

nSuccess := oMime:AddEncryptCert(oCert2)
IF (nSuccess == 0)
    ? oMime:LastErrorText
    oMime:destroy()
    oCert1:destroy()
    oCert2:destroy()
    RETURN
ENDIF

//  Encrypt for every added recipient at once.
nSuccess := oMime:EncryptN()
IF (nSuccess == 0)
    ? oMime:LastErrorText
    oMime:destroy()
    oCert1:destroy()
    oCert2:destroy()
    RETURN
ENDIF

nSuccess := oMime:SaveMime("qa_output/encrypted_multi.eml")
IF (nSuccess == 0)
    ? oMime:LastErrorText
    oMime:destroy()
    oCert1:destroy()
    oCert2:destroy()
    RETURN
ENDIF

? "Message encrypted for multiple recipients."

oMime:destroy()
oCert1:destroy()
oCert2:destroy()