Sample code for 30+ languages & platforms
SQL Server

Get the Public Key from a Private Key

See more Private Key Examples

Demonstrates the Chilkat PrivateKey.ToPublicKey method, which extracts the public portion of the loaded private key into an independent PublicKey object. The only argument is the PublicKey that receives the copy.

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: A key pair's public half is derived from the private half, and this is how you obtain it — the public key you distribute for others to verify signatures or encrypt to you, while the private key stays secret. The resulting PublicKey is an independent copy, so exporting or sharing it never risks exposing the private material. From there, export it as PEM, JWK, or XML as needed.

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

    --  Extract the public portion of the private key into an independent PublicKey object.  The
    --  PublicKey is a separate copy, unaffected by later changes to the PrivateKey.
    DECLARE @pubKey int
    EXEC @hr = sp_OACreate 'Chilkat.PublicKey', @pubKey OUT

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

    --  The PublicKey can now be exported or shared -- for example as PEM.  The argument prefers the
    --  traditional PKCS #1 PEM when a traditional representation exists.
    DECLARE @preferPkcs1 int
    SELECT @preferPkcs1 = 1
    DECLARE @pubPem nvarchar(4000)
    EXEC sp_OAMethod @pubKey, 'GetPem', @pubPem OUT, @preferPkcs1
    EXEC sp_OAGetProperty @pubKey, 'LastMethodSuccess', @iTmp0 OUT
    IF @iTmp0 = 0
      BEGIN
        EXEC sp_OAGetProperty @pubKey, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @privKey
        EXEC @hr = sp_OADestroy @pubKey
        RETURN
      END

    PRINT @pubPem

    EXEC @hr = sp_OADestroy @privKey
    EXEC @hr = sp_OADestroy @pubKey


END
GO