Sample code for 30+ languages & platforms
SQL Server

Load PEM and List Certificates

Demonstrates how to load a PEM containing certificates and accesses each individual certificate.

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

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

    SELECT @success = 0

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

    -- Load the .p7b from a file.
    EXEC sp_OAMethod @pem, 'LoadPemFile', @success OUT, '/Users/chilkat/testData/p7b/cacert_mozilla.pem'
    IF @success <> 1
      BEGIN
        EXEC sp_OAGetProperty @pem, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @pem
        RETURN
      END

    DECLARE @i int

    DECLARE @numCerts int
    EXEC sp_OAGetProperty @pem, 'NumCerts', @numCerts OUT
    IF @numCerts = 0
      BEGIN

        PRINT ('Error: Expected the PEM to contain certificates.')
        EXEC @hr = sp_OADestroy @pem
        RETURN
      END

    -- Access each certificate and show the Subject CN (Common Name)
    SELECT @i = 1
    WHILE @i <= @numCerts
      BEGIN
        DECLARE @cert int
        EXEC sp_OAMethod @pem, 'GetCert', @cert OUT, @i - 1

        EXEC sp_OAGetProperty @cert, 'SubjectCN', @sTmp0 OUT
        PRINT @i + ': ' + @sTmp0
        EXEC @hr = sp_OADestroy @cert

        SELECT @i = @i + 1
      END

    EXEC @hr = sp_OADestroy @pem


END
GO