This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new 61b70b9f2b40 CAMEL-25803: Implement hybrid wire format v2 in camel-pqc
(#30777)
61b70b9f2b40 is described below
commit 61b70b9f2b403bf19523b929fa5785cf5e9c6f25
Author: Guillaume Nodet <[email protected]>
AuthorDate: Wed Nov 25 21:06:26 2026 +0100
CAMEL-25803: Implement hybrid wire format v2 in camel-pqc (#30777)
HybridSignature.sign() and HybridKEM.encapsulate() previously produced the
legacy v1 format [4 bytes: length][payload1][payload2], while
pqc-hybrid.adoc
documented the self-describing v2 format as the default since Camel 4.19.
PQCAlgorithmId was public API with zero callers because no code ever wrote
or
read a v2 header.
Changes:
- HybridSignature: sign() now emits wire format v2 with magic bytes 0x50
0x51,
version 0x02, format type 0x01, and 16-bit algorithm IDs derived from the
Signature instances' getAlgorithm() names. parse() auto-detects v1 vs v2
by
checking the magic bytes; v1 blobs are still accepted for backward compat.
HybridSignatureComponents gains classicalAlgorithmId(), pqcAlgorithmId(),
and
version() accessors documented in the adoc snippet that previously did not
compile.
- HybridKEM: same treatment — encapsulate() emits v2 with format type 0x02,
parse() auto-detects. HybridEncapsulationComponents gains the same
accessors.
- PQCAlgorithmId: removed DILITHIUM (wrong JCA name 'DILITHIUM', real name
is
'ML-DSA' covered by ML_DSA), SPHINCSPLUS (JCA name 'SLH-DSA' covered by
SLH_DSA), PICNIC (removed from BouncyCastle), KYBER (alias for ML-KEM, was
registering 'KYBER' instead of 'ML-KEM'). Fixed FRODO JCA name from
'FRODO'
to 'FrodoKEM' to match PQCKeyEncapsulationAlgorithms. Static initializer
now
uses putIfAbsent so the first (canonical) constant for each JCA name wins.
- Tests: added testSignProducesV2WireFormat and
testParseV1BackwardCompatibility
in HybridSignatureTest; equivalent tests in HybridKEMTest. Updated
existing
parse tests to assert version==2 (combineSignatures/combineEncapsulations
now
produce v2).
Follow-up commits:
- Address review: upgrade guide, doc fixes, algorithm ID auth validation,
tests
- Address review: doc consistency, KEM combiner note, upgrade guide
wording, verify() Javadoc
Co-authored-by: Claude Sonnet 4.6 <[email protected]>
---
.../org/apache/camel/catalog/docs/pqc-hybrid.adoc | 26 ++-
components/camel-pqc/src/main/docs/pqc-hybrid.adoc | 26 ++-
.../apache/camel/component/pqc/PQCAlgorithmId.java | 16 +-
.../component/pqc/crypto/hybrid/HybridKEM.java | 210 ++++++++++++++++-
.../pqc/crypto/hybrid/HybridSignature.java | 257 ++++++++++++++++++---
.../component/pqc/crypto/hybrid/HybridKEMTest.java | 230 ++++++++++++++++++
.../pqc/crypto/hybrid/HybridSignatureTest.java | 230 +++++++++++++++++-
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 20 ++
8 files changed, 936 insertions(+), 79 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/pqc-hybrid.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/pqc-hybrid.adoc
index da850fb5bd6a..aae5743892d7 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/pqc-hybrid.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/pqc-hybrid.adoc
@@ -101,7 +101,7 @@ The same pattern applies for other classical algorithms.
For example, to use Ed2
**Hybrid Signature Wire Format:**
-Since Camel 4.19, hybrid signatures use wire format v2 which includes magic
bytes, version, and algorithm identifiers (see <<Wire Format v2 and Algorithm
Identification>>). The v1 format `[4 bytes: classical sig length][classical
sig][pqc sig]` is still accepted on input for backward compatibility.
+Since Camel 4.24, hybrid signatures use wire format v2 which includes magic
bytes, version, and algorithm identifiers (see <<Wire Format v2 and Algorithm
Identification>>). The v1 format `[4 bytes: classical sig length][classical
sig][pqc sig]` is still accepted on input for backward compatibility.
**Headers set by hybrid signature operations:**
@@ -214,7 +214,7 @@ The same pattern applies for other classical algorithms.
For example, to use ECD
**Hybrid KEM Wire Format:**
-Since Camel 4.19, hybrid encapsulations use wire format v2 which includes
magic bytes, version, and algorithm identifiers (see <<Wire Format v2 and
Algorithm Identification>>). The v1 format `[4 bytes: classical encap
length][classical encap][pqc encap]` is still accepted on input for backward
compatibility.
+Since Camel 4.24, hybrid encapsulations use wire format v2 which includes
magic bytes, version, and algorithm identifiers (see <<Wire Format v2 and
Algorithm Identification>>). The v1 format `[4 bytes: classical encap
length][classical encap][pqc encap]` is still accepted on input for backward
compatibility.
**Headers set by hybrid KEM operations:**
@@ -286,9 +286,11 @@ Based on NIST recommendations for the transition period:
5. **Algorithm agility**: Design your system to allow algorithm upgrades as
standards evolve.
+6. **KEM combiner**: The hybrid shared secret is derived by concatenating the
two component secrets and running them through HKDF. Binding the combined
secret to ciphertext or public-key material (as proposed in
draft-irtf-cfrg-hybrid-kem) is not yet implemented and is deferred to a future
release.
+
== Wire Format v2 and Algorithm Identification
-Starting with Camel 4.19, the hybrid signature, hybrid KEM, and
xref:dataformats:pqc-dataformat.adoc[PQC DataFormat] wire formats include
self-describing algorithm metadata. This makes the binary output portable and
verifiable without out-of-band knowledge of which algorithms were used.
+Starting with Camel 4.24, the hybrid signature and hybrid KEM wire formats
include self-describing algorithm metadata. This makes the binary output
portable and verifiable without out-of-band knowledge of which algorithms were
used.
=== PQCAlgorithmId
@@ -313,7 +315,7 @@ The `PQCAlgorithmId` enum maps every supported algorithm --
classical signature,
|`0x0400-0x04FF`
|Post-quantum KEM
-|ML-KEM (`0x0401`), BIKE (`0x0402`), NTRU (`0x0407`), KYBER (`0x040A`)
+|ML-KEM (`0x0401`), BIKE (`0x0402`), NTRU (`0x0407`)
|`0x0500-0x05FF`
|Symmetric encryption
@@ -354,6 +356,9 @@ String jca = alg.getJcaName(); // "ML-DSA"
HybridSignature.HybridSignatureComponents components =
HybridSignature.parse(hybridSig);
// v2 components carry algorithm identifiers
+// WARNING: these algorithm IDs are unauthenticated metadata written by the
sender.
+// Do NOT use them to select which key or algorithm to use for cryptographic
operations.
+// Always use the algorithm configured by the operator.
PQCAlgorithmId classical = components.classicalAlgorithmId(); // e.g.
SHA256_WITH_ECDSA
PQCAlgorithmId pqc = components.pqcAlgorithmId(); // e.g. ML_DSA
int version = components.version(); // 2
@@ -363,7 +368,7 @@ int version = components.version();
// 2
=== Wire Format v2 Layout
-All three output types (hybrid signature, hybrid KEM, PQC DataFormat) share
the same 8-byte header:
+Both output types (hybrid signature and hybrid KEM) share the same 8-byte
header:
[source,text]
----
@@ -391,17 +396,14 @@ All three output types (hybrid signature, hybrid KEM, PQC
DataFormat) share the
|Hybrid KEM
|Classical KEM algorithm
|PQC KEM algorithm
-
-|`0x03`
-|KEM DataFormat
-|KEM algorithm
-|Symmetric algorithm
|===
+NOTE: The PQC DataFormat retains the v1 wire format for now; v2 migration for
the data format is tracked in CAMEL-27548.
+
=== Backward Compatibility
Wire format v2 is fully backward-compatible with v1:
-* **Writing** -- `sign()`, `encapsulate()`, and `marshal()` always produce v2
output.
-* **Reading** -- `parse()`, `verify()`, `extract()`, and `unmarshal()`
auto-detect the format by checking the first two bytes for the magic bytes
`0x50 0x51`. If absent, they fall back to v1 parsing.
+* **Writing** -- `sign()`, `encapsulate()`, and the 2-argument
`combineSignatures()` / `combineEncapsulations()` overloads always produce v2
output.
+* **Reading** -- `parse()`, `verify()`, and `extract()` auto-detect the format
by checking the first two bytes for the magic bytes `0x50 0x51`. If absent,
they fall back to v1 parsing.
* **Safety** -- The magic bytes `0x50 0x51`, interpreted as the first two
bytes of a big-endian 32-bit integer, produce values above 1.3 billion. No
valid v1 payload has a classical signature or encapsulation of that size, so
false positives are impossible in practice.
diff --git a/components/camel-pqc/src/main/docs/pqc-hybrid.adoc
b/components/camel-pqc/src/main/docs/pqc-hybrid.adoc
index da850fb5bd6a..aae5743892d7 100644
--- a/components/camel-pqc/src/main/docs/pqc-hybrid.adoc
+++ b/components/camel-pqc/src/main/docs/pqc-hybrid.adoc
@@ -101,7 +101,7 @@ The same pattern applies for other classical algorithms.
For example, to use Ed2
**Hybrid Signature Wire Format:**
-Since Camel 4.19, hybrid signatures use wire format v2 which includes magic
bytes, version, and algorithm identifiers (see <<Wire Format v2 and Algorithm
Identification>>). The v1 format `[4 bytes: classical sig length][classical
sig][pqc sig]` is still accepted on input for backward compatibility.
+Since Camel 4.24, hybrid signatures use wire format v2 which includes magic
bytes, version, and algorithm identifiers (see <<Wire Format v2 and Algorithm
Identification>>). The v1 format `[4 bytes: classical sig length][classical
sig][pqc sig]` is still accepted on input for backward compatibility.
**Headers set by hybrid signature operations:**
@@ -214,7 +214,7 @@ The same pattern applies for other classical algorithms.
For example, to use ECD
**Hybrid KEM Wire Format:**
-Since Camel 4.19, hybrid encapsulations use wire format v2 which includes
magic bytes, version, and algorithm identifiers (see <<Wire Format v2 and
Algorithm Identification>>). The v1 format `[4 bytes: classical encap
length][classical encap][pqc encap]` is still accepted on input for backward
compatibility.
+Since Camel 4.24, hybrid encapsulations use wire format v2 which includes
magic bytes, version, and algorithm identifiers (see <<Wire Format v2 and
Algorithm Identification>>). The v1 format `[4 bytes: classical encap
length][classical encap][pqc encap]` is still accepted on input for backward
compatibility.
**Headers set by hybrid KEM operations:**
@@ -286,9 +286,11 @@ Based on NIST recommendations for the transition period:
5. **Algorithm agility**: Design your system to allow algorithm upgrades as
standards evolve.
+6. **KEM combiner**: The hybrid shared secret is derived by concatenating the
two component secrets and running them through HKDF. Binding the combined
secret to ciphertext or public-key material (as proposed in
draft-irtf-cfrg-hybrid-kem) is not yet implemented and is deferred to a future
release.
+
== Wire Format v2 and Algorithm Identification
-Starting with Camel 4.19, the hybrid signature, hybrid KEM, and
xref:dataformats:pqc-dataformat.adoc[PQC DataFormat] wire formats include
self-describing algorithm metadata. This makes the binary output portable and
verifiable without out-of-band knowledge of which algorithms were used.
+Starting with Camel 4.24, the hybrid signature and hybrid KEM wire formats
include self-describing algorithm metadata. This makes the binary output
portable and verifiable without out-of-band knowledge of which algorithms were
used.
=== PQCAlgorithmId
@@ -313,7 +315,7 @@ The `PQCAlgorithmId` enum maps every supported algorithm --
classical signature,
|`0x0400-0x04FF`
|Post-quantum KEM
-|ML-KEM (`0x0401`), BIKE (`0x0402`), NTRU (`0x0407`), KYBER (`0x040A`)
+|ML-KEM (`0x0401`), BIKE (`0x0402`), NTRU (`0x0407`)
|`0x0500-0x05FF`
|Symmetric encryption
@@ -354,6 +356,9 @@ String jca = alg.getJcaName(); // "ML-DSA"
HybridSignature.HybridSignatureComponents components =
HybridSignature.parse(hybridSig);
// v2 components carry algorithm identifiers
+// WARNING: these algorithm IDs are unauthenticated metadata written by the
sender.
+// Do NOT use them to select which key or algorithm to use for cryptographic
operations.
+// Always use the algorithm configured by the operator.
PQCAlgorithmId classical = components.classicalAlgorithmId(); // e.g.
SHA256_WITH_ECDSA
PQCAlgorithmId pqc = components.pqcAlgorithmId(); // e.g. ML_DSA
int version = components.version(); // 2
@@ -363,7 +368,7 @@ int version = components.version();
// 2
=== Wire Format v2 Layout
-All three output types (hybrid signature, hybrid KEM, PQC DataFormat) share
the same 8-byte header:
+Both output types (hybrid signature and hybrid KEM) share the same 8-byte
header:
[source,text]
----
@@ -391,17 +396,14 @@ All three output types (hybrid signature, hybrid KEM, PQC
DataFormat) share the
|Hybrid KEM
|Classical KEM algorithm
|PQC KEM algorithm
-
-|`0x03`
-|KEM DataFormat
-|KEM algorithm
-|Symmetric algorithm
|===
+NOTE: The PQC DataFormat retains the v1 wire format for now; v2 migration for
the data format is tracked in CAMEL-27548.
+
=== Backward Compatibility
Wire format v2 is fully backward-compatible with v1:
-* **Writing** -- `sign()`, `encapsulate()`, and `marshal()` always produce v2
output.
-* **Reading** -- `parse()`, `verify()`, `extract()`, and `unmarshal()`
auto-detect the format by checking the first two bytes for the magic bytes
`0x50 0x51`. If absent, they fall back to v1 parsing.
+* **Writing** -- `sign()`, `encapsulate()`, and the 2-argument
`combineSignatures()` / `combineEncapsulations()` overloads always produce v2
output.
+* **Reading** -- `parse()`, `verify()`, and `extract()` auto-detect the format
by checking the first two bytes for the magic bytes `0x50 0x51`. If absent,
they fall back to v1 parsing.
* **Safety** -- The magic bytes `0x50 0x51`, interpreted as the first two
bytes of a big-endian 32-bit integer, produce values above 1.3 billion. No
valid v1 payload has a classical signature or encapsulation of that size, so
false positives are impossible in practice.
diff --git
a/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/PQCAlgorithmId.java
b/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/PQCAlgorithmId.java
index 7d52c0a5b25e..d4ca0356315c 100644
---
a/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/PQCAlgorithmId.java
+++
b/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/PQCAlgorithmId.java
@@ -49,15 +49,16 @@ public enum PQCAlgorithmId {
SHA512_WITH_RSA(0x0108, "SHA512withRSA"),
// PQC signature algorithms (0x0200-0x02FF)
+ // Retired IDs -- must never be reused:
+ // 0x0206 was DILITHIUM (shipped in 4.19.0, algorithm renamed upstream
to ML-DSA)
+ // 0x0208 was SPHINCSPLUS (shipped in 4.19.0, algorithm renamed upstream
to SLH-DSA)
+ // 0x0209 was PICNIC (shipped in 4.19.0, algorithm dropped upstream)
ML_DSA(0x0201, "ML-DSA"),
SLH_DSA(0x0202, "SLH-DSA"),
LMS(0x0203, "LMS"),
XMSS(0x0204, "XMSS"),
XMSSMT(0x0205, "XMSSMT"),
- DILITHIUM(0x0206, "DILITHIUM"),
FALCON(0x0207, "FALCON"),
- SPHINCSPLUS(0x0208, "SPHINCSPLUS"),
- PICNIC(0x0209, "PICNIC"),
MAYO(0x020A, "Mayo"),
SNOVA(0x020B, "Snova"),
@@ -69,6 +70,8 @@ public enum PQCAlgorithmId {
X448(0x0305, "X448"),
// PQC KEM algorithms (0x0400-0x04FF)
+ // Retired IDs -- must never be reused:
+ // 0x040A was KYBER (shipped in 4.19.0, algorithm renamed upstream to
ML-KEM)
ML_KEM(0x0401, "ML-KEM"),
BIKE(0x0402, "BIKE"),
HQC(0x0403, "HQC"),
@@ -78,11 +81,10 @@ public enum PQCAlgorithmId {
@Deprecated(since = "4.24")
CMCE(0x0404, "CMCE"),
SABER(0x0405, "SABER"),
- FRODO(0x0406, "FRODO"),
+ FRODO(0x0406, "FrodoKEM"),
NTRU(0x0407, "NTRU"),
NTRU_LPRIME(0x0408, "NTRULPRime"),
SNTRU_PRIME(0x0409, "SNTRUPrime"),
- KYBER(0x040A, "KYBER"),
// Symmetric encryption algorithms (0x0500-0x05FF)
AES(0x0501, "AES"),
@@ -103,7 +105,9 @@ public enum PQCAlgorithmId {
static {
for (PQCAlgorithmId alg : values()) {
BY_ID.put(alg.id, alg);
- BY_JCA_NAME.put(alg.jcaName.toLowerCase(), alg);
+ // Use putIfAbsent so that the first (canonical) constant for a
given JCA name wins and
+ // deprecated aliases added later do not silently shadow it.
+ BY_JCA_NAME.putIfAbsent(alg.jcaName.toLowerCase(), alg);
}
}
diff --git
a/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/crypto/hybrid/HybridKEM.java
b/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/crypto/hybrid/HybridKEM.java
index a2743244f08e..5c960a68d1da 100644
---
a/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/crypto/hybrid/HybridKEM.java
+++
b/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/crypto/hybrid/HybridKEM.java
@@ -29,6 +29,7 @@ import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
+import org.apache.camel.component.pqc.PQCAlgorithmId;
import org.apache.camel.component.pqc.PQCKemLocks;
import org.apache.camel.component.pqc.PQCSymmetricAlgorithms;
import org.apache.camel.util.SecureRandomHelper;
@@ -56,16 +57,49 @@ import org.bouncycastle.jcajce.spec.KEMGenerateSpec;
* their {@code init()} call to the call that returns the result and are not
thread-safe, so each of those sequences
* runs while holding the instance's monitor.
* <p>
- * Wire format: [4 bytes: classical encap length][classical encap][pqc encap]
+ * <strong>Wire format v2</strong> (default since Camel 4.24):
+ *
+ * <pre>
+ * [2 bytes: magic 0x50 0x51 ("PQ")]
+ * [1 byte: version 0x02]
+ * [1 byte: format type 0x02 = hybrid KEM]
+ * [2 bytes: classical KEM algorithm ID]
+ * [2 bytes: PQC KEM algorithm ID]
+ * [4 bytes: classical encapsulation length]
+ * [N bytes: classical encapsulation]
+ * [M bytes: PQC encapsulation]
+ * </pre>
+ * <p>
+ * <strong>Wire format v1</strong> (legacy, still accepted on input):
+ *
+ * <pre>
+ * [4 bytes: classical encapsulation length]
+ * [N bytes: classical encapsulation]
+ * [M bytes: PQC encapsulation]
+ * </pre>
+ *
+ * The two formats are distinguished on input by checking the first two bytes
for the magic sequence {@code 0x50 0x51}.
*/
public final class HybridKEM {
+ /** Wire format magic bytes: ASCII "PQ" (0x50 0x51). */
+ static final byte MAGIC_BYTE_1 = 0x50;
+ /** Wire format magic bytes: ASCII "PQ" (0x50 0x51). */
+ static final byte MAGIC_BYTE_2 = 0x51;
+ /** Current wire format version. */
+ static final byte VERSION_V2 = 0x02;
+ /** Format type identifier for hybrid KEM encapsulations. */
+ static final byte FORMAT_HYBRID_KEM = 0x02;
+ /** Total byte count of the v2 header (magic + version + type + 2
algorithm IDs + payload length). */
+ static final int V2_HEADER_SIZE = 12;
+
private HybridKEM() {
// Utility class
}
/**
- * Generates a hybrid encapsulation using both classical ECDH/XDH and PQC
KEM.
+ * Generates a hybrid encapsulation using both classical ECDH/XDH and PQC
KEM. The encapsulation uses wire format
+ * v2, which embeds the algorithm identifiers in the header.
*
* @param classicalPublicKey the recipient's classical public key (EC or
XDH)
* @param pqcPublicKey the recipient's PQC public key
@@ -129,8 +163,12 @@ public final class HybridKEM {
// caller gave it, or every encapsulation produced by an earlier
version stops decrypting.
SecretKey hybridSecretKey = new SecretKeySpec(combinedSecret,
PQCSymmetricAlgorithms.toJceName(symmetricAlgorithm));
- // Combine encapsulations
- byte[] hybridEncapsulation =
combineEncapsulations(classicalEncapsulation, pqcEncapsulation);
+ // Resolve algorithm IDs for the v2 header
+ PQCAlgorithmId classicalAlgId =
PQCAlgorithmId.fromJcaName(classicalKA.getAlgorithm());
+ PQCAlgorithmId pqcAlgId =
PQCAlgorithmId.fromJcaName(pqcKemGenerator.getAlgorithm());
+
+ // Combine encapsulations in v2 wire format
+ byte[] hybridEncapsulation =
combineEncapsulations(classicalEncapsulation, pqcEncapsulation, classicalAlgId,
pqcAlgId);
return new HybridEncapsulationResult(
hybridEncapsulation,
@@ -172,6 +210,9 @@ public final class HybridKEM {
// Parse the hybrid encapsulation
HybridEncapsulationComponents components = parse(hybridEncapsulation);
+ // Validate algorithm IDs if present (v2 format)
+ validateAlgorithmIds(components, classicalKA, pqcKemGenerator);
+
// Reconstruct the ephemeral public key from classical encapsulation
PublicKey ephemeralPublicKey = reconstructPublicKey(
components.classicalEncapsulation(),
@@ -208,7 +249,8 @@ public final class HybridKEM {
}
/**
- * Parses a hybrid encapsulation into its component parts.
+ * Parses a hybrid encapsulation into its component parts. Auto-detects
the wire format version by checking the
+ * first two bytes for the magic sequence {@code 0x50 0x51}: v2 when
found, v1 (legacy) otherwise.
*
* @param hybridEncapsulation the hybrid encapsulation to parse
* @return the parsed components
@@ -219,42 +261,169 @@ public final class HybridKEM {
throw new IllegalArgumentException("Invalid hybrid encapsulation:
too short");
}
+ // Auto-detect v2 by checking the magic bytes
+ if (hybridEncapsulation[0] == MAGIC_BYTE_1 && hybridEncapsulation[1]
== MAGIC_BYTE_2) {
+ return parseV2(hybridEncapsulation);
+ }
+
+ return parseV1(hybridEncapsulation);
+ }
+
+ /**
+ * Parses a v1 (legacy) hybrid encapsulation.
+ * <p>
+ * Layout: {@code [4 bytes: classical encap length][classical encap][pqc
encap]}
+ */
+ private static HybridEncapsulationComponents parseV1(byte[]
hybridEncapsulation) {
ByteBuffer buffer = ByteBuffer.wrap(hybridEncapsulation);
- // Read classical encapsulation length
int classicalLength = buffer.getInt();
if (classicalLength <= 0 || classicalLength >
hybridEncapsulation.length - 4) {
throw new IllegalArgumentException("Invalid hybrid encapsulation:
invalid classical length");
}
+ byte[] classicalEncapsulation = new byte[classicalLength];
+ buffer.get(classicalEncapsulation);
+
+ int pqcLength = buffer.remaining();
+ if (pqcLength <= 0) {
+ throw new IllegalArgumentException("Invalid hybrid encapsulation:
missing PQC encapsulation");
+ }
+ byte[] pqcEncapsulation = new byte[pqcLength];
+ buffer.get(pqcEncapsulation);
+
+ return new HybridEncapsulationComponents(classicalEncapsulation,
pqcEncapsulation, null, null, 1);
+ }
+
+ /**
+ * Parses a v2 hybrid encapsulation.
+ * <p>
+ * Layout:
+ *
+ * <pre>
+ * [2 bytes: magic][1 byte: version][1 byte: format type]
+ * [2 bytes: classical KEM algorithm ID][2 bytes: PQC KEM algorithm ID]
+ * [4 bytes: classical encap length][N bytes: classical encap][M bytes:
PQC encap]
+ * </pre>
+ */
+ private static HybridEncapsulationComponents parseV2(byte[]
hybridEncapsulation) {
+ if (hybridEncapsulation.length < V2_HEADER_SIZE + 2) {
+ throw new IllegalArgumentException("Invalid v2 hybrid
encapsulation: too short");
+ }
+
+ ByteBuffer buffer = ByteBuffer.wrap(hybridEncapsulation);
+
+ // Skip magic (2 bytes)
+ buffer.get(); // 0x50
+ buffer.get(); // 0x51
+
+ byte version = buffer.get();
+ if (version != VERSION_V2) {
+ throw new IllegalArgumentException("Invalid v2 hybrid
encapsulation: unsupported version " + version);
+ }
+
+ byte formatType = buffer.get();
+ if (formatType != FORMAT_HYBRID_KEM) {
+ throw new IllegalArgumentException("Invalid v2 hybrid
encapsulation: unexpected format type " + formatType);
+ }
+
+ // Read algorithm IDs (16-bit each)
+ int classicalAlgRaw = buffer.getShort() & 0xFFFF;
+ int pqcAlgRaw = buffer.getShort() & 0xFFFF;
+ PQCAlgorithmId classicalAlgId = PQCAlgorithmId.fromId(classicalAlgRaw);
+ PQCAlgorithmId pqcAlgId = PQCAlgorithmId.fromId(pqcAlgRaw);
+
// Read classical encapsulation
+ int classicalLength = buffer.getInt();
+ int remaining = buffer.remaining();
+ if (classicalLength <= 0 || classicalLength > remaining) {
+ throw new IllegalArgumentException("Invalid v2 hybrid
encapsulation: invalid classical length");
+ }
byte[] classicalEncapsulation = new byte[classicalLength];
buffer.get(classicalEncapsulation);
// Read PQC encapsulation (remaining bytes)
int pqcLength = buffer.remaining();
if (pqcLength <= 0) {
- throw new IllegalArgumentException("Invalid hybrid encapsulation:
missing PQC encapsulation");
+ throw new IllegalArgumentException("Invalid v2 hybrid
encapsulation: missing PQC encapsulation");
}
byte[] pqcEncapsulation = new byte[pqcLength];
buffer.get(pqcEncapsulation);
- return new HybridEncapsulationComponents(classicalEncapsulation,
pqcEncapsulation);
+ return new HybridEncapsulationComponents(classicalEncapsulation,
pqcEncapsulation, classicalAlgId, pqcAlgId, 2);
}
/**
- * Combines classical and PQC encapsulations into a hybrid encapsulation.
+ * Combines classical and PQC encapsulations into a v2 wire format hybrid
encapsulation embedding the given
+ * algorithm identifiers.
+ *
+ * @param classicalEncapsulation the classical encapsulation bytes
+ * @param pqcEncapsulation the PQC encapsulation bytes
+ * @param classicalAlgId the classical KEM algorithm identifier
+ * @param pqcAlgId the PQC KEM algorithm identifier
+ * @return the combined v2 hybrid encapsulation
*/
- public static byte[] combineEncapsulations(byte[] classicalEncapsulation,
byte[] pqcEncapsulation) {
- ByteBuffer buffer = ByteBuffer.allocate(4 +
classicalEncapsulation.length + pqcEncapsulation.length);
+ public static byte[] combineEncapsulations(
+ byte[] classicalEncapsulation, byte[] pqcEncapsulation,
+ PQCAlgorithmId classicalAlgId, PQCAlgorithmId pqcAlgId) {
+ int totalSize = V2_HEADER_SIZE + classicalEncapsulation.length +
pqcEncapsulation.length;
+ ByteBuffer buffer = ByteBuffer.allocate(totalSize);
+ buffer.put(MAGIC_BYTE_1);
+ buffer.put(MAGIC_BYTE_2);
+ buffer.put(VERSION_V2);
+ buffer.put(FORMAT_HYBRID_KEM);
+ buffer.putShort((short) classicalAlgId.getId());
+ buffer.putShort((short) pqcAlgId.getId());
buffer.putInt(classicalEncapsulation.length);
buffer.put(classicalEncapsulation);
buffer.put(pqcEncapsulation);
return buffer.array();
}
+ /**
+ * Combines classical and PQC encapsulations into a v2 wire format hybrid
encapsulation without algorithm
+ * identifiers. Equivalent to calling {@link
#combineEncapsulations(byte[], byte[], PQCAlgorithmId, PQCAlgorithmId)}
+ * with {@link PQCAlgorithmId#UNKNOWN} for both algorithm IDs.
+ *
+ * @param classicalEncapsulation the classical encapsulation bytes
+ * @param pqcEncapsulation the PQC encapsulation bytes
+ * @return the combined v2 hybrid encapsulation
+ */
+ public static byte[] combineEncapsulations(byte[] classicalEncapsulation,
byte[] pqcEncapsulation) {
+ return combineEncapsulations(classicalEncapsulation, pqcEncapsulation,
PQCAlgorithmId.UNKNOWN, PQCAlgorithmId.UNKNOWN);
+ }
+
+ /**
+ * Validates that the algorithm IDs embedded in a v2 wire format match the
algorithms configured in the KeyAgreement
+ * and KeyGenerator instances. Skips validation for v1 payloads (null IDs)
and for UNKNOWN algorithm IDs (the sender
+ * may not have written a known ID).
+ */
+ private static void validateAlgorithmIds(
+ HybridEncapsulationComponents components, KeyAgreement
classicalKA, KeyGenerator pqcKemGenerator) {
+ if (components.classicalAlgorithmId() != null &&
components.classicalAlgorithmId() != PQCAlgorithmId.UNKNOWN) {
+ PQCAlgorithmId expected =
PQCAlgorithmId.fromJcaName(classicalKA.getAlgorithm());
+ if (expected != PQCAlgorithmId.UNKNOWN && expected !=
components.classicalAlgorithmId()) {
+ throw new IllegalArgumentException(
+ "Header algorithm ID mismatch: expected " + expected +
" but found "
+ +
components.classicalAlgorithmId());
+ }
+ }
+ if (components.pqcAlgorithmId() != null && components.pqcAlgorithmId()
!= PQCAlgorithmId.UNKNOWN) {
+ PQCAlgorithmId expected =
PQCAlgorithmId.fromJcaName(pqcKemGenerator.getAlgorithm());
+ if (expected != PQCAlgorithmId.UNKNOWN && expected !=
components.pqcAlgorithmId()) {
+ throw new IllegalArgumentException(
+ "Header algorithm ID mismatch: expected " + expected +
" but found " + components.pqcAlgorithmId());
+ }
+ }
+ }
+
/**
* Combines two shared secrets using HKDF.
+ *
+ * <p>
+ * The combiner uses simple concatenation of the two secrets as the HKDF
input key material. Binding the combined
+ * secret to ciphertext or public-key material (as proposed in
draft-irtf-cfrg-hybrid-kem) is not yet implemented
+ * and is deferred to a future version.
*/
private static byte[] combineSecrets(
byte[] secret1,
@@ -358,7 +527,24 @@ public final class HybridKEM {
/**
* Record holding the parsed components of a hybrid encapsulation.
+ * <p>
+ * <strong>Warning:</strong> The algorithm IDs in the header are
informational metadata written by the sender and
+ * are <em>not</em> authenticated by any signature or MAC. Applications
must not use these IDs to select which key
+ * or algorithm to use for cryptographic operations; always use the
algorithm configured by the operator.
+ *
+ * @param classicalEncapsulation the raw classical encapsulation bytes
+ * @param pqcEncapsulation the raw PQC encapsulation bytes
+ * @param classicalAlgorithmId the classical KEM algorithm identifier
from the wire format header, or {@code null}
+ * for v1 payloads
+ * @param pqcAlgorithmId the PQC KEM algorithm identifier from the
wire format header, or {@code null} for
+ * v1 payloads
+ * @param version the wire format version: {@code 1} for
legacy v1, {@code 2} for v2
*/
- public record HybridEncapsulationComponents(byte[] classicalEncapsulation,
byte[] pqcEncapsulation) {
+ public record HybridEncapsulationComponents(
+ byte[] classicalEncapsulation,
+ byte[] pqcEncapsulation,
+ PQCAlgorithmId classicalAlgorithmId,
+ PQCAlgorithmId pqcAlgorithmId,
+ int version) {
}
}
diff --git
a/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/crypto/hybrid/HybridSignature.java
b/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/crypto/hybrid/HybridSignature.java
index 281d99ace36d..ee2f34a6e43f 100644
---
a/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/crypto/hybrid/HybridSignature.java
+++
b/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/crypto/hybrid/HybridSignature.java
@@ -19,30 +19,67 @@ package org.apache.camel.component.pqc.crypto.hybrid;
import java.nio.ByteBuffer;
import java.security.*;
+import org.apache.camel.component.pqc.PQCAlgorithmId;
+
/**
* Utility class for hybrid signature operations combining classical and
post-quantum cryptography algorithms.
* <p>
* Hybrid signatures provide defense-in-depth by combining a classical
signature (e.g., ECDSA, RSA) with a post-quantum
- * signature (e.g., ML-DSA, Dilithium). Both signatures must verify for the
hybrid signature to be valid, ensuring
- * security even if one algorithm is compromised.
+ * signature (e.g., ML-DSA). Both signatures must verify for the hybrid
signature to be valid, ensuring security even if
+ * one algorithm is compromised.
+ * <p>
+ * <strong>Wire format v2</strong> (default since Camel 4.24):
+ *
+ * <pre>
+ * [2 bytes: magic 0x50 0x51 ("PQ")]
+ * [1 byte: version 0x02]
+ * [1 byte: format type 0x01 = hybrid signature]
+ * [2 bytes: classical algorithm ID]
+ * [2 bytes: PQC algorithm ID]
+ * [4 bytes: classical signature length]
+ * [N bytes: classical signature]
+ * [M bytes: PQC signature]
+ * </pre>
* <p>
- * The wire format is: [4 bytes: classical sig length][classical sig][pqc sig]
+ * <strong>Wire format v1</strong> (legacy, still accepted on input):
+ *
+ * <pre>
+ * [4 bytes: classical signature length]
+ * [N bytes: classical signature]
+ * [M bytes: PQC signature]
+ * </pre>
+ *
+ * The two formats are distinguished on input by checking the first two bytes
for the magic sequence {@code 0x50 0x51}.
+ * No valid v1 payload has a classical-signature length above 1.3 billion, so
false positives are impossible in
+ * practice.
*/
public final class HybridSignature {
+ /** Wire format magic bytes: ASCII "PQ" (0x50 0x51). */
+ static final byte MAGIC_BYTE_1 = 0x50;
+ /** Wire format magic bytes: ASCII "PQ" (0x50 0x51). */
+ static final byte MAGIC_BYTE_2 = 0x51;
+ /** Current wire format version. */
+ static final byte VERSION_V2 = 0x02;
+ /** Format type identifier for hybrid signatures. */
+ static final byte FORMAT_HYBRID_SIGNATURE = 0x01;
+ /** Total byte count of the v2 header (magic + version + type + 2
algorithm IDs + payload length). */
+ static final int V2_HEADER_SIZE = 12;
+
private HybridSignature() {
// Utility class
}
/**
- * Creates a hybrid signature by signing data with both classical and PQC
algorithms.
+ * Creates a hybrid signature by signing data with both classical and PQC
algorithms. The output uses wire format
+ * v2, which embeds the algorithm identifiers in the header.
*
* @param data the data to sign
* @param classicalPrivateKey the classical private key (e.g.,
ECDSA, RSA)
* @param classicalSigner the classical signature instance
- * @param pqcPrivateKey the PQC private key (e.g., ML-DSA,
Dilithium)
+ * @param pqcPrivateKey the PQC private key (e.g., ML-DSA)
* @param pqcSigner the PQC signature instance
- * @return the hybrid signature containing both
signatures
+ * @return the hybrid signature in wire format v2
* @throws InvalidKeyException if a key is invalid
* @throws SignatureException if signing fails
* @throws IllegalArgumentException if any parameter is null
@@ -70,22 +107,28 @@ public final class HybridSignature {
pqcSigner.update(data);
byte[] pqcSignature = pqcSigner.sign();
- // Combine: [4 bytes length][classical sig][pqc sig]
- return combineSignatures(classicalSignature, pqcSignature);
+ // Resolve algorithm IDs from the JCA algorithm names reported by the
Signature instances
+ PQCAlgorithmId classicalAlgId =
PQCAlgorithmId.fromJcaName(classicalSigner.getAlgorithm());
+ PQCAlgorithmId pqcAlgId =
PQCAlgorithmId.fromJcaName(pqcSigner.getAlgorithm());
+
+ // Produce v2 wire format with algorithm identifiers in the header
+ return combineSignatures(classicalSignature, pqcSignature,
classicalAlgId, pqcAlgId);
}
/**
* Verifies a hybrid signature - BOTH signatures must be valid for
verification to succeed.
*
- * @param data the original data that was signed
- * @param hybridSignature the hybrid signature to verify
- * @param classicalPublicKey the classical public key
- * @param classicalSigner the classical signature instance
- * @param pqcPublicKey the PQC public key
- * @param pqcSigner the PQC signature instance
- * @return true if both signatures are valid, false
otherwise
- * @throws InvalidKeyException if a key is invalid
- * @throws SignatureException if verification fails unexpectedly
+ * @param data the original data that was signed
+ * @param hybridSignature the hybrid signature to verify
+ * @param classicalPublicKey the classical public key
+ * @param classicalSigner the classical signature instance
+ * @param pqcPublicKey the PQC public key
+ * @param pqcSigner the PQC signature instance
+ * @return true if both signatures are valid,
false otherwise
+ * @throws InvalidKeyException if a key is invalid
+ * @throws SignatureException if verification fails unexpectedly
+ * @throws IllegalArgumentException if the signature format is malformed
or if a v2 header algorithm ID does not
+ * match the configured algorithm
*/
public static boolean verify(
byte[] data,
@@ -104,6 +147,9 @@ public final class HybridSignature {
// Parse the hybrid signature
HybridSignatureComponents components = parse(hybridSignature);
+ // Validate algorithm IDs if present (v2 format)
+ validateAlgorithmIds(components, classicalSigner, pqcSigner);
+
// Verify classical signature
classicalSigner.initVerify(classicalPublicKey);
classicalSigner.update(data);
@@ -121,15 +167,17 @@ public final class HybridSignature {
/**
* Verifies a hybrid signature and returns detailed results for each
component.
*
- * @param data the original data that was signed
- * @param hybridSignature the hybrid signature to verify
- * @param classicalPublicKey the classical public key
- * @param classicalSigner the classical signature instance
- * @param pqcPublicKey the PQC public key
- * @param pqcSigner the PQC signature instance
- * @return verification result with details
- * @throws InvalidKeyException if a key is invalid
- * @throws SignatureException if verification fails unexpectedly
+ * @param data the original data that was signed
+ * @param hybridSignature the hybrid signature to verify
+ * @param classicalPublicKey the classical public key
+ * @param classicalSigner the classical signature instance
+ * @param pqcPublicKey the PQC public key
+ * @param pqcSigner the PQC signature instance
+ * @return verification result with details
+ * @throws InvalidKeyException if a key is invalid
+ * @throws SignatureException if verification fails unexpectedly
+ * @throws IllegalArgumentException if the signature format is malformed
or if a v2 header algorithm ID does not
+ * match the configured algorithm
*/
public static HybridVerificationResult verifyDetailed(
byte[] data,
@@ -147,6 +195,9 @@ public final class HybridSignature {
HybridSignatureComponents components = parse(hybridSignature);
+ // Validate algorithm IDs if present (v2 format)
+ validateAlgorithmIds(components, classicalSigner, pqcSigner);
+
// Verify classical signature
classicalSigner.initVerify(classicalPublicKey);
classicalSigner.update(data);
@@ -161,7 +212,32 @@ public final class HybridSignature {
}
/**
- * Parses a hybrid signature into its component parts.
+ * Validates that the algorithm IDs embedded in a v2 wire format match the
algorithms configured in the Signature
+ * instances. Skips validation for v1 payloads (null IDs) and for UNKNOWN
algorithm IDs (the sender may not have
+ * written a known ID).
+ */
+ private static void validateAlgorithmIds(
+ HybridSignatureComponents components, Signature classicalSigner,
Signature pqcSigner) {
+ if (components.classicalAlgorithmId() != null &&
components.classicalAlgorithmId() != PQCAlgorithmId.UNKNOWN) {
+ PQCAlgorithmId expected =
PQCAlgorithmId.fromJcaName(classicalSigner.getAlgorithm());
+ if (expected != PQCAlgorithmId.UNKNOWN && expected !=
components.classicalAlgorithmId()) {
+ throw new IllegalArgumentException(
+ "Header algorithm ID mismatch: expected " + expected +
" but found "
+ +
components.classicalAlgorithmId());
+ }
+ }
+ if (components.pqcAlgorithmId() != null && components.pqcAlgorithmId()
!= PQCAlgorithmId.UNKNOWN) {
+ PQCAlgorithmId expected =
PQCAlgorithmId.fromJcaName(pqcSigner.getAlgorithm());
+ if (expected != PQCAlgorithmId.UNKNOWN && expected !=
components.pqcAlgorithmId()) {
+ throw new IllegalArgumentException(
+ "Header algorithm ID mismatch: expected " + expected +
" but found " + components.pqcAlgorithmId());
+ }
+ }
+ }
+
+ /**
+ * Parses a hybrid signature into its component parts. Auto-detects the
wire format version by checking the first
+ * two bytes for the magic sequence {@code 0x50 0x51}: v2 when found, v1
(legacy) otherwise.
*
* @param hybridSignature the hybrid signature to parse
* @return the parsed components
@@ -172,48 +248,159 @@ public final class HybridSignature {
throw new IllegalArgumentException("Invalid hybrid signature: too
short");
}
+ // Auto-detect v2 by checking the magic bytes
+ if (hybridSignature[0] == MAGIC_BYTE_1 && hybridSignature[1] ==
MAGIC_BYTE_2) {
+ return parseV2(hybridSignature);
+ }
+
+ return parseV1(hybridSignature);
+ }
+
+ /**
+ * Parses a v1 (legacy) hybrid signature.
+ * <p>
+ * Layout: {@code [4 bytes: classical sig length][classical sig][pqc sig]}
+ */
+ private static HybridSignatureComponents parseV1(byte[] hybridSignature) {
ByteBuffer buffer = ByteBuffer.wrap(hybridSignature);
- // Read classical signature length
int classicalLength = buffer.getInt();
if (classicalLength <= 0 || classicalLength > hybridSignature.length -
4) {
throw new IllegalArgumentException("Invalid hybrid signature:
invalid classical signature length");
}
+ byte[] classicalSignature = new byte[classicalLength];
+ buffer.get(classicalSignature);
+
+ int pqcLength = buffer.remaining();
+ if (pqcLength <= 0) {
+ throw new IllegalArgumentException("Invalid hybrid signature:
missing PQC signature");
+ }
+ byte[] pqcSignature = new byte[pqcLength];
+ buffer.get(pqcSignature);
+
+ return new HybridSignatureComponents(classicalSignature, pqcSignature,
null, null, 1);
+ }
+
+ /**
+ * Parses a v2 hybrid signature.
+ * <p>
+ * Layout:
+ *
+ * <pre>
+ * [2 bytes: magic][1 byte: version][1 byte: format type]
+ * [2 bytes: classical algorithm ID][2 bytes: PQC algorithm ID]
+ * [4 bytes: classical sig length][N bytes: classical sig][M bytes: PQC
sig]
+ * </pre>
+ */
+ private static HybridSignatureComponents parseV2(byte[] hybridSignature) {
+ if (hybridSignature.length < V2_HEADER_SIZE + 2) {
+ throw new IllegalArgumentException("Invalid v2 hybrid signature:
too short");
+ }
+
+ ByteBuffer buffer = ByteBuffer.wrap(hybridSignature);
+
+ // Skip magic (2 bytes)
+ buffer.get(); // 0x50
+ buffer.get(); // 0x51
+
+ byte version = buffer.get();
+ if (version != VERSION_V2) {
+ throw new IllegalArgumentException("Invalid v2 hybrid signature:
unsupported version " + version);
+ }
+
+ byte formatType = buffer.get();
+ if (formatType != FORMAT_HYBRID_SIGNATURE) {
+ throw new IllegalArgumentException("Invalid v2 hybrid signature:
unexpected format type " + formatType);
+ }
+
+ // Read algorithm IDs (16-bit each)
+ int classicalAlgRaw = buffer.getShort() & 0xFFFF;
+ int pqcAlgRaw = buffer.getShort() & 0xFFFF;
+ PQCAlgorithmId classicalAlgId = PQCAlgorithmId.fromId(classicalAlgRaw);
+ PQCAlgorithmId pqcAlgId = PQCAlgorithmId.fromId(pqcAlgRaw);
+
// Read classical signature
+ int classicalLength = buffer.getInt();
+ int remaining = buffer.remaining();
+ if (classicalLength <= 0 || classicalLength > remaining) {
+ throw new IllegalArgumentException("Invalid v2 hybrid signature:
invalid classical signature length");
+ }
byte[] classicalSignature = new byte[classicalLength];
buffer.get(classicalSignature);
// Read PQC signature (remaining bytes)
int pqcLength = buffer.remaining();
if (pqcLength <= 0) {
- throw new IllegalArgumentException("Invalid hybrid signature:
missing PQC signature");
+ throw new IllegalArgumentException("Invalid v2 hybrid signature:
missing PQC signature");
}
byte[] pqcSignature = new byte[pqcLength];
buffer.get(pqcSignature);
- return new HybridSignatureComponents(classicalSignature, pqcSignature);
+ return new HybridSignatureComponents(classicalSignature, pqcSignature,
classicalAlgId, pqcAlgId, 2);
}
/**
- * Combines classical and PQC signatures into a hybrid signature.
+ * Combines classical and PQC signatures into a v2 wire format hybrid
signature embedding the given algorithm
+ * identifiers.
*
* @param classicalSignature the classical signature bytes
* @param pqcSignature the PQC signature bytes
- * @return the combined hybrid signature
+ * @param classicalAlgId the classical algorithm identifier (use
{@link PQCAlgorithmId#UNKNOWN} if not known)
+ * @param pqcAlgId the PQC algorithm identifier (use {@link
PQCAlgorithmId#UNKNOWN} if not known)
+ * @return the combined v2 hybrid signature
*/
- public static byte[] combineSignatures(byte[] classicalSignature, byte[]
pqcSignature) {
- ByteBuffer buffer = ByteBuffer.allocate(4 + classicalSignature.length
+ pqcSignature.length);
+ public static byte[] combineSignatures(
+ byte[] classicalSignature, byte[] pqcSignature,
+ PQCAlgorithmId classicalAlgId, PQCAlgorithmId pqcAlgId) {
+ int totalSize = V2_HEADER_SIZE + classicalSignature.length +
pqcSignature.length;
+ ByteBuffer buffer = ByteBuffer.allocate(totalSize);
+ buffer.put(MAGIC_BYTE_1);
+ buffer.put(MAGIC_BYTE_2);
+ buffer.put(VERSION_V2);
+ buffer.put(FORMAT_HYBRID_SIGNATURE);
+ buffer.putShort((short) classicalAlgId.getId());
+ buffer.putShort((short) pqcAlgId.getId());
buffer.putInt(classicalSignature.length);
buffer.put(classicalSignature);
buffer.put(pqcSignature);
return buffer.array();
}
+ /**
+ * Combines classical and PQC signatures into a v2 wire format hybrid
signature without algorithm identifiers.
+ * Equivalent to calling {@link #combineSignatures(byte[], byte[],
PQCAlgorithmId, PQCAlgorithmId)} with
+ * {@link PQCAlgorithmId#UNKNOWN} for both algorithm IDs.
+ *
+ * @param classicalSignature the classical signature bytes
+ * @param pqcSignature the PQC signature bytes
+ * @return the combined v2 hybrid signature
+ */
+ public static byte[] combineSignatures(byte[] classicalSignature, byte[]
pqcSignature) {
+ return combineSignatures(classicalSignature, pqcSignature,
PQCAlgorithmId.UNKNOWN, PQCAlgorithmId.UNKNOWN);
+ }
+
/**
* Record holding the parsed components of a hybrid signature.
+ * <p>
+ * <strong>Warning:</strong> The algorithm IDs in the header are
informational metadata written by the sender and
+ * are <em>not</em> authenticated by any signature or MAC. Applications
must not use these IDs to select which key
+ * or algorithm to use for cryptographic operations; always use the
algorithm configured by the operator.
+ *
+ * @param classicalSignature the raw classical signature bytes
+ * @param pqcSignature the raw PQC signature bytes
+ * @param classicalAlgorithmId the classical algorithm identifier from the
wire format header, or {@code null} for
+ * v1 payloads
+ * @param pqcAlgorithmId the PQC algorithm identifier from the wire
format header, or {@code null} for v1
+ * payloads
+ * @param version the wire format version: {@code 1} for
legacy v1, {@code 2} for v2
*/
- public record HybridSignatureComponents(byte[] classicalSignature, byte[]
pqcSignature) {
+ public record HybridSignatureComponents(
+ byte[] classicalSignature,
+ byte[] pqcSignature,
+ PQCAlgorithmId classicalAlgorithmId,
+ PQCAlgorithmId pqcAlgorithmId,
+ int version) {
}
/**
diff --git
a/components/camel-pqc/src/test/java/org/apache/camel/component/pqc/crypto/hybrid/HybridKEMTest.java
b/components/camel-pqc/src/test/java/org/apache/camel/component/pqc/crypto/hybrid/HybridKEMTest.java
index f895a35dbfdd..380936bccb5b 100644
---
a/components/camel-pqc/src/test/java/org/apache/camel/component/pqc/crypto/hybrid/HybridKEMTest.java
+++
b/components/camel-pqc/src/test/java/org/apache/camel/component/pqc/crypto/hybrid/HybridKEMTest.java
@@ -16,6 +16,7 @@
*/
package org.apache.camel.component.pqc.crypto.hybrid;
+import java.nio.ByteBuffer;
import java.security.*;
import java.security.spec.ECGenParameterSpec;
@@ -23,6 +24,7 @@ import javax.crypto.KeyAgreement;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
+import org.apache.camel.component.pqc.PQCAlgorithmId;
import org.bouncycastle.jcajce.spec.MLKEMParameterSpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider;
@@ -90,6 +92,63 @@ class HybridKEMTest {
assertArrayEquals(encapResult.sharedSecret().getEncoded(),
extractedSecret.getEncoded());
}
+ @Test
+ void testEncapsulateProducesV2WireFormat() throws Exception {
+ // Generate X25519 key pair
+ KeyPairGenerator x25519Kpg = KeyPairGenerator.getInstance("X25519",
"BC");
+ KeyPair x25519KeyPair = x25519Kpg.generateKeyPair();
+
+ // Generate ML-KEM key pair
+ KeyPairGenerator mlkemKpg = KeyPairGenerator.getInstance("ML-KEM",
"BC");
+ mlkemKpg.initialize(MLKEMParameterSpec.ml_kem_768, new SecureRandom());
+ KeyPair mlkemKeyPair = mlkemKpg.generateKeyPair();
+
+ KeyAgreement senderKA = KeyAgreement.getInstance("X25519", "BC");
+ KeyGenerator senderKg = KeyGenerator.getInstance("ML-KEM", "BC");
+
+ HybridKEM.HybridEncapsulationResult result = HybridKEM.encapsulate(
+ x25519KeyPair.getPublic(),
+ mlkemKeyPair.getPublic(),
+ senderKA,
+ senderKg,
+ "AES",
+ 256,
+ "HKDF-SHA256");
+
+ byte[] encapsulation = result.encapsulation();
+
+ // Check magic bytes
+ assertEquals(HybridKEM.MAGIC_BYTE_1, encapsulation[0]);
+ assertEquals(HybridKEM.MAGIC_BYTE_2, encapsulation[1]);
+ assertEquals(HybridKEM.VERSION_V2, encapsulation[2]);
+ assertEquals(HybridKEM.FORMAT_HYBRID_KEM, encapsulation[3]);
+
+ // Parse and verify algorithm IDs are populated
+ HybridKEM.HybridEncapsulationComponents components =
HybridKEM.parse(encapsulation);
+ assertEquals(2, components.version());
+ assertEquals(PQCAlgorithmId.X25519, components.classicalAlgorithmId());
+ assertEquals(PQCAlgorithmId.ML_KEM, components.pqcAlgorithmId());
+ }
+
+ @Test
+ void testParseV1BackwardCompatibility() {
+ // Build a hand-crafted v1 payload (no magic bytes)
+ byte[] classicalEncap = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
+ byte[] pqcEncap = new byte[] { 10, 20, 30, 40, 50, 60, 70, 80, 90 };
+ ByteBuffer v1 = ByteBuffer.allocate(4 + classicalEncap.length +
pqcEncap.length);
+ v1.putInt(classicalEncap.length);
+ v1.put(classicalEncap);
+ v1.put(pqcEncap);
+
+ HybridKEM.HybridEncapsulationComponents components =
HybridKEM.parse(v1.array());
+
+ assertEquals(1, components.version());
+ assertNull(components.classicalAlgorithmId(), "v1 payloads carry no
algorithm IDs");
+ assertNull(components.pqcAlgorithmId(), "v1 payloads carry no
algorithm IDs");
+ assertArrayEquals(classicalEncap, components.classicalEncapsulation());
+ assertArrayEquals(pqcEncap, components.pqcEncapsulation());
+ }
+
@Test
void testEncapsulateAndExtractWithECDHAndMLKEM() throws Exception {
// Generate ECDH P-256 key pair (recipient)
@@ -143,10 +202,12 @@ class HybridKEMTest {
byte[] combined = HybridKEM.combineEncapsulations(classicalEncap,
pqcEncap);
+ // combineEncapsulations now produces v2 format
HybridKEM.HybridEncapsulationComponents components =
HybridKEM.parse(combined);
assertArrayEquals(classicalEncap, components.classicalEncapsulation());
assertArrayEquals(pqcEncap, components.pqcEncapsulation());
+ assertEquals(2, components.version());
}
@Test
@@ -186,4 +247,173 @@ class HybridKEMTest {
assertEquals(32, result.sharedSecret().getEncoded().length); //
256 bits = 32 bytes
}
}
+
+ @Test
+ void testMalformedV2Input_headerOnly() {
+ // Magic bytes present but shorter than V2_HEADER_SIZE + 2
+ byte[] malformed = new byte[] {
+ HybridKEM.MAGIC_BYTE_1, HybridKEM.MAGIC_BYTE_2,
HybridKEM.VERSION_V2,
+ HybridKEM.FORMAT_HYBRID_KEM, 0x00, 0x00 };
+ assertThrows(IllegalArgumentException.class, () ->
HybridKEM.parse(malformed));
+ }
+
+ @Test
+ void testMalformedV2Input_classicalLengthTooLarge() {
+ // Build a syntactically valid v2 header but set classicalLength
larger than remaining bytes
+ ByteBuffer buf = ByteBuffer.allocate(HybridKEM.V2_HEADER_SIZE + 4);
+ buf.put(HybridKEM.MAGIC_BYTE_1);
+ buf.put(HybridKEM.MAGIC_BYTE_2);
+ buf.put(HybridKEM.VERSION_V2);
+ buf.put(HybridKEM.FORMAT_HYBRID_KEM);
+ buf.putShort((short) PQCAlgorithmId.X25519.getId());
+ buf.putShort((short) PQCAlgorithmId.ML_KEM.getId());
+ buf.putInt(9999); // classicalLength far larger than 4 remaining bytes
+ buf.put(new byte[] { 1, 2, 3, 4 });
+ assertThrows(IllegalArgumentException.class, () ->
HybridKEM.parse(buf.array()));
+ }
+
+ @Test
+ void testMalformedV2Input_unknownVersion() {
+ ByteBuffer buf = ByteBuffer.allocate(HybridKEM.V2_HEADER_SIZE + 4);
+ buf.put(HybridKEM.MAGIC_BYTE_1);
+ buf.put(HybridKEM.MAGIC_BYTE_2);
+ buf.put((byte) 0x99); // unknown version
+ buf.put(HybridKEM.FORMAT_HYBRID_KEM);
+ buf.putShort((short) 0);
+ buf.putShort((short) 0);
+ buf.putInt(1);
+ buf.put(new byte[] { 1, 2, 3, 4 });
+ assertThrows(IllegalArgumentException.class, () ->
HybridKEM.parse(buf.array()));
+ }
+
+ @Test
+ void testMalformedV2Input_wrongFormatType() {
+ ByteBuffer buf = ByteBuffer.allocate(HybridKEM.V2_HEADER_SIZE + 4);
+ buf.put(HybridKEM.MAGIC_BYTE_1);
+ buf.put(HybridKEM.MAGIC_BYTE_2);
+ buf.put(HybridKEM.VERSION_V2);
+ buf.put((byte) 0x01); // signature format type, not KEM
+ buf.putShort((short) 0);
+ buf.putShort((short) 0);
+ buf.putInt(1);
+ buf.put(new byte[] { 1, 2, 3, 4 });
+ assertThrows(IllegalArgumentException.class, () ->
HybridKEM.parse(buf.array()));
+ }
+
+ @Test
+ void testMalformedV2Input_emptyPqcPart() {
+ // Build a valid v2 header where classicalLength equals all remaining
bytes, leaving 0 for PQC
+ byte[] classical = new byte[] { 1, 2, 3, 4 };
+ ByteBuffer buf = ByteBuffer.allocate(HybridKEM.V2_HEADER_SIZE +
classical.length);
+ buf.put(HybridKEM.MAGIC_BYTE_1);
+ buf.put(HybridKEM.MAGIC_BYTE_2);
+ buf.put(HybridKEM.VERSION_V2);
+ buf.put(HybridKEM.FORMAT_HYBRID_KEM);
+ buf.putShort((short) PQCAlgorithmId.X25519.getId());
+ buf.putShort((short) PQCAlgorithmId.ML_KEM.getId());
+ buf.putInt(classical.length); // exactly all remaining bytes
+ buf.put(classical);
+ assertThrows(IllegalArgumentException.class, () ->
HybridKEM.parse(buf.array()));
+ }
+
+ @Test
+ void testV1BlobThroughExtractEndToEnd() throws Exception {
+ // Generate X25519 key pair (recipient)
+ KeyPairGenerator x25519Kpg = KeyPairGenerator.getInstance("X25519",
"BC");
+ KeyPair x25519KeyPair = x25519Kpg.generateKeyPair();
+
+ // Generate ML-KEM key pair (recipient)
+ KeyPairGenerator mlkemKpg = KeyPairGenerator.getInstance("ML-KEM",
"BC");
+ mlkemKpg.initialize(MLKEMParameterSpec.ml_kem_768, new SecureRandom());
+ KeyPair mlkemKeyPair = mlkemKpg.generateKeyPair();
+
+ // Sender side: produce encapsulation in v2 format, then extract the
raw components
+ KeyAgreement senderKA = KeyAgreement.getInstance("X25519", "BC");
+ KeyGenerator senderKg = KeyGenerator.getInstance("ML-KEM", "BC");
+
+ HybridKEM.HybridEncapsulationResult encapResult =
HybridKEM.encapsulate(
+ x25519KeyPair.getPublic(),
+ mlkemKeyPair.getPublic(),
+ senderKA,
+ senderKg,
+ "AES",
+ 256,
+ "HKDF-SHA256");
+
+ // Parse the v2 encapsulation to get the raw classical and PQC parts
+ HybridKEM.HybridEncapsulationComponents v2Components =
HybridKEM.parse(encapResult.encapsulation());
+
+ // Manually re-assemble as v1 format: [4 bytes: classical
len][classical][pqc]
+ byte[] classicalEncap = v2Components.classicalEncapsulation();
+ byte[] pqcEncap = v2Components.pqcEncapsulation();
+ ByteBuffer v1 = ByteBuffer.allocate(4 + classicalEncap.length +
pqcEncap.length);
+ v1.putInt(classicalEncap.length);
+ v1.put(classicalEncap);
+ v1.put(pqcEncap);
+
+ // Recipient side: extract from v1 blob
+ KeyAgreement recipientKA = KeyAgreement.getInstance("X25519", "BC");
+ KeyGenerator recipientKg = KeyGenerator.getInstance("ML-KEM", "BC");
+
+ SecretKey extractedSecret = HybridKEM.extract(
+ v1.array(),
+ x25519KeyPair.getPrivate(),
+ mlkemKeyPair.getPrivate(),
+ recipientKA,
+ recipientKg,
+ "AES",
+ 256,
+ "HKDF-SHA256");
+
+ assertNotNull(extractedSecret);
+ // The secret extracted from v1 must match the original v2
encapsulation secret
+ assertArrayEquals(encapResult.sharedSecret().getEncoded(),
extractedSecret.getEncoded());
+ }
+
+ @Test
+ void testAlgorithmIdMismatchRejected() throws Exception {
+ // Generate X25519 key pair (recipient)
+ KeyPairGenerator x25519Kpg = KeyPairGenerator.getInstance("X25519",
"BC");
+ KeyPair x25519KeyPair = x25519Kpg.generateKeyPair();
+
+ // Generate ML-KEM key pair (recipient)
+ KeyPairGenerator mlkemKpg = KeyPairGenerator.getInstance("ML-KEM",
"BC");
+ mlkemKpg.initialize(MLKEMParameterSpec.ml_kem_768, new SecureRandom());
+ KeyPair mlkemKeyPair = mlkemKpg.generateKeyPair();
+
+ // Sender side: produce encapsulation
+ KeyAgreement senderKA = KeyAgreement.getInstance("X25519", "BC");
+ KeyGenerator senderKg = KeyGenerator.getInstance("ML-KEM", "BC");
+
+ HybridKEM.HybridEncapsulationResult encapResult =
HybridKEM.encapsulate(
+ x25519KeyPair.getPublic(),
+ mlkemKeyPair.getPublic(),
+ senderKA,
+ senderKg,
+ "AES",
+ 256,
+ "HKDF-SHA256");
+
+ byte[] encapsulation = encapResult.encapsulation();
+
+ // Tamper the classical algorithm ID in the header (bytes 4-5) to ECDH
instead of X25519
+ ByteBuffer tampered = ByteBuffer.wrap(encapsulation.clone());
+ tampered.position(4);
+ tampered.putShort((short) PQCAlgorithmId.ECDH.getId());
+
+ // Extract should throw due to algorithm ID mismatch
+ KeyAgreement recipientKA = KeyAgreement.getInstance("X25519", "BC");
+ KeyGenerator recipientKg = KeyGenerator.getInstance("ML-KEM", "BC");
+ byte[] tamperedArray = tampered.array();
+
+ assertThrows(IllegalArgumentException.class, () -> HybridKEM.extract(
+ tamperedArray,
+ x25519KeyPair.getPrivate(),
+ mlkemKeyPair.getPrivate(),
+ recipientKA,
+ recipientKg,
+ "AES",
+ 256,
+ "HKDF-SHA256"));
+ }
}
diff --git
a/components/camel-pqc/src/test/java/org/apache/camel/component/pqc/crypto/hybrid/HybridSignatureTest.java
b/components/camel-pqc/src/test/java/org/apache/camel/component/pqc/crypto/hybrid/HybridSignatureTest.java
index ce5914f253fc..688c951c0c7b 100644
---
a/components/camel-pqc/src/test/java/org/apache/camel/component/pqc/crypto/hybrid/HybridSignatureTest.java
+++
b/components/camel-pqc/src/test/java/org/apache/camel/component/pqc/crypto/hybrid/HybridSignatureTest.java
@@ -16,9 +16,11 @@
*/
package org.apache.camel.component.pqc.crypto.hybrid;
+import java.nio.ByteBuffer;
import java.security.*;
import java.security.spec.ECGenParameterSpec;
+import org.apache.camel.component.pqc.PQCAlgorithmId;
import org.bouncycastle.jcajce.spec.MLDSAParameterSpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider;
@@ -77,6 +79,58 @@ class HybridSignatureTest {
assertTrue(valid);
}
+ @Test
+ void testSignProducesV2WireFormat() throws Exception {
+ // Generate ECDSA key pair
+ KeyPairGenerator ecKpg = KeyPairGenerator.getInstance("EC", "BC");
+ ecKpg.initialize(new ECGenParameterSpec("secp256r1"), new
SecureRandom());
+ KeyPair ecKeyPair = ecKpg.generateKeyPair();
+ Signature ecSigner = Signature.getInstance("SHA256withECDSA", "BC");
+
+ // Generate ML-DSA key pair
+ KeyPairGenerator mldsaKpg = KeyPairGenerator.getInstance("ML-DSA",
"BC");
+ mldsaKpg.initialize(MLDSAParameterSpec.ml_dsa_65, new SecureRandom());
+ KeyPair mldsaKeyPair = mldsaKpg.generateKeyPair();
+ Signature mldsaSigner = Signature.getInstance("ML-DSA", "BC");
+
+ byte[] data = "v2 format test".getBytes();
+ byte[] hybridSig = HybridSignature.sign(
+ data,
+ ecKeyPair.getPrivate(), ecSigner,
+ mldsaKeyPair.getPrivate(), mldsaSigner);
+
+ // Check magic bytes
+ assertEquals(HybridSignature.MAGIC_BYTE_1, hybridSig[0]);
+ assertEquals(HybridSignature.MAGIC_BYTE_2, hybridSig[1]);
+ assertEquals(HybridSignature.VERSION_V2, hybridSig[2]);
+ assertEquals(HybridSignature.FORMAT_HYBRID_SIGNATURE, hybridSig[3]);
+
+ // Parse and verify algorithm IDs are populated
+ HybridSignature.HybridSignatureComponents components =
HybridSignature.parse(hybridSig);
+ assertEquals(2, components.version());
+ assertEquals(PQCAlgorithmId.SHA256_WITH_ECDSA,
components.classicalAlgorithmId());
+ assertEquals(PQCAlgorithmId.ML_DSA, components.pqcAlgorithmId());
+ }
+
+ @Test
+ void testParseV1BackwardCompatibility() {
+ // Build a hand-crafted v1 payload (no magic bytes)
+ byte[] classicalSig = new byte[] { 1, 2, 3, 4, 5 };
+ byte[] pqcSig = new byte[] { 10, 20, 30, 40, 50, 60 };
+ ByteBuffer v1 = ByteBuffer.allocate(4 + classicalSig.length +
pqcSig.length);
+ v1.putInt(classicalSig.length);
+ v1.put(classicalSig);
+ v1.put(pqcSig);
+
+ HybridSignature.HybridSignatureComponents components =
HybridSignature.parse(v1.array());
+
+ assertEquals(1, components.version());
+ assertNull(components.classicalAlgorithmId(), "v1 payloads carry no
algorithm IDs");
+ assertNull(components.pqcAlgorithmId(), "v1 payloads carry no
algorithm IDs");
+ assertArrayEquals(classicalSig, components.classicalSignature());
+ assertArrayEquals(pqcSig, components.pqcSignature());
+ }
+
@Test
void testVerifyFailsWithWrongData() throws Exception {
// Generate key pairs
@@ -114,16 +168,18 @@ class HybridSignatureTest {
@Test
void testParseHybridSignature() throws Exception {
- // Create a simple hybrid signature manually
+ // Create a simple hybrid signature manually using the public API
byte[] classicalSig = new byte[] { 1, 2, 3, 4, 5 };
byte[] pqcSig = new byte[] { 10, 20, 30, 40, 50, 60 };
byte[] combined = HybridSignature.combineSignatures(classicalSig,
pqcSig);
+ // combineSignatures now produces v2 format
HybridSignature.HybridSignatureComponents components =
HybridSignature.parse(combined);
assertArrayEquals(classicalSig, components.classicalSignature());
assertArrayEquals(pqcSig, components.pqcSignature());
+ assertEquals(2, components.version());
}
@Test
@@ -164,8 +220,178 @@ class HybridSignatureTest {
@Test
void testInvalidSignatureFormat() {
- byte[] invalidSig = new byte[] { 0, 0, 0, 0 }; // Length 0 for
classical sig
+ byte[] invalidSig = new byte[] { 0, 0, 0, 0 }; // too short, not v2
magic
assertThrows(IllegalArgumentException.class, () ->
HybridSignature.parse(invalidSig));
}
+
+ @Test
+ void testMalformedV2Input_unknownVersion() {
+ ByteBuffer buf = ByteBuffer.allocate(HybridSignature.V2_HEADER_SIZE +
4);
+ buf.put(HybridSignature.MAGIC_BYTE_1);
+ buf.put(HybridSignature.MAGIC_BYTE_2);
+ buf.put((byte) 0x99); // unknown version
+ buf.put(HybridSignature.FORMAT_HYBRID_SIGNATURE);
+ buf.putShort((short) 0);
+ buf.putShort((short) 0);
+ buf.putInt(1);
+ buf.put(new byte[] { 1, 2, 3, 4 });
+ assertThrows(IllegalArgumentException.class, () ->
HybridSignature.parse(buf.array()));
+ }
+
+ @Test
+ void testMalformedV2Input_wrongFormatType() {
+ ByteBuffer buf = ByteBuffer.allocate(HybridSignature.V2_HEADER_SIZE +
4);
+ buf.put(HybridSignature.MAGIC_BYTE_1);
+ buf.put(HybridSignature.MAGIC_BYTE_2);
+ buf.put(HybridSignature.VERSION_V2);
+ buf.put((byte) 0x02); // KEM format type, not signature
+ buf.putShort((short) 0);
+ buf.putShort((short) 0);
+ buf.putInt(1);
+ buf.put(new byte[] { 1, 2, 3, 4 });
+ assertThrows(IllegalArgumentException.class, () ->
HybridSignature.parse(buf.array()));
+ }
+
+ @Test
+ void testMalformedV2Input_classicalLengthTooLarge() {
+ ByteBuffer buf = ByteBuffer.allocate(HybridSignature.V2_HEADER_SIZE +
4);
+ buf.put(HybridSignature.MAGIC_BYTE_1);
+ buf.put(HybridSignature.MAGIC_BYTE_2);
+ buf.put(HybridSignature.VERSION_V2);
+ buf.put(HybridSignature.FORMAT_HYBRID_SIGNATURE);
+ buf.putShort((short) PQCAlgorithmId.SHA256_WITH_ECDSA.getId());
+ buf.putShort((short) PQCAlgorithmId.ML_DSA.getId());
+ buf.putInt(Integer.MAX_VALUE); // classicalLength absurdly large
+ buf.put(new byte[] { 1, 2, 3, 4 });
+ assertThrows(IllegalArgumentException.class, () ->
HybridSignature.parse(buf.array()));
+ }
+
+ @Test
+ void testV1BlobThroughVerifyEndToEnd() throws Exception {
+ // Generate ECDSA key pair
+ KeyPairGenerator ecKpg = KeyPairGenerator.getInstance("EC", "BC");
+ ecKpg.initialize(new ECGenParameterSpec("secp256r1"), new
SecureRandom());
+ KeyPair ecKeyPair = ecKpg.generateKeyPair();
+
+ // Generate ML-DSA key pair
+ KeyPairGenerator mldsaKpg = KeyPairGenerator.getInstance("ML-DSA",
"BC");
+ mldsaKpg.initialize(MLDSAParameterSpec.ml_dsa_65, new SecureRandom());
+ KeyPair mldsaKeyPair = mldsaKpg.generateKeyPair();
+
+ byte[] data = "v1 end-to-end test".getBytes();
+
+ // Sign with both algorithms individually to get the raw signatures
+ Signature ecSign = Signature.getInstance("SHA256withECDSA", "BC");
+ ecSign.initSign(ecKeyPair.getPrivate());
+ ecSign.update(data);
+ byte[] classicalSig = ecSign.sign();
+
+ Signature pqcSign = Signature.getInstance("ML-DSA", "BC");
+ pqcSign.initSign(mldsaKeyPair.getPrivate());
+ pqcSign.update(data);
+ byte[] pqcSig = pqcSign.sign();
+
+ // Build a v1-format blob: [4 bytes: classical len][classical sig][pqc
sig]
+ ByteBuffer v1 = ByteBuffer.allocate(4 + classicalSig.length +
pqcSig.length);
+ v1.putInt(classicalSig.length);
+ v1.put(classicalSig);
+ v1.put(pqcSig);
+
+ // Verify via HybridSignature.verify()
+ Signature ecVerifier = Signature.getInstance("SHA256withECDSA", "BC");
+ Signature mldsaVerifier = Signature.getInstance("ML-DSA", "BC");
+
+ boolean valid = HybridSignature.verify(
+ data,
+ v1.array(),
+ ecKeyPair.getPublic(), ecVerifier,
+ mldsaKeyPair.getPublic(), mldsaVerifier);
+
+ assertTrue(valid);
+ }
+
+ @Test
+ void testValidClassicalHalfGarbagePqcHalf() throws Exception {
+ // Generate ECDSA key pair
+ KeyPairGenerator ecKpg = KeyPairGenerator.getInstance("EC", "BC");
+ ecKpg.initialize(new ECGenParameterSpec("secp256r1"), new
SecureRandom());
+ KeyPair ecKeyPair = ecKpg.generateKeyPair();
+
+ // Generate ML-DSA key pair
+ KeyPairGenerator mldsaKpg = KeyPairGenerator.getInstance("ML-DSA",
"BC");
+ mldsaKpg.initialize(MLDSAParameterSpec.ml_dsa_65, new SecureRandom());
+ KeyPair mldsaKeyPair = mldsaKpg.generateKeyPair();
+
+ byte[] data = "garbage pqc test".getBytes();
+
+ // Sign to get a valid hybrid signature
+ Signature ecSigner = Signature.getInstance("SHA256withECDSA", "BC");
+ Signature mldsaSigner = Signature.getInstance("ML-DSA", "BC");
+ byte[] hybridSig = HybridSignature.sign(
+ data,
+ ecKeyPair.getPrivate(), ecSigner,
+ mldsaKeyPair.getPrivate(), mldsaSigner);
+
+ // Parse to get components, replace PQC signature with garbage
+ HybridSignature.HybridSignatureComponents components =
HybridSignature.parse(hybridSig);
+ byte[] garbagePqc = new byte[components.pqcSignature().length];
+ new SecureRandom().nextBytes(garbagePqc);
+
+ // Rebuild v2 blob with garbage PQC part
+ byte[] tampered = HybridSignature.combineSignatures(
+ components.classicalSignature(), garbagePqc,
+ components.classicalAlgorithmId(),
components.pqcAlgorithmId());
+
+ // Verify should return false (not throw)
+ Signature ecVerifier = Signature.getInstance("SHA256withECDSA", "BC");
+ Signature mldsaVerifier = Signature.getInstance("ML-DSA", "BC");
+
+ boolean valid = HybridSignature.verify(
+ data,
+ tampered,
+ ecKeyPair.getPublic(), ecVerifier,
+ mldsaKeyPair.getPublic(), mldsaVerifier);
+
+ assertFalse(valid, "Verification should fail when PQC signature is
garbage");
+ }
+
+ @Test
+ void testAlgorithmIdMismatchRejected() throws Exception {
+ // Generate ECDSA key pair
+ KeyPairGenerator ecKpg = KeyPairGenerator.getInstance("EC", "BC");
+ ecKpg.initialize(new ECGenParameterSpec("secp256r1"), new
SecureRandom());
+ KeyPair ecKeyPair = ecKpg.generateKeyPair();
+
+ // Generate ML-DSA key pair
+ KeyPairGenerator mldsaKpg = KeyPairGenerator.getInstance("ML-DSA",
"BC");
+ mldsaKpg.initialize(MLDSAParameterSpec.ml_dsa_65, new SecureRandom());
+ KeyPair mldsaKeyPair = mldsaKpg.generateKeyPair();
+
+ byte[] data = "algorithm mismatch test".getBytes();
+
+ // Sign
+ Signature ecSigner = Signature.getInstance("SHA256withECDSA", "BC");
+ Signature mldsaSigner = Signature.getInstance("ML-DSA", "BC");
+ byte[] hybridSig = HybridSignature.sign(
+ data,
+ ecKeyPair.getPrivate(), ecSigner,
+ mldsaKeyPair.getPrivate(), mldsaSigner);
+
+ // Tamper the classical algorithm ID in the header (bytes 4-5) to
Ed25519 instead of SHA256withECDSA
+ byte[] tampered = hybridSig.clone();
+ ByteBuffer buf = ByteBuffer.wrap(tampered);
+ buf.position(4);
+ buf.putShort((short) PQCAlgorithmId.ED25519.getId());
+
+ // Verify should throw due to algorithm ID mismatch
+ Signature ecVerifier = Signature.getInstance("SHA256withECDSA", "BC");
+ Signature mldsaVerifier = Signature.getInstance("ML-DSA", "BC");
+
+ assertThrows(IllegalArgumentException.class, () ->
HybridSignature.verify(
+ data,
+ tampered,
+ ecKeyPair.getPublic(), ecVerifier,
+ mldsaKeyPair.getPublic(), mldsaVerifier));
+ }
}
diff --git
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index 15dcbfc6d388..6af4daf8000c 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -167,6 +167,26 @@ Bouncy Castle deprecated Classic McEliece, as it is now
believed to be unsafe to
release. The `CMCE` key encapsulation algorithm of the `pqc` component and the
`pqc` data format is deprecated too, and
an endpoint or a data format that uses it logs a WARN at startup. Use `MLKEM`
instead.
+==== camel-pqc - Hybrid wire format v2 is now the default
+
+The hybrid signature and hybrid KEM utilities now produce **wire format v2**
by default.
+`sign()`, `encapsulate()`, and the 2-argument `combineSignatures()` /
`combineEncapsulations()` overloads all emit v2
+output. A 4.24 writer paired with a pre-4.24 reader will fail with "invalid
classical length" because the reader does
+not recognize the v2 magic header. Upgrade the readers before the writers:
bring all consumers to 4.24 first, then
+upgrade the producers.
+
+The following `PQCAlgorithmId` constants, originally shipped in 4.19.0, have
been removed because the algorithms they
+referred to were renamed or dropped upstream:
+
+* `DILITHIUM` (was `0x0206`)
+* `SPHINCSPLUS` (was `0x0208`)
+* `PICNIC` (was `0x0209`)
+* `KYBER` (was `0x040A`)
+
+The `HybridSignatureComponents` and `HybridEncapsulationComponents` record
constructors changed from 2 arguments
+(`classicalBytes`, `pqcBytes`) to 5 arguments (`classicalBytes`, `pqcBytes`,
`classicalAlgorithmId`, `pqcAlgorithmId`,
+`version`). Code that constructs these records directly must be updated.
+
=== camel-observability-services - promoted to Stable
The `camel-observability-services` component has been promoted from _Preview_
to _Stable_ support level.