SQL Server
SQL Server
Generate an RSA Key and Get as Base64 DER
See more RSA Examples
Demonstrates how to generate a 2048-bit RSA key and return the public and private parts as unencrypted Base64 encoded DER.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
-- Generate a 2048-bit key.
DECLARE @privKey int
EXEC @hr = sp_OACreate 'Chilkat.PrivateKey', @privKey OUT
EXEC sp_OAMethod @rsa, 'GenKey', @success OUT, 2048, @privKey
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @rsa, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @rsa
EXEC @hr = sp_OADestroy @privKey
RETURN
END
-- Get the public part of the key.
DECLARE @pubKey int
EXEC @hr = sp_OACreate 'Chilkat.PublicKey', @pubKey OUT
EXEC sp_OAMethod @privKey, 'ToPublicKey', @success OUT, @pubKey
-- There are two possible formats for representing the RSA public key
-- in ASN.1 (DER). The possible formats are PKCS1 and PKCS8.
-- We can get either by setting bChoosePkcs1 to 1 or 0.
DECLARE @bChoosePkcs1 int
SELECT @bChoosePkcs1 = 1
DECLARE @pubKeyBase64Der nvarchar(4000)
EXEC sp_OAMethod @pubKey, 'GetEncoded', @pubKeyBase64Der OUT, @bChoosePkcs1, 'base64'
PRINT 'Public Key Base64 DER:'
PRINT @pubKeyBase64Der
-- Get the private key as Base64 DER:
-- We can get PKCS1 or PKCS8, but with different methods:
DECLARE @privKeyPkcs1 nvarchar(4000)
EXEC sp_OAMethod @privKey, 'GetPkcs1ENC', @privKeyPkcs1 OUT, 'base64'
PRINT 'Private Key PKCS1 Base64 DER:'
PRINT @privKeyPkcs1
DECLARE @privKeyPkcs8 nvarchar(4000)
EXEC sp_OAMethod @privKey, 'GetPkcs8ENC', @privKeyPkcs8 OUT, 'base64'
PRINT 'Private Key PKCS8 Base64 DER:'
PRINT @privKeyPkcs8
EXEC @hr = sp_OADestroy @rsa
EXEC @hr = sp_OADestroy @privKey
EXEC @hr = sp_OADestroy @pubKey
END
GO