Sample code for 30+ languages & platforms
DataFlex

Decrypt S/MIME with an Explicit Certificate and Private Key

See more MIME Examples

Loads a CMS/PKCS #7 encrypted S/MIME message and decrypts it back to the original MIME content.

Decrypt2 accepts the certificate and its private key directly as arguments.

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 the certificate and private key are already loaded as separate objects, Decrypt2 uses them directly rather than searching an internal collection of credential sources.

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoMime
    Variant vCert
    Handle hoCert
    Variant vPrivKey
    Handle hoPrivKey
    String sBody
    String sTemp1
    Boolean bTemp1

    Move False To iSuccess

    Get Create (RefClass(cComChilkatMime)) To hoMime
    If (Not(IsComObjectCreated(hoMime))) Begin
        Send CreateComObject of hoMime
    End
    Get ComLoadMimeFile Of hoMime "qa_data/encrypted.eml" To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoMime To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    //  Decrypt using an explicitly supplied certificate and private key.  The 1st argument is the
    //  certificate and the 2nd is its private key.
    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

    Get Create (RefClass(cComChilkatPrivateKey)) To hoPrivKey
    If (Not(IsComObjectCreated(hoPrivKey))) Begin
        Send CreateComObject of hoPrivKey
    End
    Get ComLoadPemFile Of hoPrivKey "qa_data/recipient_privkey.pem" To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoPrivKey To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Get pvComObject of hoCert to vCert
    Get pvComObject of hoPrivKey to vPrivKey
    Get ComDecrypt2 Of hoMime vCert vPrivKey To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoMime To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Get ComGetBodyDecoded Of hoMime To sBody
    Get ComLastMethodSuccess Of hoMime To bTemp1
    If (bTemp1 = False) Begin
        Get ComLastErrorText Of hoMime To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Showln sBody


End_Procedure