Sample code for 30+ languages & platforms
SQL Server

Export a Public Key DER as Encoded Text

Demonstrates the Chilkat PublicKey.GetEncoded method, which returns the DER representation encoded as text. The first argument selects the DER representation (as for GetPem) and the second names the binary encoding, such as base64 or hex.

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 returns the raw DER bytes as an encoded string, so the key can travel through a text-only medium without the BEGIN/END armor of PEM. Choosing base64 versus hex is simply a matter of what the consumer expects, and the first argument selects the same DER structures as GetPem.

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 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

    --  Export the DER as text.  The 1st argument selects the DER representation (as for GetPem) and
    --  the 2nd names the binary encoding, such as "base64" or "hex".
    DECLARE @preferPkcs1 int
    SELECT @preferPkcs1 = 0
    DECLARE @encoded nvarchar(4000)
    EXEC sp_OAMethod @pubKey, 'GetEncoded', @encoded OUT, @preferPkcs1, 'base64'
    EXEC sp_OAGetProperty @pubKey, 'LastMethodSuccess', @iTmp0 OUT
    IF @iTmp0 = 0
      BEGIN
        EXEC sp_OAGetProperty @pubKey, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @pubKey
        RETURN
      END

    PRINT @encoded

    EXEC @hr = sp_OADestroy @pubKey


END
GO