Sample code for 30+ languages & platforms
SQL Server

Load and Validate a JWS from a StringBuilder

See more JSON Web Signatures (JWS) Examples

Demonstrates Jws.LoadJwsSb, which loads a JWS from a StringBuilder (here read from a file). The example then supplies the MAC key and validates the signature.

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. Validate returns 1 when the signature or MAC is cryptographically valid, 0 when it is not, or a negative value on error.

Chilkat SQL Server Downloads

SQL Server
-- 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

    --  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 JWS text from a file into a StringBuilder.
    DECLARE @sbJws int
    EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sbJws OUT

    DECLARE @bLoaded int
    EXEC sp_OAMethod @sbJws, 'LoadFile', @bLoaded OUT, 'qa_data/message.jws', 'utf-8'
    IF @bLoaded <> 1
      BEGIN

        PRINT 'Failed to load the JWS file.'
        EXEC @hr = sp_OADestroy @jws
        EXEC @hr = sp_OADestroy @sbJws
        RETURN
      END

    --  Load the JWS from the StringBuilder.
    EXEC sp_OAMethod @jws, 'LoadJwsSb', @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 @sbJws
        RETURN
      END

    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 @sbJws
        RETURN
      END

    DECLARE @v int
    EXEC sp_OAMethod @jws, 'Validate', @v OUT, 0
    IF @v < 0
      BEGIN
        EXEC sp_OAGetProperty @jws, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @jws
        EXEC @hr = sp_OADestroy @sbJws
        RETURN
      END
    IF @v <> 1
      BEGIN

        PRINT 'The signature is not valid.'
        EXEC @hr = sp_OADestroy @jws
        EXEC @hr = sp_OADestroy @sbJws
        RETURN
      END

    PRINT 'The signature is valid.'

    EXEC @hr = sp_OADestroy @jws
    EXEC @hr = sp_OADestroy @sbJws


END
GO