Sample code for 30+ languages & platforms
SQL Server

Example: Mime.GetDecryptCertInfo method

Demonstrates the GetDecryptCertInfo method.

Chilkat SQL Server Downloads

SQL Server
-- Important: See this note about string length limitations for strings returned by sp_OAMethod calls.
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    -- Important: Do not use nvarchar(max).  See the warning about using nvarchar(max).
    DECLARE @sTmp0 nvarchar(4000)
    DECLARE @success int
    SELECT @success = 0

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

    -- Load MIME that is has Content-Type like this:
    -- Content-Type: application/pkcs7-mime; smime-type="enveloped-data"; name="smime.p7m"; smime-type="enveloped-data"
    EXEC sp_OAMethod @mime, 'LoadMimeFile', @success OUT, 'qa_data/mime/enveloped_data.eml'
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @mime, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @mime
        RETURN
      END

    -- Get information about the certificate that would be needed to decrypt.
    -- An enveloped-data can potentially be decrypted by multiple certificates if it was encrypted in a way that allows it,
    -- but in most cases, only a single certificate with associated private key (that of the message recipient) is possible.
    DECLARE @json int
    EXEC @hr = sp_OACreate 'Chilkat.JsonObject', @json OUT

    EXEC sp_OAMethod @mime, 'GetDecryptCertInfo', @success OUT, @json
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @mime, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @mime
        EXEC @hr = sp_OADestroy @json
        RETURN
      END

    EXEC sp_OASetProperty @json, 'EmitCompact', 0
    EXEC sp_OAMethod @json, 'Emit', @sTmp0 OUT
    PRINT @sTmp0

    -- Sample output:

    -- {
    --   "recipientInfo": [
    --     {
    --       "serial": "****",
    --       "issuerCN": "****"
    --     }
    --   ]
    -- }

    -- Get each certificate's information like this:
    DECLARE @serial nvarchar(4000)

    DECLARE @issuerCN nvarchar(4000)

    DECLARE @i int
    SELECT @i = 0
    DECLARE @count int
    EXEC sp_OAMethod @json, 'SizeOfArray', @count OUT, 'recipientInfo'
    WHILE @i < @count
      BEGIN
        EXEC sp_OASetProperty @json, 'I', @i
        EXEC sp_OAMethod @json, 'StringOf', @serial OUT, 'recipientInfo[i].serial'
        EXEC sp_OAMethod @json, 'StringOf', @issuerCN OUT, 'recipientInfo[i].issuerCN'
        SELECT @i = @i + 1
      END

    EXEC @hr = sp_OADestroy @mime
    EXEC @hr = sp_OADestroy @json


END
GO