Skip to content

Flow 10 --- ML-KEM-1024 Compact-JWE Encrypt / Decrypt (Non-Streaming)

This scenario walks through a post-quantum, non-streaming round-trip with an ML-KEM-1024 key:

  • Generate an ML-KEM-1024 key-pair (kty="ML-KEM").

  • Export its public metadata to a JSON file.

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

  • Decrypt the compact JWE back to plaintext.

  • Validate that the recovered data matches the original.

Key points

  • Uses encryptFile( ) / decryptFile( ) helpers (entire token in memory, no streaming).

  • Demonstrates the Compact JWE format, ideal for pasting into logs, manifests or tickets.

  • Shows server-supplied metadata: key actually used, algorithm, lifetime warnings.

When to use it

  • Medium-sized artefacts --- perfect for files up to ~10 MB where a single self-contained token is simpler than a multipart stream.

  • Post-quantum readiness --- ML-KEM-1024 offers NIST-selected KEM protection for data that must survive future RSA/ECC breaks.

  • Easy distribution & audit --- the compact-JWE string can be emailed, committed to Git, or embedded in JSON APIs without binary handling.

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/ExampleScenario10.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.model.ExportedKeySpec;
import co.ankatech.ankasecure.sdk.model.GenerateKeySpec;
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 10 — ML-KEM-1024 Bulk Helpers (Compact JWE).
 *
 * <p>This scenario demonstrates the <strong>non-streaming</strong> helper
 * methods for RFC&nbsp;7516 <em>Compact&nbsp;JWE</em> using an ML-KEM-1024 key:</p>
 * <ol>
 *   <li>Generate an ML-KEM-1024 key.</li>
 *   <li>Export its public metadata.</li>
 *   <li>Encrypt a plaintext file.</li>
 *   <li>Decrypt the ciphertext.</li>
 *   <li>Validate round-trip integrity.</li>
 * </ol>
 *
 * <p><b>Implementation notes (Java&nbsp;21+):</b></p>
 * <ul>
 *   <li>Filesystem interactions use the {@link java.nio.file.Path} API.</li>
 *   <li>UTF-8 encoding is enforced explicitly for deterministic behaviour.</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 AuthenticatedSdk
 */
public final class ExampleScenario10 {

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

    /**
     * Runs the ML-KEM-1024 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 10 START =====");
        System.out.println("""
                Purpose :
                  * Demonstrate Compact-JWE helpers with an ML-KEM-1024 key
                Steps   :
                  1) Generate ML-KEM-1024 key
                  2) Export public metadata
                  3) Encrypt payload (compact JWE)
                  4) Decrypt ciphertext
                  5) Validate integrity
                --------------------------------------------------------------""");

        try {
            ensureTempDir(TEMP_DIR);

            Properties   props = loadProperties();
            AuthenticatedSdk sdk  = authenticate(props);

            runScenario(sdk);

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

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

    /**
     * Executes the 5-step ML-KEM-1024 compact JWE scenario.
     *
     * <ol>
     *   <li>Create sample plaintext file.</li>
     *   <li>Generate ML-KEM-1024 key.</li>
     *   <li>Export key metadata.</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}
     * @throws Exception if any step fails
     */
    private static void runScenario(final AuthenticatedSdk sdk) throws Exception {

        final String kid = "sc10_kem1024_" + System.currentTimeMillis();

        Path plainFile  = TEMP_DIR.resolve("scenario10_plain.txt");
        Path cipherFile = TEMP_DIR.resolve("scenario10_cipher.jwe");
        Path decFile    = TEMP_DIR.resolve("scenario10_dec.txt");
        Path exportJson = TEMP_DIR.resolve("scenario10_keydata.json");

        /* 1 -- sample plaintext --------------------------------------------- */
        FileIO.writeUtf8(plainFile,
                "Scenario-10 - ML-KEM-1024 non-streaming encrypt / decrypt.");
        System.out.println("[1] Plaintext ready          -> " + plainFile.toAbsolutePath());

        /* 2 -- create ML-KEM-1024 key --------------------------------------- */
        sdk.generateKey(new GenerateKeySpec()
                .setKid(kid)
                .setKty("ML-KEM")
                .setAlg("ML-KEM-1024"));
        System.out.println("[2] Key generated            -> kid = " + kid);

        /* 3 -- export metadata ---------------------------------------------- */
        ExportedKeySpec meta = sdk.exportKey(kid);
        FileIO.writeUtf8(exportJson, toJson(meta));
        System.out.println("[3] Metadata exported        -> " + exportJson.toAbsolutePath());

        /* 4 -- encrypt (Compact JWE) ---------------------------------------- */
        EncryptResult encMeta = sdk.encryptFile(kid, plainFile, cipherFile);
        System.out.println("[4] Ciphertext written       -> " + cipherFile.toAbsolutePath());
        printEncryptMeta(encMeta);

        /* 5 -- decrypt (Compact JWE) ---------------------------------------- */
        DecryptResultMetadata decMeta = sdk.decryptFile(cipherFile, decFile);
        System.out.println("[5] Decrypted file           -> " + decFile.toAbsolutePath());
        printDecryptMeta(decMeta);

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

How to run

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

Console milestones

  • ML-KEM-1024 key generation

  • Metadata export → scenario10_keydata.json

  • Compact-JWE encryption → scenario10_cipher.jwe

  • Decryption → scenario10_dec.txt

  • SUCCESS message confirming byte-perfect round-trip


Where next?