SQL Server
SQL Server
Encrypt a JWE with a Recipient Public Key
See more JSON Web Encryption (JWE) Examples
Demonstrates Jwe.SetPublicKey, which sets the public key used to encrypt for a recipient. The example uses RSA-OAEP-256 key management with AES-256-GCM content encryption.
The file path is relative to the application's current working directory. An absolute path may also be used. Supply the path appropriate to your own environment.
Background. In public-key JWE, the content-encryption key is wrapped for the recipient using their public key, so only the holder of the matching private key can decrypt.
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
DECLARE @iTmp0 int
DECLARE @sTmp0 nvarchar(4000)
DECLARE @success int
SELECT @success = 0
DECLARE @jwe int
EXEC @hr = sp_OACreate 'Chilkat.Jwe', @jwe OUT
IF @hr <> 0
BEGIN
PRINT 'Failed to create ActiveX component'
RETURN
END
-- Protected header: RSA-OAEP-256 key management with AES-256-GCM content encryption.
DECLARE @header int
EXEC @hr = sp_OACreate 'Chilkat.JsonObject', @header OUT
EXEC sp_OAMethod @header, 'UpdateString', @success OUT, 'alg', 'RSA-OAEP-256'
EXEC sp_OAMethod @header, 'UpdateString', @success OUT, 'enc', 'A256GCM'
EXEC sp_OAMethod @jwe, 'SetProtectedHeader', @success OUT, @header
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @jwe, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @jwe
EXEC @hr = sp_OADestroy @header
RETURN
END
-- The file path is relative to the application's current working directory. An absolute path
-- may also be used. Supply the path appropriate to your own environment.
-- Load the recipient's public key.
DECLARE @pubKey int
EXEC @hr = sp_OACreate 'Chilkat.PublicKey', @pubKey OUT
EXEC sp_OAMethod @pubKey, 'LoadFromFile', @success OUT, 'qa_data/recipient_pubkey.pem'
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @pubKey, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @jwe
EXEC @hr = sp_OADestroy @header
EXEC @hr = sp_OADestroy @pubKey
RETURN
END
-- Set the public key used to encrypt for recipient 0.
EXEC sp_OAMethod @jwe, 'SetPublicKey', @success OUT, 0, @pubKey
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @jwe, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @jwe
EXEC @hr = sp_OADestroy @header
EXEC @hr = sp_OADestroy @pubKey
RETURN
END
DECLARE @jweCompact nvarchar(4000)
EXEC sp_OAMethod @jwe, 'Encrypt', @jweCompact OUT, 'This is the secret content.', 'utf-8'
EXEC sp_OAGetProperty @jwe, 'LastMethodSuccess', @iTmp0 OUT
IF @iTmp0 = 0
BEGIN
EXEC sp_OAGetProperty @jwe, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @jwe
EXEC @hr = sp_OADestroy @header
EXEC @hr = sp_OADestroy @pubKey
RETURN
END
PRINT @jweCompact
EXEC @hr = sp_OADestroy @jwe
EXEC @hr = sp_OADestroy @header
EXEC @hr = sp_OADestroy @pubKey
END
GO