Sample code for 30+ languages & platforms
SQL Server

Decrypt a JWE into BinData

See more JSON Web Encryption (JWE) Examples

Demonstrates Jwe.DecryptBd, which decrypts a recipient of a loaded JWE and writes the plaintext bytes into a BinData.

Background. This is used when the decrypted content is binary. The recipient key must be provided before decrypting.

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 @iTmp0 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 bytes into a BinData.
    DECLARE @bd int
    EXEC @hr = sp_OACreate 'Chilkat.BinData', @bd OUT

    EXEC sp_OAMethod @jwe, 'DecryptBd', @success OUT, 0, @bd
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @jwe, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @jwe
        EXEC @hr = sp_OADestroy @bd
        RETURN
      END

    EXEC sp_OAGetProperty @bd, 'NumBytes', @iTmp0 OUT

    PRINT 'Decrypted ' + @iTmp0 + ' bytes.'

    EXEC @hr = sp_OADestroy @jwe
    EXEC @hr = sp_OADestroy @bd


END
GO