Sample code for 30+ languages & platforms
SQL Server

Export Selected PFX Contents as PEM

See more PFX/P12 Examples

Demonstrates Pfx.ToPemEx, which exports selected PFX contents as PEM-formatted text with control over which parts are included and how private keys are encrypted.

Background. Private keys are written in PKCS #8 form. Supported key-encryption algorithms include aes128, aes192, aes256, and 3des; leaving the algorithm empty produces unencrypted keys.

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.
    --  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

    --  Export selected PFX contents as PEM-formatted text.  The boolean arguments control what is
    --  included: extended attributes, and whether to omit private keys, certificates, or CA certificates.
    DECLARE @bExtendedAttrs int
    SELECT @bExtendedAttrs = 0
    DECLARE @bNoKeys int
    SELECT @bNoKeys = 0
    DECLARE @bNoCerts int
    SELECT @bNoCerts = 0
    DECLARE @bNoCaCerts int
    SELECT @bNoCaCerts = 0

    --  Encrypt the exported private keys.  Supported algorithms include aes128, aes192, aes256, and 3des;
    --  leave the algorithm empty for unencrypted keys.  The key password should come from a secure source.
    DECLARE @keyPassword nvarchar(4000)
    SELECT @keyPassword = 'myKeyPassword'
    DECLARE @pem nvarchar(4000)
    EXEC sp_OAMethod @pfx, 'ToPemEx', @pem OUT, @bExtendedAttrs, @bNoKeys, @bNoCerts, @bNoCaCerts, 'aes256', @keyPassword
    EXEC sp_OAGetProperty @pfx, 'LastMethodSuccess', @iTmp0 OUT
    IF @iTmp0 = 0
      BEGIN
        EXEC sp_OAGetProperty @pfx, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @pfx
        RETURN
      END

    PRINT @pem

    EXEC @hr = sp_OADestroy @pfx


END
GO