This is an automated email from the ASF dual-hosted git repository.
apupier 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 3c82f51338d3 CAMEL-27293: camel-pqc - SABER KEM operations share one
Bouncy Castle engine, serialize them JVM-wide
3c82f51338d3 is described below
commit 3c82f51338d3298d7db32b1d401e894f4d227fe6
Author: Aurélien Pupier <[email protected]>
AuthorDate: Fri Nov 20 11:22:15 2026 +0100
CAMEL-27293: camel-pqc - SABER KEM operations share one Bouncy Castle
engine, serialize them JVM-wide
Every SABER key of a parameter set points to one static Bouncy Castle
SABERParameters constant, which owns a single SABEREngine whose SHA-3
state is mutated by each encapsulation and decapsulation. The KEM
operations only synchronized on the KeyGenerator they use, and
PQCProducer creates a fresh KeyGenerator per exchange, so concurrent
SABER exchanges ran on different locks and corrupted each other:
"attempt to absorb while squeezing", or an extracted secret that differs
from the encapsulated one (the assertTrue failure of
PQCSABERGenerateEncapsulationAESNoAutowiredTest). The test became flaky
when CAMEL-24290 enabled parallel test classes for camel-pqc.
PQCKemLocks.lockFor() returns one JVM-wide monitor for SABER keys and the
KeyGenerator itself for every other algorithm, and PQCProducer,
PQCDataFormat and HybridKEM use it around their init()/generateKey()
sequences. The other KEM algorithms were checked with concurrent
encapsulation and extraction on separate KeyGenerators and keep their
state in the generator or the key.
Tests hold one exchange between init() and generateKey() and start a
second one on another KeyGenerator, for every KEM algorithm and for the
producer, the data format and the hybrid KEM, so the check does not
depend on thread scheduling. Only SABER fails without the fix.
Co-authored-by: IBM Bob 2.2.1
Signed-off-by: Aurélien Pupier <[email protected]>
---
.../apache/camel/component/pqc/PQCKemLocks.java | 63 +++++++++++
.../apache/camel/component/pqc/PQCProducer.java | 4 +-
.../component/pqc/crypto/hybrid/HybridKEM.java | 5 +-
.../component/pqc/dataformat/PQCDataFormat.java | 5 +-
.../pqc/PQCKemSharedEngineIsolationTest.java | 126 +++++++++++++++++++++
.../hybrid/HybridKEMSharedEngineIsolationTest.java | 109 ++++++++++++++++++
.../PQCDataFormatSharedEngineIsolationTest.java | 121 ++++++++++++++++++++
7 files changed, 427 insertions(+), 6 deletions(-)
diff --git
a/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/PQCKemLocks.java
b/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/PQCKemLocks.java
new file mode 100644
index 000000000000..dc69599bfaeb
--- /dev/null
+++
b/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/PQCKemLocks.java
@@ -0,0 +1,63 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+package org.apache.camel.component.pqc;
+
+import java.security.Key;
+
+import javax.crypto.KeyGenerator;
+
+/**
+ * Chooses the monitor that serializes one KEM {@code init()} / {@code
generateKey()} sequence.
+ * <p>
+ * A KEM {@link KeyGenerator} is not thread-safe, so the sequence normally
holds the monitor of the generator it uses.
+ * That is not enough for SABER: every SABER key of a parameter set points to
one static Bouncy Castle
+ * {@code SABERParameters} constant, which owns a single {@code SABEREngine}
whose SHA-3 state is mutated by every
+ * encapsulation and decapsulation. Two threads using different {@code
KeyGenerator} instances - for example the
+ * generators a producer creates for each exchange - still corrupt each other
("attempt to absorb while squeezing", or a
+ * secret that differs from the one extracted). All SABER operations of this
JVM therefore share one monitor.
+ */
+public final class PQCKemLocks {
+
+ private static final Object SABER_LOCK = new Object();
+
+ private PQCKemLocks() {
+ }
+
+ /**
+ * @param generator the KEM key generator the sequence is going to use
+ * @param key the public key (encapsulate) or private key (extract)
given to the generator
+ * @return the object to synchronize the whole {@code init()} /
{@code generateKey()} sequence on
+ */
+ public static Object lockFor(KeyGenerator generator, Key key) {
+ if (key != null &&
PQCKeyEncapsulationAlgorithms.SABER.getAlgorithm().equals(key.getAlgorithm())) {
+ return SABER_LOCK;
+ }
+ return generator;
+ }
+
+ /**
+ * Whether the Bouncy Castle implementation of the algorithm keeps mutable
state outside the {@code KeyGenerator},
+ * so that {@link #lockFor(KeyGenerator, Key)} has to hand out one monitor
for all generators of the algorithm.
+ * <p>
+ * Only SABER does. The other KEMs were checked with concurrent
encapsulation and extraction on separate generators
+ * and keep their state in the generator or the key. HQC and SmaugT also
hold an engine in their static parameter
+ * constants, but it only contains immutable sizes and tables.
+ */
+ public static boolean
sharesEngineAcrossKeyGenerators(PQCKeyEncapsulationAlgorithms algorithm) {
+ return algorithm == PQCKeyEncapsulationAlgorithms.SABER;
+ }
+}
diff --git
a/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/PQCProducer.java
b/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/PQCProducer.java
index 7f15935f1560..a8859654d67b 100644
---
a/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/PQCProducer.java
+++
b/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/PQCProducer.java
@@ -841,7 +841,7 @@ public class PQCProducer extends DefaultProducer {
KeyGenerator generator = keyGeneratorForExchange();
SecretKeyWithEncapsulation secEnc1;
- synchronized (generator) {
+ synchronized (PQCKemLocks.lockFor(generator, keyPair.getPublic())) {
// initialise for creating an encapsulation and shared secret.
generator.init(
new KEMGenerateSpec(
@@ -873,7 +873,7 @@ public class PQCProducer extends DefaultProducer {
KeyGenerator generator = keyGeneratorForExchange();
SecretKeyWithEncapsulation secEnc2;
- synchronized (generator) {
+ synchronized (PQCKemLocks.lockFor(generator, keyPair.getPrivate())) {
generator.init(
new KEMExtractSpec(
keyPair.getPrivate(), payload.getEncapsulation(),
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 76330529fd82..a2743244f08e 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.PQCKemLocks;
import org.apache.camel.component.pqc.PQCSymmetricAlgorithms;
import org.apache.camel.util.SecureRandomHelper;
import org.bouncycastle.crypto.digests.SHA256Digest;
@@ -107,7 +108,7 @@ public final class HybridKEM {
// Perform PQC KEM encapsulation
SecretKeyWithEncapsulation pqcResult;
- synchronized (pqcKemGenerator) {
+ synchronized (PQCKemLocks.lockFor(pqcKemGenerator, pqcPublicKey)) {
pqcKemGenerator.init(
new KEMGenerateSpec(pqcPublicKey, symmetricAlgorithm,
keyLength),
SecureRandomHelper.getSecureRandom());
@@ -186,7 +187,7 @@ public final class HybridKEM {
// Perform PQC KEM extraction
SecretKeyWithEncapsulation pqcResult;
- synchronized (pqcKemGenerator) {
+ synchronized (PQCKemLocks.lockFor(pqcKemGenerator, pqcPrivateKey)) {
pqcKemGenerator.init(
new KEMExtractSpec(pqcPrivateKey,
components.pqcEncapsulation(), symmetricAlgorithm, keyLength),
SecureRandomHelper.getSecureRandom());
diff --git
a/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/dataformat/PQCDataFormat.java
b/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/dataformat/PQCDataFormat.java
index e0a5a4d482a0..7359e3657e07 100644
---
a/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/dataformat/PQCDataFormat.java
+++
b/components/camel-pqc/src/main/java/org/apache/camel/component/pqc/dataformat/PQCDataFormat.java
@@ -34,6 +34,7 @@ import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.camel.Exchange;
+import org.apache.camel.component.pqc.PQCKemLocks;
import org.apache.camel.component.pqc.PQCKeyEncapsulationAlgorithms;
import org.apache.camel.component.pqc.PQCSymmetricAlgorithms;
import org.apache.camel.spi.BodyType;
@@ -177,7 +178,7 @@ public class PQCDataFormat extends ServiceSupport
implements DataFormat, DataFor
// Generate KEM encapsulation and the fresh shared secret
KeyGenerator kg = getOrCreateKeyGenerator(kemAlg);
SecretKeyWithEncapsulation secretKey;
- synchronized (kg) {
+ synchronized (PQCKemLocks.lockFor(kg, kp.getPublic())) {
kg.init(new KEMGenerateSpec(kp.getPublic(), symAlg,
symmetricKeyLength),
SecureRandomHelper.getSecureRandom());
secretKey = (SecretKeyWithEncapsulation) kg.generateKey();
@@ -239,7 +240,7 @@ public class PQCDataFormat extends ServiceSupport
implements DataFormat, DataFor
// Extract the shared secret from the encapsulation
KeyGenerator kg = getOrCreateKeyGenerator(kemAlg);
SecretKeyWithEncapsulation secretKey;
- synchronized (kg) {
+ synchronized (PQCKemLocks.lockFor(kg, kp.getPrivate())) {
kg.init(new KEMExtractSpec(kp.getPrivate(), encapsulation,
symAlg, symmetricKeyLength),
SecureRandomHelper.getSecureRandom());
secretKey = (SecretKeyWithEncapsulation) kg.generateKey();
diff --git
a/components/camel-pqc/src/test/java/org/apache/camel/component/pqc/PQCKemSharedEngineIsolationTest.java
b/components/camel-pqc/src/test/java/org/apache/camel/component/pqc/PQCKemSharedEngineIsolationTest.java
new file mode 100644
index 000000000000..915a9f26f3aa
--- /dev/null
+++
b/components/camel-pqc/src/test/java/org/apache/camel/component/pqc/PQCKemSharedEngineIsolationTest.java
@@ -0,0 +1,126 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+package org.apache.camel.component.pqc;
+
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.SecureRandom;
+import java.security.Security;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import javax.crypto.KeyGenerator;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.ProducerTemplate;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.bouncycastle.jcajce.SecretKeyWithEncapsulation;
+import org.bouncycastle.jcajce.spec.KEMGenerateSpec;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
+import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * The KEM operations of a Camel producer are serialized on the KeyGenerator
they use, which is enough as long as the
+ * algorithm keeps its state in that generator. Bouncy Castle SABER does not:
all keys of a parameter set share one
+ * engine, so two exchanges using two different KeyGenerators still corrupt
each other.
+ * <p>
+ * The test is deterministic. It holds one exchange between {@code init()} and
{@code generateKey()} of its generator
+ * and starts a second exchange on another generator in the meantime. Whether
the second {@code init()} ran inside that
+ * window does not depend on thread scheduling.
+ */
+class PQCKemSharedEngineIsolationTest {
+
+ private static final long SECONDS = 20;
+
+ @BeforeAll
+ static void startup() {
+ if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
+ Security.addProvider(new BouncyCastleProvider());
+ }
+ if (Security.getProvider(BouncyCastlePQCProvider.PROVIDER_NAME) ==
null) {
+ Security.addProvider(new BouncyCastlePQCProvider());
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(PQCKeyEncapsulationAlgorithms.class)
+ void
overlappingExtractionsOnDifferentKeyGeneratorsEachReturnTheirOwnSecret(PQCKeyEncapsulationAlgorithms
kem)
+ throws Exception {
+ InterleavingProbe probe = new InterleavingProbe();
+ KeyPair keyPair = KeyPairGenerator.getInstance(kem.getAlgorithm(),
kem.getBcProvider()).generateKeyPair();
+
+ try (CamelContext context = new DefaultCamelContext()) {
+ context.getRegistry().bind("kemKeyPair", keyPair);
+ context.getRegistry().bind("firstGenerator",
ProbedKeyGenerator.wrap(newKeyGenerator(kem), probe));
+ context.getRegistry().bind("secondGenerator",
ProbedKeyGenerator.wrap(newKeyGenerator(kem), probe));
+ context.start();
+ ProducerTemplate template = context.createProducerTemplate();
+
+ SecretKeyWithEncapsulation first = encapsulate(kem, keyPair);
+ SecretKeyWithEncapsulation second = encapsulate(kem, keyPair);
+
+ probe.holdNextResult();
+ Future<SecretKeyWithEncapsulation> firstResult
+ = template.asyncRequestBody(extractUri(kem,
"firstGenerator"), first, SecretKeyWithEncapsulation.class);
+ assertThat(probe.awaitHolding(SECONDS, TimeUnit.SECONDS)).isTrue();
+ Future<SecretKeyWithEncapsulation> secondResult
+ = template.asyncRequestBody(extractUri(kem,
"secondGenerator"), second, SecretKeyWithEncapsulation.class);
+
+ assertThat(firstResult.get(SECONDS,
TimeUnit.SECONDS).getEncoded()).isEqualTo(first.getEncoded());
+ assertThat(secondResult.get(SECONDS,
TimeUnit.SECONDS).getEncoded()).isEqualTo(second.getEncoded());
+ if (PQCKemLocks.sharesEngineAcrossKeyGenerators(kem)) {
+ assertThat(probe.interleaved())
+ .as("%s: an init() of another KeyGenerator ran between
init() and generateKey() of an exchange", kem)
+ .isFalse();
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(PQCKeyEncapsulationAlgorithms.class)
+ void
lockIsSharedByKeyGeneratorsOnlyWhenTheEngineIsShared(PQCKeyEncapsulationAlgorithms
kem) throws Exception {
+ KeyPair keyPair = KeyPairGenerator.getInstance(kem.getAlgorithm(),
kem.getBcProvider()).generateKeyPair();
+ KeyGenerator first = newKeyGenerator(kem);
+ KeyGenerator second = newKeyGenerator(kem);
+
+ assertThat(PQCKemLocks.lockFor(first, keyPair.getPublic())).isSameAs(
+ PQCKemLocks.sharesEngineAcrossKeyGenerators(kem)
+ ? PQCKemLocks.lockFor(second, keyPair.getPrivate())
+ : first);
+ }
+
+ private static String extractUri(PQCKeyEncapsulationAlgorithms kem, String
generator) {
+ return "pqc:extract-" + generator +
"?operation=extractSecretKeyEncapsulation&symmetricKeyAlgorithm=AES"
+ + "&keyEncapsulationAlgorithm=" + kem.name() +
"&keyPair=#kemKeyPair&keyGenerator=#" + generator;
+ }
+
+ private static SecretKeyWithEncapsulation
encapsulate(PQCKeyEncapsulationAlgorithms kem, KeyPair keyPair)
+ throws Exception {
+ KeyGenerator kg = newKeyGenerator(kem);
+ kg.init(new KEMGenerateSpec(keyPair.getPublic(), "AES", 256), new
SecureRandom());
+ return (SecretKeyWithEncapsulation) kg.generateKey();
+ }
+
+ private static KeyGenerator newKeyGenerator(PQCKeyEncapsulationAlgorithms
kem) throws Exception {
+ return KeyGenerator.getInstance(kem.getAlgorithm(),
kem.getBcProvider());
+ }
+}
diff --git
a/components/camel-pqc/src/test/java/org/apache/camel/component/pqc/crypto/hybrid/HybridKEMSharedEngineIsolationTest.java
b/components/camel-pqc/src/test/java/org/apache/camel/component/pqc/crypto/hybrid/HybridKEMSharedEngineIsolationTest.java
new file mode 100644
index 000000000000..1691497d0a9d
--- /dev/null
+++
b/components/camel-pqc/src/test/java/org/apache/camel/component/pqc/crypto/hybrid/HybridKEMSharedEngineIsolationTest.java
@@ -0,0 +1,109 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+package org.apache.camel.component.pqc.crypto.hybrid;
+
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.Security;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import javax.crypto.KeyAgreement;
+import javax.crypto.KeyGenerator;
+import javax.crypto.SecretKey;
+
+import org.apache.camel.component.pqc.InterleavingProbe;
+import org.apache.camel.component.pqc.PQCKemLocks;
+import org.apache.camel.component.pqc.PQCKeyEncapsulationAlgorithms;
+import org.apache.camel.component.pqc.ProbedKeyGenerator;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
+import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * Hybrid encapsulations and extractions using two different PQC KeyGenerators
of the same algorithm. For an algorithm
+ * that keeps state outside the KeyGenerator (SABER) one operation must not
run its {@code init()} between the
+ * {@code init()} and the {@code generateKey()} of the other. The first
operation is held between those two calls, so
+ * the outcome does not depend on thread scheduling.
+ */
+class HybridKEMSharedEngineIsolationTest {
+
+ private static final long SECONDS = 20;
+
+ @BeforeAll
+ static void setup() {
+ if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
+ Security.addProvider(new BouncyCastleProvider());
+ }
+ if (Security.getProvider(BouncyCastlePQCProvider.PROVIDER_NAME) ==
null) {
+ Security.addProvider(new BouncyCastlePQCProvider());
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(PQCKeyEncapsulationAlgorithms.class)
+ void
overlappingEncapsulationAndExtractionOnDifferentKeyGeneratorsKeepTheirOwnSecrets(
+ PQCKeyEncapsulationAlgorithms kem)
+ throws Exception {
+ KeyPair classical = KeyPairGenerator.getInstance("X25519",
"BC").generateKeyPair();
+ KeyPair pqc = KeyPairGenerator.getInstance(kem.getAlgorithm(),
kem.getBcProvider()).generateKeyPair();
+ InterleavingProbe probe = new InterleavingProbe();
+
+ HybridKEM.HybridEncapsulationResult other =
HybridKEM.encapsulate(classical.getPublic(), pqc.getPublic(),
+ KeyAgreement.getInstance("X25519", "BC"),
newKeyGenerator(kem), "AES", 256, "HKDF-SHA256");
+
+ probe.holdNextResult();
+ KeyGenerator encapsulationGenerator =
ProbedKeyGenerator.wrap(newKeyGenerator(kem), probe);
+ KeyGenerator extractionGenerator =
ProbedKeyGenerator.wrap(newKeyGenerator(kem), probe);
+ ExecutorService pool = Executors.newFixedThreadPool(2);
+ HybridKEM.HybridEncapsulationResult mine;
+ SecretKey extracted;
+ try {
+ Future<HybridKEM.HybridEncapsulationResult> encapsulated =
pool.submit(
+ () -> HybridKEM.encapsulate(classical.getPublic(),
pqc.getPublic(),
+ KeyAgreement.getInstance("X25519", "BC"),
encapsulationGenerator, "AES", 256, "HKDF-SHA256"));
+ assertThat(probe.awaitHolding(SECONDS, TimeUnit.SECONDS)).isTrue();
+ Future<SecretKey> extraction = pool.submit(
+ () -> HybridKEM.extract(other.encapsulation(),
classical.getPrivate(), pqc.getPrivate(),
+ KeyAgreement.getInstance("X25519", "BC"),
extractionGenerator, "AES", 256, "HKDF-SHA256"));
+ mine = encapsulated.get(SECONDS, TimeUnit.SECONDS);
+ extracted = extraction.get(SECONDS, TimeUnit.SECONDS);
+ } finally {
+ pool.shutdownNow();
+ }
+
+ SecretKey mineExtracted = HybridKEM.extract(mine.encapsulation(),
classical.getPrivate(), pqc.getPrivate(),
+ KeyAgreement.getInstance("X25519", "BC"),
newKeyGenerator(kem), "AES", 256, "HKDF-SHA256");
+
assertThat(mineExtracted.getEncoded()).isEqualTo(mine.sharedSecret().getEncoded());
+
assertThat(extracted.getEncoded()).isEqualTo(other.sharedSecret().getEncoded());
+ if (PQCKemLocks.sharesEngineAcrossKeyGenerators(kem)) {
+ assertThat(probe.interleaved())
+ .as("%s: an init() of another KeyGenerator ran between
init() and generateKey()", kem)
+ .isFalse();
+ }
+ }
+
+ private static KeyGenerator newKeyGenerator(PQCKeyEncapsulationAlgorithms
kem) throws Exception {
+ return KeyGenerator.getInstance(kem.getAlgorithm(),
kem.getBcProvider());
+ }
+}
diff --git
a/components/camel-pqc/src/test/java/org/apache/camel/component/pqc/dataformat/PQCDataFormatSharedEngineIsolationTest.java
b/components/camel-pqc/src/test/java/org/apache/camel/component/pqc/dataformat/PQCDataFormatSharedEngineIsolationTest.java
new file mode 100644
index 000000000000..51fde0d342eb
--- /dev/null
+++
b/components/camel-pqc/src/test/java/org/apache/camel/component/pqc/dataformat/PQCDataFormatSharedEngineIsolationTest.java
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+package org.apache.camel.component.pqc.dataformat;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.Security;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import javax.crypto.KeyGenerator;
+
+import org.apache.camel.component.pqc.InterleavingProbe;
+import org.apache.camel.component.pqc.PQCKemLocks;
+import org.apache.camel.component.pqc.PQCKeyEncapsulationAlgorithms;
+import org.apache.camel.component.pqc.ProbedKeyGenerator;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.support.DefaultExchange;
+import org.bouncycastle.jce.provider.BouncyCastleProvider;
+import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * Two data formats, each with its own KeyGenerator, work on the same KEM
algorithm. For an algorithm that keeps state
+ * outside the KeyGenerator (SABER) one operation must not run its {@code
init()} between the {@code init()} and the
+ * {@code generateKey()} of the other. The first operation is held between
those two calls, so the outcome does not
+ * depend on thread scheduling.
+ */
+class PQCDataFormatSharedEngineIsolationTest {
+
+ private static final long SECONDS = 20;
+
+ @BeforeAll
+ static void startup() {
+ if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
+ Security.addProvider(new BouncyCastleProvider());
+ }
+ if (Security.getProvider(BouncyCastlePQCProvider.PROVIDER_NAME) ==
null) {
+ Security.addProvider(new BouncyCastlePQCProvider());
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(PQCKeyEncapsulationAlgorithms.class)
+ void
overlappingMarshalAndUnmarshalOnDifferentKeyGeneratorsKeepTheirOwnSecrets(PQCKeyEncapsulationAlgorithms
kem)
+ throws Exception {
+ KeyPair keyPair = KeyPairGenerator.getInstance(kem.getAlgorithm(),
kem.getBcProvider()).generateKeyPair();
+ InterleavingProbe probe = new InterleavingProbe();
+ PQCDataFormat marshaller = startedDataFormat(kem, keyPair, probe);
+ PQCDataFormat unmarshaller = startedDataFormat(kem, keyPair, probe);
+ byte[] otherMessage = marshal(startedDataFormat(kem, keyPair, null),
"other");
+
+ probe.holdNextResult();
+ ExecutorService pool = Executors.newFixedThreadPool(2);
+ byte[] mine;
+ String other;
+ try {
+ Future<byte[]> marshalled = pool.submit(() -> marshal(marshaller,
"mine"));
+ assertThat(probe.awaitHolding(SECONDS, TimeUnit.SECONDS)).isTrue();
+ Future<String> unmarshalled = pool.submit(() ->
unmarshal(unmarshaller, otherMessage));
+ mine = marshalled.get(SECONDS, TimeUnit.SECONDS);
+ other = unmarshalled.get(SECONDS, TimeUnit.SECONDS);
+ } finally {
+ pool.shutdownNow();
+ }
+
+ assertThat(unmarshal(unmarshaller, mine)).isEqualTo("mine");
+ assertThat(other).isEqualTo("other");
+ if (PQCKemLocks.sharesEngineAcrossKeyGenerators(kem)) {
+ assertThat(probe.interleaved())
+ .as("%s: an init() of another KeyGenerator ran between
init() and generateKey()", kem)
+ .isFalse();
+ }
+ }
+
+ private static PQCDataFormat
startedDataFormat(PQCKeyEncapsulationAlgorithms kem, KeyPair keyPair,
InterleavingProbe probe)
+ throws Exception {
+ PQCDataFormat dataFormat = new PQCDataFormat(kem.name(), "AES",
keyPair);
+ if (probe != null) {
+ dataFormat.setKeyGenerator(
+
ProbedKeyGenerator.wrap(KeyGenerator.getInstance(kem.getAlgorithm(),
kem.getBcProvider()), probe));
+ }
+ dataFormat.start();
+ return dataFormat;
+ }
+
+ private static byte[] marshal(PQCDataFormat dataFormat, String body)
throws Exception {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ dataFormat.marshal(new DefaultExchange(new DefaultCamelContext()),
body, out);
+ return out.toByteArray();
+ }
+
+ private static String unmarshal(PQCDataFormat dataFormat, byte[] data)
throws Exception {
+ byte[] plaintext = (byte[]) dataFormat.unmarshal(new
DefaultExchange(new DefaultCamelContext()),
+ new ByteArrayInputStream(data));
+ return new String(plaintext, StandardCharsets.UTF_8);
+ }
+}