Sample code for 30+ languages & platforms
SQL Server

Convert RSA Private Key to Public Key

See more RSA Examples

Demonstrates how to get a public RSA key from a private RSA key.

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
    -- Important: Do not use nvarchar(max).  See the warning about using nvarchar(max).
    DECLARE @sTmp0 nvarchar(4000)
    DECLARE @success int
    SELECT @success = 0

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

    -- Step 1: Load the private key from a source.
    -- (Chilkat can load private keys from all types of formats, and from in-memory bytes or encoded strings.
    -- see the online reference documentation for more options.)
    EXEC sp_OAMethod @privKey, 'LoadPemFile', @success OUT, 'qa_data/pem/VP_Private.pem'
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @privKey, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @privKey
        RETURN
      END

    -- Step 2: Get the public key object from the private key object.
    DECLARE @pubKey int
    EXEC @hr = sp_OACreate 'Chilkat.PublicKey', @pubKey OUT

    EXEC sp_OAMethod @privKey, 'ToPublicKey', @success OUT, @pubKey

    -- Step 3: Save the public key in a desired format. 
    -- (Chilkat can load or save public and private keys in many different formats.  See
    -- the online reference documentation for more options.)

    -- Saves to a PKCS8 PEM file.
    DECLARE @bPreferPkcs1 int
    SELECT @bPreferPkcs1 = 0
    EXEC sp_OAMethod @pubKey, 'SavePemFile', @success OUT, @bPreferPkcs1, 'qa_data/pem/VP_Public.pem'
    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 'Extracted and saved public key from private key.'

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


END
GO