Sample code for 30+ languages & platforms
SQL Server

Generate RSA Key and Sign a String

See more RSA Examples

Demonstrates how to generate a new RSA public/private key pair and use it to generate a signature for a string. The (binary) digital signature is returned as a hexidecimalized string.

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

    -- This example assumes the Chilkat API to have been previously unlocked.
    -- See Global Unlock Sample for sample code.

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

    -- Generate a 2048-bit RSA key.
    DECLARE @privKey int
    EXEC @hr = sp_OACreate 'Chilkat.PrivateKey', @privKey OUT

    EXEC sp_OAMethod @rsa, 'GenKey', @success OUT, 2048, @privKey

    EXEC sp_OAMethod @rsa, 'UsePrivateKey', @success OUT, @privKey

    -- Return the signature in hex.
    EXEC sp_OASetProperty @rsa, 'EncodingMode', 'hex'

    DECLARE @strData nvarchar(4000)
    SELECT @strData = 'This is the string to be signed.'

    -- Sign the SHA256 hash of the string.
    DECLARE @hexSig nvarchar(4000)
    EXEC sp_OAMethod @rsa, 'SignStringENC', @hexSig OUT, @strData, 'sha256'


    PRINT @hexSig

    -- Now verify the signature:
    DECLARE @pubKey int
    EXEC @hr = sp_OACreate 'Chilkat.PublicKey', @pubKey OUT

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

    EXEC sp_OAMethod @rsa, 'VerifyStringENC', @success OUT, @strData, 'sha256', @hexSig
    IF @success = 1
      BEGIN

        PRINT 'Signature verified!'
      END
    ELSE
      BEGIN
        EXEC sp_OAGetProperty @rsa, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
      END

    -- Try it with an invalid signature:
    EXEC sp_OAMethod @rsa, 'VerifyStringENC', @success OUT, @strData, 'sha256', 'not a valid sig'
    IF @success = 1
      BEGIN

        PRINT 'Signature verified!'
      END
    ELSE
      BEGIN

        PRINT 'Signature validation failed!'
      END

    -- Try it with invalid data:
    EXEC sp_OAMethod @rsa, 'VerifyStringENC', @success OUT, 'Not the original data', 'sha256', @hexSig
    IF @success = 1
      BEGIN

        PRINT 'Signature verified!'
      END
    ELSE
      BEGIN

        PRINT 'Signature validation failed!'
      END

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


END
GO