SQL Server
SQL Server
Load a JWE from a StringBuilder
See more JSON Web Encryption (JWE) Examples
Demonstrates Jwe.LoadJweSb, which loads a JWE from a StringBuilder (here read from a file) so it can be decrypted.
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. JWE (JSON Web Encryption) protects content with a content-encryption algorithm (the header
enc value) while the content-encryption key is managed by the key-management algorithm (the header alg value). This example uses AES key wrapping with a symmetric wrapping key.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
-- 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 JWE text from a file into a StringBuilder.
DECLARE @sbJwe int
EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sbJwe OUT
DECLARE @bLoaded int
EXEC sp_OAMethod @sbJwe, 'LoadFile', @bLoaded OUT, 'qa_data/message.jwe', 'utf-8'
IF @bLoaded <> 1
BEGIN
PRINT 'Failed to load the JWE file.'
EXEC @hr = sp_OADestroy @jwe
EXEC @hr = sp_OADestroy @sbJwe
RETURN
END
-- Load the JWE from the StringBuilder.
EXEC sp_OAMethod @jwe, 'LoadJweSb', @success OUT, @sbJwe
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @jwe, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @jwe
EXEC @hr = sp_OADestroy @sbJwe
RETURN
END
-- The 256-bit key-wrapping key (base64) for recipient index 0. In production, obtain the key
-- from a secure source rather than hard-coding it.
DECLARE @base64Key nvarchar(4000)
SELECT @base64Key = 'YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU='
EXEC sp_OAMethod @jwe, 'SetWrappingKey', @success OUT, 0, @base64Key, 'base64'
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @jwe, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @jwe
EXEC @hr = sp_OADestroy @sbJwe
RETURN
END
DECLARE @content nvarchar(4000)
EXEC sp_OAMethod @jwe, 'Decrypt', @content OUT, 0, '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 @sbJwe
RETURN
END
PRINT @content
EXEC @hr = sp_OADestroy @jwe
EXEC @hr = sp_OADestroy @sbJwe
END
GO