Sample code for 30+ languages & platforms
SQL Server Requires Chilkat v11.0.0+

RSA Encrypt and OpenSSL Decrypt

See more OpenSSL Examples

Demonstrates how to use Chilkat to RSA encrypt, and then use OpenSSL to decrypt.

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 @success int
    SELECT @success = 0

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

    DECLARE @privKey int
    EXEC @hr = sp_OACreate 'Chilkat.PrivateKey', @privKey OUT

    EXEC sp_OAMethod @rsa, 'GenKey', @success OUT, 2048, @privKey
    EXEC sp_OAMethod @privKey, 'SavePkcs8PemFile', @success OUT, 'qa_output/privKey.pem'

    DECLARE @pubKey int
    EXEC @hr = sp_OACreate 'Chilkat.PublicKey', @pubKey OUT

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

    EXEC sp_OASetProperty @rsa, 'EncodingMode', 'base64'
    DECLARE @plainText nvarchar(4000)
    SELECT @plainText = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890'
    DECLARE @bUsePrivateKey int
    SELECT @bUsePrivateKey = 0
    EXEC sp_OAMethod @rsa, 'UsePublicKey', @success OUT, @pubKey
    DECLARE @encryptedStr nvarchar(4000)
    EXEC sp_OAMethod @rsa, 'EncryptStringENC', @encryptedStr OUT, @plainText, @bUsePrivateKey

    DECLARE @bd int
    EXEC @hr = sp_OACreate 'Chilkat.BinData', @bd OUT

    EXEC sp_OAMethod @bd, 'AppendEncoded', @success OUT, @encryptedStr, 'base64'
    EXEC sp_OAMethod @bd, 'WriteFile', @success OUT, 'qa_output/enc.dat'

    --  The OpenSSL command to decrypt is:
    --  openssl pkeyutl -in enc.dat -inkey privKey.pem -keyform PEM -pkeyopt rsa_padding_mode:pkcs1 -decrypt


    PRINT 'OK'

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


END
GO