Sample code for 30+ languages & platforms
Java

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 Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Jwe;

public class ChilkatExample {

    public static void main(String[] args) {
        Jwe jwe = new Jwe();

        // Protected header: PBES2 password-based key management with AES-128-GCM content encryption.
        JsonObject header = new JsonObject();
        header.updateString("alg", "PBES2-HS256+A128KW");
        header.updateString("enc", "A128GCM");
        try {
            jwe.setProtectedHeader(header);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Set the PBES2 password for recipient 0.  The password should come from a secure source rather than
        // being hard-coded.
        String password = "myPassword";
        String jweCompact;
        try {
            jwe.setPassword(0, password);

            jweCompact = jwe.encrypt("This is the secret content.", "utf-8");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        System.out.println(jweCompact);
    }
}