Sample code for 30+ languages & platforms
SQL Server

Decrypt a JWE with a Private Key

See more JSON Web Encryption (JWE) Examples

Demonstrates Jwe.SetPrivateKey, which sets the private key used to decrypt a recipient of a loaded JWE.

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. The private key unwraps the content-encryption key that was wrapped with the corresponding public key during encryption.

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 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 recipient's private key.
    DECLARE @privKey int
    EXEC @hr = sp_OACreate 'Chilkat.PrivateKey', @privKey OUT

    EXEC sp_OAMethod @privKey, 'LoadPemFile', @success OUT, 'qa_data/recipient_privkey.pem'
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @privKey, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @jwe
        EXEC @hr = sp_OADestroy @privKey
        RETURN
      END

    --  Set the private key used to decrypt recipient 0.
    EXEC sp_OAMethod @jwe, 'SetPrivateKey', @success OUT, 0, @privKey
    IF @success = 0
      BEGIN
        EXEC sp_OAGetProperty @jwe, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @jwe
        EXEC @hr = sp_OADestroy @privKey
        RETURN
      END

    DECLARE @content nvarchar(4000)
    EXEC sp_OAMethod @jwe, 'Decrypt', @content OUT, 0, 'utf-8'
    EXEC sp_OAGetProperty @jwe, 'LastMethodSuccess', @iTmp0 OUT
    IF @iTmp0 = 0
      BEGIN
        EXEC sp_OAGetProperty @jwe, 'LastErrorText', @sTmp0 OUT
        PRINT @sTmp0
        EXEC @hr = sp_OADestroy @jwe
        EXEC @hr = sp_OADestroy @privKey
        RETURN
      END

    PRINT @content

    EXEC @hr = sp_OADestroy @jwe
    EXEC @hr = sp_OADestroy @privKey


END
GO