Sample code for 30+ languages & platforms
SQL Server

Find a PFX Certificate by localKeyId

See more PFX/P12 Examples

Demonstrates Pfx.CertByLocalKeyId, which searches for a certificate whose certificate-bag localKeyId attribute matches a given value and copies it into a Cert object.

The file path is relative to the application's current working directory. An absolute path may also be used. Supply the path appropriate to your own environment.

Background. The encoding argument names the binary representation of the id, such as decimal, base64, or hex. The localKeyId links a certificate to its corresponding private key within the container.

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
    DECLARE @sTmp0 nvarchar(4000)
    DECLARE @success int
    SELECT @success = 0

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

    --  The file path is relative to the application's current working directory.  An absolute path
    --  may also be used.  Supply the path appropriate to your own environment.
    --  The PFX password should come from a secure source rather than being hard-coded.
    DECLARE @password nvarchar(4000)
    SELECT @password = 'myPfxPassword'
    EXEC sp_OAMethod @pfx, 'LoadPfxFile', @success OUT, 'qa_data/identity.pfx', @password
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @pfx, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @pfx
        RETURN
      END

    --  Find a certificate whose certificate-bag localKeyId attribute matches the given value.  The 2nd
    --  argument names the binary representation of the id, such as decimal, base64, or hex.
    DECLARE @cert int
    EXEC @hr = sp_OACreate 'Chilkat.Cert', @cert OUT

    EXEC sp_OAMethod @pfx, 'CertByLocalKeyId', @success OUT, '01', 'hex', @cert
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @pfx, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @pfx
        EXEC @hr = sp_OADestroy @cert
        RETURN
      END

    EXEC sp_OAGetProperty @cert, 'SubjectCN', @sTmp0 OUT
    PRINT 'Found certificate: ' + @sTmp0

    EXEC @hr = sp_OADestroy @pfx
    EXEC @hr = sp_OADestroy @cert


END
GO