Sample code for 30+ languages & platforms
DataFlex Requires Chilkat v11.8.0+

Decrypt a .p7m File (using a Certificate and Private Key from a PEM File)

See more Encryption Examples

_LANGUAGE_ sample code showing how to decrypt a .p7m using a certificate w/ private key from a PEM file.

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoCrypt
    String sPemPath
    String sPemPassword
    Variant vPem
    Handle hoPem
    String sInPath
    String sOutPath
    String sTemp1

    Move False To iSuccess

    //  This example requires the Chilkat API to have been previously unlocked.
    //  See Global Unlock Sample for sample code.

    Get Create (RefClass(cComChilkatCrypt2)) To hoCrypt
    If (Not(IsComObjectCreated(hoCrypt))) Begin
        Send CreateComObject of hoCrypt
    End

    //  Use a digital certificate and private key from a PEM file.
    //  The 2nd argument of LoadPemFile is the password of the private key.
    //  (Pass an empty string if the private key is not encrypted.)
    Move "myCertAndKey.pem" To sPemPath
    Move "test123" To sPemPassword

    Get Create (RefClass(cComChilkatPem)) To hoPem
    If (Not(IsComObjectCreated(hoPem))) Begin
        Send CreateComObject of hoPem
    End
    Get ComLoadPemFile Of hoPem sPemPath sPemPassword To iSuccess
    If (iSuccess <> True) Begin
        Get ComLastErrorText Of hoPem To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    //  Give the certificate and private key to the Crypt2 object.
    Get pvComObject of hoPem to vPem
    Get ComAddPemSource Of hoCrypt vPem To iSuccess
    If (iSuccess <> True) Begin
        Get ComLastErrorText Of hoCrypt To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    //  Set the  outPath to whatever is appropriate.
    //  If you are decrypting a PDF, your output might be "out.pdf"...
    Move "smime.p7m" To sInPath
    Move "original.txt" To sOutPath

    //  Indicate that we're doing public key decryption (i.e. PKCS7)
    Set ComCryptAlgorithm Of hoCrypt To "pki"

    Get ComCkDecryptFile Of hoCrypt sInPath sOutPath To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoCrypt To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Showln "Success."


End_Procedure