SQL Server
SQL Server
Load PKCS12 / PFX and Access Contents
See more PFX/P12 Examples
Loads a PKCS12 / PFX file and iterates over the contents which include private keys and certificates.Chilkat SQL Server Downloads
-- 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
-- Important: Do not use nvarchar(max). See the warning about using nvarchar(max).
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
-- Load the PKCS12 from a file
EXEC sp_OAMethod @pfx, 'LoadPfxFile', @success OUT, '/someDir/my.p12', 'pfxFilePassword'
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @pfx, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @pfx
RETURN
END
DECLARE @numPrivateKeys int
EXEC sp_OAGetProperty @pfx, 'NumPrivateKeys', @numPrivateKeys OUT
DECLARE @privKey int
EXEC @hr = sp_OACreate 'Chilkat.PrivateKey', @privKey OUT
PRINT 'Private Keys:'
DECLARE @i int
SELECT @i = 0
WHILE @i < @numPrivateKeys
BEGIN
EXEC sp_OAMethod @pfx, 'PrivateKeyAt', @success OUT, @i, @privKey
-- Do something with the private key ...
SELECT @i = @i + 1
END
DECLARE @cert int
EXEC @hr = sp_OACreate 'Chilkat.Cert', @cert OUT
DECLARE @numCerts int
EXEC sp_OAGetProperty @pfx, 'NumCerts', @numCerts OUT
PRINT 'Certs:'
SELECT @i = 0
WHILE @i < @numCerts
BEGIN
EXEC sp_OAMethod @pfx, 'CertAt', @success OUT, @i, @cert
EXEC sp_OAGetProperty @cert, 'SubjectDN', @sTmp0 OUT
PRINT @sTmp0
-- If the certificate has a private key (one of the private keys within the PFX)
-- then it can also be obtained via the certificate object:
EXEC sp_OAMethod @cert, 'HasPrivateKey', @iTmp0 OUT
IF @iTmp0 = 1
BEGIN
PRINT 'Has private key!'
EXEC sp_OAMethod @cert, 'GetPrivateKey', @success OUT, @privKey
-- ...
END
SELECT @i = @i + 1
END
EXEC @hr = sp_OADestroy @pfx
EXEC @hr = sp_OADestroy @privKey
EXEC @hr = sp_OADestroy @cert
END
GO