SQL Server
SQL Server
Iterate Keys and Certs in PEM
See more PEM Examples
Demonstrates how to access each of the private keys and certs contained within a PEM.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
-- This example assumes the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.
DECLARE @pem int
EXEC @hr = sp_OACreate 'Chilkat.Pem', @pem OUT
IF @hr <> 0
BEGIN
PRINT 'Failed to create ActiveX component'
RETURN
END
-- Load the PEM from a file.
-- If the PEM is encrypted, provide a password. Otherwise pass an empty string for the password.
DECLARE @password nvarchar(4000)
SELECT @password = 'myPassword'
EXEC sp_OAMethod @pem, 'LoadPemFile', @success OUT, '../myPemFiles/myPem.pem', @password
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @pem, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @pem
RETURN
END
-- Note: If the app already has the PEM pre-loaded in a string variable, then load it
-- by calling LoadPem instead.
DECLARE @pemContent nvarchar(4000)
SELECT @pemContent = '... the PEM contents ...'
EXEC sp_OAMethod @pem, 'LoadPem', @success OUT, @pemContent, @password
-- Check for success as before..
-- Iterate over the private keys.
DECLARE @numPrivateKeys int
EXEC sp_OAGetProperty @pem, 'NumPrivateKeys', @numPrivateKeys OUT
DECLARE @i int
SELECT @i = 0
DECLARE @privKey int
EXEC @hr = sp_OACreate 'Chilkat.PrivateKey', @privKey OUT
WHILE @i < @numPrivateKeys
BEGIN
EXEC sp_OAMethod @pem, 'PrivateKeyAt', @success OUT, @i, @privKey
EXEC sp_OAGetProperty @privKey, 'BitLength', @iTmp0 OUT
PRINT 'Private Key ' + @i + ' is ' + @iTmp0 + ' in length'
SELECT @i = @i + 1
END
-- Iterate over the certificates.
DECLARE @cert int
EXEC @hr = sp_OACreate 'Chilkat.Cert', @cert OUT
DECLARE @numCerts int
EXEC sp_OAGetProperty @pem, 'NumCerts', @numCerts OUT
SELECT @i = 0
WHILE @i < @numCerts
BEGIN
EXEC sp_OAMethod @pem, 'CertAt', @success OUT, @i, @cert
EXEC sp_OAGetProperty @cert, 'SubjectDN', @sTmp0 OUT
PRINT 'Certificate ' + @i + ' : ' + @sTmp0
SELECT @i = @i + 1
END
EXEC @hr = sp_OADestroy @pem
EXEC @hr = sp_OADestroy @privKey
EXEC @hr = sp_OADestroy @cert
END
GO