SQL Server
SQL Server
Encrypt a JWE with a Password (PBES2)
See more JSON Web Encryption (JWE) Examples
Demonstrates Jwe.SetPassword, which sets the PBES2 password for a recipient. The example uses PBES2-HS256+A128KW key management with AES-128-GCM content encryption.
Background. PBES2 derives a key-wrapping key from a password using a salt and iteration count, allowing password-based JWE encryption. The password should come from a secure source.
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 @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
-- Protected header: PBES2 password-based key management with AES-128-GCM content encryption.
DECLARE @header int
EXEC @hr = sp_OACreate 'Chilkat.JsonObject', @header OUT
EXEC sp_OAMethod @header, 'UpdateString', @success OUT, 'alg', 'PBES2-HS256+A128KW'
EXEC sp_OAMethod @header, 'UpdateString', @success OUT, 'enc', 'A128GCM'
EXEC sp_OAMethod @jwe, 'SetProtectedHeader', @success OUT, @header
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @jwe, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @jwe
EXEC @hr = sp_OADestroy @header
RETURN
END
-- Set the PBES2 password for recipient 0. The password should come from a secure source rather than
-- being hard-coded.
DECLARE @password nvarchar(4000)
SELECT @password = 'myPassword'
EXEC sp_OAMethod @jwe, 'SetPassword', @success OUT, 0, @password
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @jwe, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @jwe
EXEC @hr = sp_OADestroy @header
RETURN
END
DECLARE @jweCompact nvarchar(4000)
EXEC sp_OAMethod @jwe, 'Encrypt', @jweCompact OUT, 'This is the secret content.', '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 @header
RETURN
END
PRINT @jweCompact
EXEC @hr = sp_OADestroy @jwe
EXEC @hr = sp_OADestroy @header
END
GO