Sample code for 30+ languages & platforms
SQL Server

Find a JWE Recipient by Header Value

See more JSON Web Encryption (JWE) Examples

Demonstrates Jwe.FindRecipient, which searches the per-recipient unprotected headers for a member with a given name and string value, and returns the matching recipient index.

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. This locates the recipient that a particular key belongs to (for example by kid) before decrypting. The method returns -1 when no match is found.

Chilkat SQL Server Downloads

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

    --  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 a multi-recipient JWE (JSON serialization) from a file.
    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
    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

    --  Search the per-recipient unprotected headers for a member named "kid" whose value equals the
    --  given string.  Returns the recipient index, or -1 if not found.
    DECLARE @bCaseSensitive int
    SELECT @bCaseSensitive = 1
    DECLARE @index int
    EXEC sp_OAMethod @jwe, 'FindRecipient', @index OUT, 'kid', 'recipient-key-1', @bCaseSensitive
    IF @index < 0
      BEGIN

        PRINT 'Recipient not found.'
        EXEC @hr = sp_OADestroy @jwe
        EXEC @hr = sp_OADestroy @sbJwe
        RETURN
      END

    PRINT 'Found recipient at index ' + @index

    EXEC @hr = sp_OADestroy @jwe
    EXEC @hr = sp_OADestroy @sbJwe


END
GO