SQL Server
SQL Server
Add a Private Key and Certificate Chain to a PFX
See more PFX/P12 Examples
Demonstrates Pfx.AddPrivateKey, which adds a private key together with its certificate chain to 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 chain must contain at least one certificate; the certificate at index 0 is treated as the leaf. The chain is built here with Cert.BuildCertChain.
Chilkat SQL Server Downloads
--
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.
-- Load the private key.
DECLARE @privKey int
EXEC @hr = sp_OACreate 'Chilkat.PrivateKey', @privKey OUT
EXEC sp_OAMethod @privKey, 'LoadPemFile', @success OUT, 'qa_data/private_key.pem'
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @privKey, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @pfx
EXEC @hr = sp_OADestroy @privKey
RETURN
END
-- Load the certificate and build its chain of authority. The chain must contain at least one
-- certificate; the certificate at index 0 is treated as the leaf.
DECLARE @cert int
EXEC @hr = sp_OACreate 'Chilkat.Cert', @cert OUT
EXEC sp_OAMethod @cert, 'LoadFromFile', @success OUT, 'qa_data/cert.pem'
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @cert, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @pfx
EXEC @hr = sp_OADestroy @privKey
EXEC @hr = sp_OADestroy @cert
RETURN
END
DECLARE @chain int
EXEC @hr = sp_OACreate 'Chilkat.CertChain', @chain OUT
EXEC sp_OAMethod @cert, 'BuildCertChain', @success OUT, @chain
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @cert, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @pfx
EXEC @hr = sp_OADestroy @privKey
EXEC @hr = sp_OADestroy @cert
EXEC @hr = sp_OADestroy @chain
RETURN
END
-- Add the private key and its certificate chain to the PFX.
EXEC sp_OAMethod @pfx, 'AddPrivateKey', @success OUT, @privKey, @chain
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @pfx, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @pfx
EXEC @hr = sp_OADestroy @privKey
EXEC @hr = sp_OADestroy @cert
EXEC @hr = sp_OADestroy @chain
RETURN
END
PRINT 'Private key and certificate chain added to the PFX.'
EXEC @hr = sp_OADestroy @pfx
EXEC @hr = sp_OADestroy @privKey
EXEC @hr = sp_OADestroy @cert
EXEC @hr = sp_OADestroy @chain
END
GO