SQL Server
SQL Server
Create a JWS into a StringBuilder
See more JSON Web Signatures (JWS) Examples
Demonstrates Jws.CreateJwsSb, which creates a JWS and writes it into a StringBuilder.
Background. JWS (JSON Web Signature) integrity-protects a payload with a signature or MAC. The header
alg names the algorithm; this example uses HMAC-SHA256 (HS256) with a symmetric MAC 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 @sTmp0 nvarchar(4000)
DECLARE @success int
SELECT @success = 0
DECLARE @jws int
EXEC @hr = sp_OACreate 'Chilkat.Jws', @jws OUT
IF @hr <> 0
BEGIN
PRINT 'Failed to create ActiveX component'
RETURN
END
-- Set the protected header for signer 0, specifying the signature algorithm (alg).
DECLARE @header int
EXEC @hr = sp_OACreate 'Chilkat.JsonObject', @header OUT
EXEC sp_OAMethod @header, 'UpdateString', @success OUT, 'alg', 'HS256'
EXEC sp_OAMethod @jws, 'SetProtectedHeader', @success OUT, 0, @header
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @jws, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @jws
EXEC @hr = sp_OADestroy @header
RETURN
END
-- Set the payload to be signed.
DECLARE @bIncludeBom int
SELECT @bIncludeBom = 0
EXEC sp_OAMethod @jws, 'SetPayload', @success OUT, 'This is the content to sign.', 'utf-8', @bIncludeBom
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @jws, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @jws
EXEC @hr = sp_OADestroy @header
RETURN
END
-- Provide the HMAC key (base64) for signer 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 @jws, 'SetMacKey', @success OUT, 0, @base64Key, 'base64'
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @jws, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @jws
EXEC @hr = sp_OADestroy @header
RETURN
END
-- Create the JWS and write it into a StringBuilder.
DECLARE @sbJws int
EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sbJws OUT
EXEC sp_OAMethod @jws, 'CreateJwsSb', @success OUT, @sbJws
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @jws, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @jws
EXEC @hr = sp_OADestroy @header
EXEC @hr = sp_OADestroy @sbJws
RETURN
END
EXEC sp_OAMethod @sbJws, 'GetAsString', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @jws
EXEC @hr = sp_OADestroy @header
EXEC @hr = sp_OADestroy @sbJws
END
GO