Sample code for 30+ languages & platforms
SQL Server

Export a Public Key as DER into a BinData

Demonstrates the Chilkat PublicKey.GetDerBd method, which writes the public key as binary DER into a BinData. The first argument selects the representation (as for GetPem) and the second is the BinData that receives the bytes (its contents are replaced).

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: The in-memory binary export: the raw DER lands in a BinData ready to hash, transmit, or hand to another API without a temporary file. It is the BinData counterpart to the text exporters, and the first argument picks the same PKCS #1 versus SubjectPublicKeyInfo structure.

Chilkat SQL Server Downloads

SQL Server
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    DECLARE @iTmp0 int
    DECLARE @sTmp0 nvarchar(4000)
    DECLARE @success int
    SELECT @success = 0

    --  Load a public key to export.  LoadFromFile inspects the content, so it accepts DER, PEM, XML,
    --  JWK, and other supported representations.
    DECLARE @pubKey int
    EXEC @hr = sp_OACreate 'Chilkat.PublicKey', @pubKey OUT
    IF @hr <> 0
    BEGIN
        PRINT 'Failed to create ActiveX component'
        RETURN
    END

    EXEC sp_OAMethod @pubKey, 'LoadFromFile', @success OUT, 'qa_data/public.pem'
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @pubKey, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @pubKey
        RETURN
      END

    --  Write the public key as binary DER into a BinData.  The 1st argument selects the representation
    --  (as for GetPem) and the 2nd is the BinData that receives the bytes (its contents are replaced).
    DECLARE @preferPkcs1 int
    SELECT @preferPkcs1 = 0
    DECLARE @bd int
    EXEC @hr = sp_OACreate 'Chilkat.BinData', @bd OUT

    EXEC sp_OAMethod @pubKey, 'GetDerBd', @success OUT, @preferPkcs1, @bd
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @pubKey, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @pubKey
        EXEC @hr = sp_OADestroy @bd
        RETURN
      END

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

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

    EXEC @hr = sp_OADestroy @pubKey
    EXEC @hr = sp_OADestroy @bd


END
GO