Sample code for 30+ languages & platforms
SQL Server

Export a Private Key as DER into a BinData

See more Private Key Examples

Demonstrates the Chilkat PrivateKey.GetPkcsBd method, which exports the key as DER into a BinData. The first argument selects PKCS #1 (true) versus PKCS #8 (false), the second is the password (empty for unencrypted), and the third is the BinData that receives the bytes.

Note: The file paths are relative to the application's current working directory. Absolute paths may also be used. Supply the paths appropriate to your own environment.

Background: This is the in-memory binary export — the raw DER bytes land in a BinData ready to hash, encrypt, or hand to another API without a temporary file. One method covers several cases: the boolean picks the traditional (PKCS #1) versus modern (PKCS #8) structure, and a nonempty password produces an encrypted PKCS #8 export (with the cipher from Pkcs8EncryptAlg). Source any password securely.

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

    --  Load a private key to export.
    DECLARE @privKey int
    EXEC @hr = sp_OACreate 'Chilkat.PrivateKey', @privKey OUT
    IF @hr <> 0
    BEGIN
        PRINT 'Failed to create ActiveX component'
        RETURN
    END

    EXEC sp_OAMethod @privKey, 'LoadPemFile', @success OUT, 'qa_data/private.pem'
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @privKey, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @privKey
        RETURN
      END

    --  The key password is not hard-coded in a real application; obtain it from an interactive
    --  prompt, environment variable, or a secrets vault.
    DECLARE @password nvarchar(4000)
    SELECT @password = 'myKeyPassword'

    --  Export the key as DER into a BinData.  The 1st argument selects PKCS #1 (1) versus PKCS #8
    --  (0); the 2nd is the password (empty string for an unencrypted export); the 3rd is the
    --  BinData that receives the DER bytes.
    DECLARE @usePkcs1 int
    SELECT @usePkcs1 = 0
    DECLARE @bd int
    EXEC @hr = sp_OACreate 'Chilkat.BinData', @bd OUT

    EXEC sp_OAMethod @privKey, 'GetPkcsBd', @success OUT, @usePkcs1, @password, @bd
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @privKey, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @privKey
        EXEC @hr = sp_OADestroy @bd
        RETURN
      END

    EXEC sp_OAGetProperty @bd, 'NumBytes', @iTmp0 OUT

    PRINT 'Exported ' + @iTmp0 + ' DER bytes.'

    EXEC @hr = sp_OADestroy @privKey
    EXEC @hr = sp_OADestroy @bd


END
GO