Sample code for 30+ languages & platforms
SQL Server Requires Chilkat v11.0.0+

Decrypt an S/MIME email and verify its signature

See more Email Object Examples

Register the recipient’s PFX before opening signed-encrypted.eml. This workflow expects both encryption and a signature, so it checks both layers before reading the message. Cryptographic signature validity is one input to a signer-trust decision.

Chilkat SQL Server Downloads

SQL Server
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    DECLARE @iTmp0 int
    DECLARE @iTmp1 int
    DECLARE @sTmp0 nvarchar(4000)
    DECLARE @success int
    SELECT @success = 0

    --  Assumes Chilkat is unlocked. See Global Unlock Sample.

    DECLARE @email int
    EXEC @hr = sp_OACreate 'Chilkat.Email', @email OUT
    IF @hr <> 0
    BEGIN
        PRINT 'Failed to create ActiveX component'
        RETURN
    END

    EXEC sp_OAMethod @email, 'AddPfxSourceFile', @success OUT, 'recipient.pfx', 'RECIPIENT_PASSWORD'
    IF @success <> 1
      BEGIN
        EXEC sp_OAGetProperty @email, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @email
        RETURN
      END
    EXEC sp_OAMethod @email, 'LoadEml', @success OUT, 'signed-encrypted.eml'
    IF @success <> 1
      BEGIN
        EXEC sp_OAGetProperty @email, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @email
        RETURN
      END
    EXEC sp_OAGetProperty @email, 'ReceivedEncrypted', @iTmp0 OUT
    EXEC sp_OAGetProperty @email, 'Decrypted', @iTmp1 OUT
    IF (@iTmp0 <> 1) or (@iTmp1 <> 1)
      BEGIN

        PRINT 'Expected a successfully decrypted S/MIME envelope.'
        EXEC @hr = sp_OADestroy @email
        RETURN
      END
    EXEC sp_OAGetProperty @email, 'ReceivedSigned', @iTmp0 OUT
    EXEC sp_OAGetProperty @email, 'SignaturesValid', @iTmp1 OUT
    IF (@iTmp0 <> 1) or (@iTmp1 <> 1)
      BEGIN

        PRINT 'Expected a valid signature inside the envelope.'
        EXEC @hr = sp_OADestroy @email
        RETURN
      END
    --  This message has one signer. Examine its certificate after verification.
    DECLARE @signer int
    EXEC @hr = sp_OACreate 'Chilkat.Cert', @signer OUT

    EXEC sp_OAMethod @email, 'LastSignerCert', @success OUT, 0, @signer
    IF @success <> 1
      BEGIN
        EXEC sp_OAGetProperty @email, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @email
        EXEC @hr = sp_OADestroy @signer
        RETURN
      END

    EXEC sp_OAGetProperty @signer, 'SubjectDN', @sTmp0 OUT
    PRINT 'Signer certificate: ' + @sTmp0

    EXEC sp_OAGetProperty @email, 'Subject', @sTmp0 OUT
    PRINT 'Recovered subject: ' + @sTmp0

    EXEC sp_OAGetProperty @email, 'NumAttachments', @iTmp0 OUT
    PRINT 'Recovered attachments: ' + @iTmp0

    EXEC @hr = sp_OADestroy @email
    EXEC @hr = sp_OADestroy @signer


END
GO