Sample code for 30+ languages & platforms
SQL Server

Load Identities from PEM Text

See more PFX/P12 Examples

Demonstrates Pfx.LoadPem, which loads one or more certificate/private-key identities from PEM-formatted text and builds the contents of the Pfx 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 password decrypts any encrypted private keys in the PEM. This builds a PFX in memory from PEM material, which can then be serialized to PKCS#12.

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 @iTmp0 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.
    --  Load the PEM text (certificates and private keys) into a string.
    DECLARE @sbPem int
    EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sbPem OUT

    DECLARE @bLoaded int
    EXEC sp_OAMethod @sbPem, 'LoadFile', @bLoaded OUT, 'qa_data/identity.pem'
    IF @bLoaded <> 1
      BEGIN

        PRINT 'Failed to load the PEM file.'
        EXEC @hr = sp_OADestroy @pfx
        EXEC @hr = sp_OADestroy @sbPem
        RETURN
      END
    DECLARE @pemText nvarchar(4000)
    EXEC sp_OAMethod @sbPem, 'GetAsString', @pemText OUT
    EXEC sp_OAGetProperty @sbPem, 'LastMethodSuccess', @iTmp0 OUT
    IF @iTmp0 = 0
      BEGIN
        EXEC sp_OAGetProperty @sbPem, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @pfx
        EXEC @hr = sp_OADestroy @sbPem
        RETURN
      END

    --  The password decrypts any encrypted private keys in the PEM (use an empty string if none are
    --  encrypted).  A password should come from a secure source rather than being hard-coded.
    DECLARE @password nvarchar(4000)
    SELECT @password = 'myPemPassword'
    EXEC sp_OAMethod @pfx, 'LoadPem', @success OUT, @pemText, @password
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @pfx, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @pfx
        EXEC @hr = sp_OADestroy @sbPem
        RETURN
      END

    EXEC sp_OAGetProperty @pfx, 'NumPrivateKeys', @iTmp0 OUT

    PRINT 'Loaded ' + @iTmp0 + ' private key(s).'

    EXEC @hr = sp_OADestroy @pfx
    EXEC @hr = sp_OADestroy @sbPem


END
GO