SQL Server
SQL Server
Set JWE Additional Authenticated Data
See more JSON Web Encryption (JWE) Examples
Demonstrates Jwe.SetAad, which sets external Additional Authenticated Data (AAD) for a JWE being encrypted, encoding the supplied text with the given charset.
Background. AAD is integrity-protected but not encrypted, binding external context to the ciphertext. The same AAD must be supplied again when 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
-- Protected header: AES key-wrap 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', 'A256KW'
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 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 @header
RETURN
END
-- Set external Additional Authenticated Data (AAD). The AAD is integrity-protected but not
-- encrypted, and must be supplied again when decrypting.
EXEC sp_OAMethod @jwe, 'SetAad', @success OUT, 'context-info-v1', 'utf-8'
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
DECLARE @sbContent int
EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sbContent OUT
EXEC sp_OAMethod @sbContent, 'Append', @success OUT, 'This is the secret content.'
DECLARE @sbJwe int
EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sbJwe OUT
EXEC sp_OAMethod @jwe, 'EncryptSb', @success OUT, @sbContent, 'utf-8', @sbJwe
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 @sbContent
EXEC @hr = sp_OADestroy @sbJwe
RETURN
END
EXEC sp_OAMethod @sbJwe, 'GetAsString', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @jwe
EXEC @hr = sp_OADestroy @header
EXEC @hr = sp_OADestroy @sbContent
EXEC @hr = sp_OADestroy @sbJwe
END
GO