Skip to content

Flow 7 -- AES-256 Compact-JWE Encrypt / Decrypt (Non-Streaming)

This scenario walks through a symmetric, non-streaming round-trip with an AES-256 key:

  • Resolve the pre-provisioned AES-256 symmetric key (kty="oct").

  • Encrypt a plaintext file → compact JWE (five B64URL segments).

  • Decrypt the compact JWE back to plaintext.

  • Validate that the recovered bytes equal the original.

Key points

  • Uses encryptFile( ) / decryptFile( ) helpers (entire token in memory).
  • Demonstrates the Compact JWE format that's easy to persist or embed.
  • Shows server-side metadata (key requested, material version, algorithm, warnings).

Prerequisites

The flow examples are data-plane only. They never create, rotate, or delete keys — they resolve pre-provisioned playground keys and operate on them. Before running any flow example you must:

  1. Provision a fresh demo-cli playground. Use the ankasecure-demo-provisioning tool to provision the demo-cli playground. This seeds the cryptographic keys the examples operate on and the cli-reference@demo-cli actor that holds capability grants on them.
  2. Use the emitted cli.properties. The provisioning tool writes a cli.properties file that carries the ankasecure.demo.kids catalogue line — the comma-separated list of provisioned key ids, in YAML file order. The examples load this file to discover which keys exist.
  3. Authenticate as cli-reference@demo-cli. Authenticate the SDK as the cli-reference@demo-cli actor — the all-operations actor of the demo-cli playground — so the resolved keys carry the capability grants each operation needs.

Key selection in the examples is by algorithm or by exact name:

  • kidForAlgorithm(alg) returns a pre-provisioned key id matching the requested algorithm — used by the single-key operation flows.
  • requireKid(name) asserts that an exact, named cross-kid endpoint is present in the ankasecure.demo.kids catalogue — used by the cross-kid REENCRYPT / RESIGN flows that must operate on a specific granted source/target pair.

If cli.properties is missing the ankasecure.demo.kids line, the examples fail fast with a clear message instructing you to (re-)provision the demo-cli playground — they will not silently fall back.

PKCS#7 / CMS examples (Flow 19 & Flow 20)

The PKCS#7 interop examples operate on a packaged, non-sensitive CMS EnvelopedData fixture — you do not supply a PKCS#7 file:

  • Fixture: src/main/resources/pkcs7/enveloped-data-sample.p7m, loaded from the classpath by Pkcs7ExampleFixture. It is a single-recipient, zero-signer EnvelopedData artifact from the QA test signer; it carries no private key and no secret.
  • Flow 19 (analysis) needs no key. Structural analysis (analyzePkcs7 / analyzePkcs7Stream) inspects the CMS envelope metadata only, so it runs with no decryption key and no extra configuration.
  • Flow 20 (conversion) needs a pre-provisioned recipient key. Converting EnvelopedData to JWE requires the platform to decrypt the envelope, so it needs the recipient's private key referenced by the pkcs7.decryptionKid property in cli.properties. That key is matched by issuer DN + serial number and is imported by a control-plane step (outside the data-plane SDK); until it is provisioned, Flow 20's conversion calls fail at the server while Flow 19 still runs.
  • Data-plane only. Like every flow example, these never import keystores or perform any key-lifecycle operation.

When to use it

  • Small-to-mid-sized artefacts – ideal for files below the server's configured compact limit (maxPlaintextBytes, default 4 MB; discover via GET /api/v3/crypto/limits) where a single, self-contained token is simpler than a multipart stream. The SDK auto-switches to streaming above it.
  • High-throughput workloads – AES-256 is symmetric, fast and FIPS-validated, making it perfect for CI pipelines, database dumps or nightly backups that must finish quickly.
  • Easy embedding & transport – the compact-JWE string can be logged, emailed, dropped into JSON manifests or pasted into bug reports without worrying about binary encoding or multipart boundaries.

Shared helper – this code imports the utility class from
example-util.md (configuration, authentication, JSON).



Complete Java implementation

src/main/java/co/ankatech/ankasecure/sdk/examples/ExampleScenario7.java

/*
 * Copyright 2025 ANKATech Solutions Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * SPDX-License-Identifier: Apache-2.0
 */
package co.ankatech.ankasecure.sdk.examples;

import co.ankatech.ankasecure.sdk.AuthenticatedSdk;
import co.ankatech.ankasecure.sdk.model.DecryptResultMetadata;
import co.ankatech.ankasecure.sdk.model.EncryptResult;
import co.ankatech.ankasecure.sdk.util.FileIO;

import java.nio.file.Path;
import java.util.Properties;

import static co.ankatech.ankasecure.sdk.examples.ExampleUtil.*;

