Sample code for 30+ languages & platforms
Lianja

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 Lianja Downloads

Lianja
llSuccess = .F.

loMime = createobject("CkMime")
llSuccess = loMime.SetBodyFromPlainText("This message will be encrypted.")
if (llSuccess = .F.) then
    ? loMime.LastErrorText
    release loMime
    return
endif

//  Add a certificate for each intended recipient.  Every recipient receives an independently
//  wrapped copy of the message key.
loCert1 = createobject("CkCert")
llSuccess = loCert1.LoadFromFile("qa_data/recipient1.cer")
if (llSuccess = .F.) then
    ? loCert1.LastErrorText
    release loMime
    release loCert1
    return
endif

llSuccess = loMime.AddEncryptCert(loCert1)
if (llSuccess = .F.) then
    ? loMime.LastErrorText
    release loMime
    release loCert1
    return
endif

loCert2 = createobject("CkCert")
llSuccess = loCert2.LoadFromFile("qa_data/recipient2.cer")
if (llSuccess = .F.) then
    ? loCert2.LastErrorText
    release loMime
    release loCert1
    release loCert2
    return
endif

llSuccess = loMime.AddEncryptCert(loCert2)
if (llSuccess = .F.) then
    ? loMime.LastErrorText
    release loMime
    release loCert1
    release loCert2
    return
endif

//  Encrypt for every added recipient at once.
llSuccess = loMime.EncryptN()
if (llSuccess = .F.) then
    ? loMime.LastErrorText
    release loMime
    release loCert1
    release loCert2
    return
endif

llSuccess = loMime.SaveMime("qa_output/encrypted_multi.eml")
if (llSuccess = .F.) then
    ? loMime.LastErrorText
    release loMime
    release loCert1
    release loCert2
    return
endif

? "Message encrypted for multiple recipients."


release loMime
release loCert1
release loCert2