SQL Server
SQL Server
RSA Sign Using Private Key from .pfx/.p12 to Base64 Signature
See more RSA Examples
Demonstrates how to RSA sign something using a private key loaded from a .pfx/.p12. The RSA signature is returned in Base64 encoded format.Chilkat SQL Server Downloads
-- 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
-- Load the .pfx/.p12
DECLARE @pfx int
EXEC @hr = sp_OACreate 'Chilkat.Pfx', @pfx OUT
EXEC sp_OAMethod @pfx, 'LoadPfxFile', @success OUT, 'qa_data/pfx/myKey.p12', 'myPassword'
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @pfx, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @rsa
EXEC @hr = sp_OADestroy @pfx
RETURN
END
-- Get the default private key.
DECLARE @privKey int
EXEC @hr = sp_OACreate 'Chilkat.PrivateKey', @privKey OUT
EXEC sp_OAMethod @pfx, 'PrivateKeyAt', @success OUT, 0, @privKey
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @pfx, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @rsa
EXEC @hr = sp_OADestroy @pfx
EXEC @hr = sp_OADestroy @privKey
RETURN
END
-- Import the private key into the RSA component:
EXEC sp_OAMethod @rsa, 'UsePrivateKey', @success OUT, @privKey
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @rsa, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @rsa
EXEC @hr = sp_OADestroy @pfx
EXEC @hr = sp_OADestroy @privKey
RETURN
END
-- Get the signature in base64
EXEC sp_OASetProperty @rsa, 'EncodingMode', 'base64'
DECLARE @strData nvarchar(4000)
SELECT @strData = 'This is the string to be signed.'
-- Sign the string using the sha256 hash algorithm.
-- Other valid choices are "sha384", "sha512", "sha-1", "md2" and "md5".
DECLARE @base64Sig nvarchar(4000)
EXEC sp_OAMethod @rsa, 'SignStringENC', @base64Sig OUT, @strData, 'sha256'
PRINT @base64Sig
PRINT 'Success!'
EXEC @hr = sp_OADestroy @rsa
EXEC @hr = sp_OADestroy @pfx
EXEC @hr = sp_OADestroy @privKey
END
GO