Sample code for 30+ languages & platforms
DataFlex

Encrypt MIME for a Recipient Certificate

See more MIME Examples

Demonstrates encrypting the current MIME entity for a single recipient using the Mime.Encrypt method. The entity is replaced with CMS/PKCS #7 encrypted S/MIME that only the holder of the recipient's private key can read.

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. S/MIME encryption uses the recipient's public certificate to protect a message so that only the matching private key can recover it. The recipient certificate must be RSA-based. Only the recipient's public key is needed to encrypt—the private key is required to decrypt.

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoMime
    Variant vCert
    Handle hoCert
    String sTemp1

    Move False To iSuccess

    Get Create (RefClass(cComChilkatMime)) To hoMime
    If (Not(IsComObjectCreated(hoMime))) Begin
        Send CreateComObject of hoMime
    End
    Get ComSetBodyFromPlainText Of hoMime "This message will be encrypted." To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoMime To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    //  Load the recipient's certificate (public key only is sufficient for encrypting).
    Get Create (RefClass(cComChilkatCert)) To hoCert
    If (Not(IsComObjectCreated(hoCert))) Begin
        Send CreateComObject of hoCert
    End
    Get ComLoadFromFile Of hoCert "qa_data/recipient.cer" To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoCert To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    //  Encrypt for the recipient.  The entity is replaced with CMS/PKCS #7 encrypted S/MIME that only
    //  the holder of the recipient's private key can decrypt.  The certificate must be RSA-based.
    Get pvComObject of hoCert to vCert
    Get ComEncrypt Of hoMime vCert To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoMime To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Get ComSaveMime Of hoMime "qa_output/encrypted.eml" To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoMime To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Showln "Message encrypted."


End_Procedure