/**
 * Scenario 7 — AES-256 Compact JWE Helpers.
 *
 * <p>This scenario showcases the SDK's <strong>non-streaming</strong> helpers
 * for symmetric Compact&nbsp;JWE operations:</p>
 * <ol>
 *   <li>Resolve a pre-provisioned <code>AES-GCM-256</code> key from the demo-cli
 *       playground (the SDK is data-plane-only — it does not create keys).</li>
 *   <li>Encrypt a plaintext file (helper stores a Compact&nbsp;JWE).</li>
 *   <li>Decrypt the ciphertext (helper resolves the key from the JWE header).</li>
 *   <li>Print metadata and validate integrity.</li>
 * </ol>
 *
 * <p><b>Implementation notes (Java&nbsp;21+):</b></p>
 * <ul>
 *   <li>All filesystem interactions use the {@link java.nio.file.Path} API.</li>
 *   <li>UTF-8 is enforced explicitly for deterministic encoding.</li>
 *   <li>Temporary artefacts reside under <kbd>temp_files/</kbd>.</li>
 * </ul>
 *
 * <p><b>Thread-safety:</b> this class is stateless and immutable.</p>
 *
 * @author ANKATech Solutions Inc.
 * @since 3.0.0
 * @see ExampleUtil
 * @see ExamplePlaygroundKeys
 * @see AuthenticatedSdk
 */
public final class ExampleScenario7 {

    /** No instantiation &mdash; this class only exposes {@link #main(String[])}. */
    private ExampleScenario7() { }

    /**
     * Runs the AES-256 compact JWE encrypt/decrypt scenario.
     *
     * <p>Loads CLI properties, authenticates against ANKASecure&copy;,
     * and delegates to the scenario logic. On any unrecoverable error
     * the JVM terminates via
     * {@link ExampleUtil#fatal(String, Throwable)}.</p>
     *
     * @param args command-line arguments (ignored)
     */
    public static void main(final String[] args) {

        System.out.println("===== SCENARIO 7 START =====");
        System.out.println("""
                Purpose :
                  * AES-256 Compact-JWE encrypt / decrypt helpers
                  * Non-streaming - full token handled in memory
                  * Operates on a pre-provisioned playground key
                Steps   :
                  1) Resolve pre-provisioned AES-GCM-256 key
                  2) Create sample payload
                  3) Encrypt payload (compact JWE)
                  4) Decrypt ciphertext
                  5) Validate integrity
                --------------------------------------------------------------""");

        try {
            prepareWorkingDir();

            Properties            props      = loadProperties();
            AuthenticatedSdk      sdk        = authenticate(props);
            ExamplePlaygroundKeys playground = ExamplePlaygroundKeys.from(props, sdk);

            runScenario(sdk, playground);

        } catch (Exception ex) {
            fatal("Scenario 7 failed", ex);
        }

        System.out.println("===== SCENARIO 7 END =====");
    }

    /**
     * Executes the AES-256 compact JWE scenario on a pre-provisioned key.
     *
     * <ol>
     *   <li>Create sample plaintext file.</li>
     *   <li>Resolve a pre-provisioned AES-GCM-256 symmetric key.</li>
     *   <li>Encrypt file (compact JWE).</li>
     *   <li>Decrypt and validate integrity.</li>
     * </ol>
     *
     * @param sdk        an authenticated {@link AuthenticatedSdk} instance; must not be {@code null}
     * @param playground the pre-provisioned playground key resolver; must not be {@code null}
     * @throws Exception if any step fails
     */
    private static void runScenario(final AuthenticatedSdk sdk,
                                    final ExamplePlaygroundKeys playground) throws Exception {

        /* 1 -- create sample plaintext -------------------------------------- */
        Path plain = TEMP_DIR.resolve("scenario7_plain.txt");
        FileIO.writeUtf8(plain,
                "Scenario-7 - AES-256 Compact-JWE encrypt / decrypt demo.");
        System.out.println("[1] Plaintext ready          -> " + plain.toAbsolutePath());

        /* 2 -- resolve pre-provisioned key (data-plane SDK: no key creation) */
        final String kid = playground.kidForAlgorithm("AES-GCM-256");
        System.out.println("[2] Using pre-provisioned key -> kid = " + kid);

        /* 3 -- encrypt file (compact JWE) ----------------------------------- */
        Path jweFile = TEMP_DIR.resolve("scenario7.jwe");
        EncryptResult encMeta = sdk.encryptFile(kid, plain, jweFile);
        System.out.println("[3] Ciphertext stored         -> " + jweFile.toAbsolutePath());
        printEncryptMeta(encMeta);

        /* 4 -- decrypt ------------------------------------------------------ */
        Path recovered = TEMP_DIR.resolve("scenario7_dec.txt");
        DecryptResultMetadata decMeta = sdk.decryptFile(jweFile, recovered);
        System.out.println("[4] Decrypted file            -> " + recovered.toAbsolutePath());
        printDecryptMeta(decMeta);

        /* 5 -- validation --------------------------------------------------- */
        boolean match = FileIO.readUtf8(plain)
                .equals(FileIO.readUtf8(recovered));
        System.out.println(match
                ? "[5] SUCCESS - plaintext matches."
                : "[5] FAILURE - plaintext mismatch.");
    }
}

How to run


mvn -q compile exec:java\
  -Dexec.mainClass="co.ankatech.ankasecure.sdk.examples.ExampleScenario7"

Console milestones:

  • AES-256 key resolution from the playground

  • Compact-JWE encryption → scenario7.jwe

  • Decryption → scenario7_dec.txt

  • SUCCESS message confirming byte-perfect round-trip


Where next?