SQL Server
SQL Server
Decrypt a JWE into a StringBuilder
See more JSON Web Encryption (JWE) Examples
Demonstrates Jwe.DecryptSb, which decrypts a recipient of a loaded JWE and writes the plaintext into a StringBuilder.
Background. The recipient index selects which recipient's key material to use. The key for that recipient must be provided before decrypting.
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 @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
-- Load the JWE compact serialization to be decrypted.
DECLARE @jweCompact nvarchar(4000)
SELECT @jweCompact = 'eyJhbGciOiJBMjU2S1ciLCJlbmMiOiJBMjU2R0NNIn0.<...>.<iv>.<ciphertext>.<tag>'
EXEC sp_OAMethod @jwe, 'LoadJwe', @success OUT, @jweCompact
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @jwe, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @jwe
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
RETURN
END
-- Decrypt recipient index 0, writing the plaintext into a StringBuilder.
DECLARE @sbContent int
EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sbContent OUT
EXEC sp_OAMethod @jwe, 'DecryptSb', @success OUT, 0, 'utf-8', @sbContent
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @jwe, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @jwe
EXEC @hr = sp_OADestroy @sbContent
RETURN
END
EXEC sp_OAMethod @sbContent, 'GetAsString', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @jwe
EXEC @hr = sp_OADestroy @sbContent
END
GO