Skip to content

Commit 0f336b6

Browse files
author
gefeili
committed
Address the code review of the NTRU LPRime, NTRU+ and SMAUG-T KEM support, in three groups.
Three comments asserted things the code did not do. NTRULPRimeParameters.getEncapsulationLength() said it existed so the expression would not be repeated, but the extractor was left open-coding its own copy, leaving the encapsulator and decapsulator reading the size from two independently maintained places; the extractor now delegates, and SNTRUPrimeParameters gains the same accessor with its extractor delegating too, retiring the last open-coded copy in that package. The NTRU+ and SMAUG-T KEM SPI javadoc said a future parameter set with a different session key size would need no change, when the size fed to the validation and the size actually produced come from separate constants - a fixed getSsBytes() against NTRUPlusEngine.SSBytes, a per-set defaultKeySize against the mode-independent SmaugTEngine.CRYPTO_BYTES - so following that invitation would have admitted a no-KDF size the extractor cannot fill; both now say so. And the claim that the engine wanted the fix FrodoKEMEngine had was wrong on this branch, where FrodoKEMEngine still keeps its digest in a field and took the same workaround. The family level KEM services for NTRU+ and SMAUG-T did not bind their family object identifier, so it resolved as a Cipher but not as a KEM while NTRU LPRime in the same commit bound its own; both now go through addKEMAlgorithm. NTRULPRimeKEMSpi is reshaped to abstract plus a nested subclass to match the SNTRU Prime sibling registered beside it, so acting on the per-parameter-set note above them needs no restructuring either side. The spec validation is extended to the KEMs that still lacked it. ML-KEM, HQC, NTRU and SNTRU Prime accepted a KDF-less spec larger than the mechanism produces and then threw ArrayIndexOutOfBoundsException out of encapsulate; each now delegates to KdfUtil.resolveKemSpec, passing its own algorithm name so the existing message text is unchanged. SM9 is left alone: its own KDF produces the secret at the requested size, so it has no fixed session key to bound against. Also record the thread-safety requirements where they will be read rather than only in an SPI comment - SmaugTEngine must stay immutable because one instance is shared process wide, and NTRUPlusKEMExtractor is not safe to share - correct SmaugTEngine's fields being described as static constants when they are per-instance finals, note in CMCEDecapsulatorSpi that its per-call rebuild is for symmetry rather than correctness now that the safe families share, align the SMAUG-T service name in one exception message, and record why compileJava17Java deliberately avoids options.release.
1 parent 5139086 commit 0f336b6

21 files changed

Lines changed: 151 additions & 102 deletions

File tree

‎core/src/main/java/org/bouncycastle/pqc/crypto/ntruplus/NTRUPlusKEMExtractor.java‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,16 @@
22

33
import org.bouncycastle.crypto.EncapsulatedSecretExtractor;
44

5+
/**
6+
* NTRU+ decapsulation.
7+
* <p>
8+
* <b>Not thread safe.</b> The NTRUPlusEngine built here keeps one SHAKE instance in a field, so two
9+
* threads sharing an extractor interleave its absorb and squeeze phases: the secrets they recover do
10+
* not match the sender's, and an IllegalStateException from the digest is also possible. Give each
11+
* thread its own extractor - construction is cheap, roughly a thousandth of a decapsulation. The
12+
* KEM.Decapsulator that javax.crypto.KEM builds does exactly that, since that API requires
13+
* decapsulate to be safe for concurrent use.
14+
*/
515
public class NTRUPlusKEMExtractor
616
implements EncapsulatedSecretExtractor
717
{

‎core/src/main/java/org/bouncycastle/pqc/crypto/ntruprime/NTRULPRimeKEMExtractor.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,6 @@ public byte[] extractSecret(byte[] encapsulation)
182182

183183
public int getEncapsulationLength()
184184
{
185-
return privateKey.getParameters().getRoundedPolynomialBytes() + 128 + 32;
185+
return privateKey.getParameters().getEncapsulationLength();
186186
}
187187
}

‎core/src/main/java/org/bouncycastle/pqc/crypto/ntruprime/SNTRUPrimeKEMExtractor.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,6 @@ public byte[] extractSecret(byte[] encapsulation)
154154

155155
public int getEncapsulationLength()
156156
{
157-
return privateKey.getParameters().getRoundedPolynomialBytes() + 32;
157+
return privateKey.getParameters().getEncapsulationLength();
158158
}
159159
}

‎core/src/main/java/org/bouncycastle/pqc/crypto/ntruprime/SNTRUPrimeParameters.java‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,4 +100,14 @@ public int getSessionKeySize()
100100
{
101101
return sharedKeyBytes * 8;
102102
}
103+
104+
/**
105+
* Return the size in bytes of an encapsulation produced for this parameter set, so that the
106+
* encapsulating side - which holds only a public key and no extractor - reads it from the same
107+
* place SNTRUPrimeKEMExtractor does.
108+
*/
109+
public int getEncapsulationLength()
110+
{
111+
return roundedPolynomialBytes + 32;
112+
}
103113
}

‎core/src/main/java/org/bouncycastle/pqc/crypto/smaugt/SmaugTEngine.java‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,14 @@
88
/**
99
* Reference implementation of SMAUG-T KEM, translated from the SMAUG-T 1.2.0 C
1010
* reference code.
11+
* <p>
12+
* <b>Must remain immutable.</b> SmaugTParameters holds one instance per parameter set for the life
13+
* of the JVM and hands it to every extractor, generator and key pair generator, so this class is
14+
* shared across threads. javax.crypto.KEM requires a Decapsulator to be safe for concurrent use and
15+
* SmaugTKEMExtractor relies on that sharing being safe. Every field here is final and set at
16+
* construction, and every operation allocates its own buffers and digests - adding a scratch buffer
17+
* or a cached digest field would silently corrupt concurrent users rather than fail. If one is ever
18+
* needed, make getEngine() return a new instance instead.
1119
*/
1220
class SmaugTEngine
1321
{

‎core/src/main/java/org/bouncycastle/pqc/crypto/smaugt/SmaugTParameters.java‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,10 @@ int getMode()
6161
return mode;
6262
}
6363

64+
/**
65+
* Return the engine for this parameter set. One instance is shared by every caller for the life
66+
* of the JVM, so SmaugTEngine must stay immutable - see its class javadoc.
67+
*/
6468
SmaugTEngine getEngine()
6569
{
6670
return engine;

‎docs/releasenotes.html‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ <h3>2.1.3 Additional Features and Functionality</h3>
169169
<li>org.bouncycastle.jcajce.provider.util.SecurityExceptions gained an invalidAlgorithmParameterException(String, Throwable) factory, for the same reason as its siblings: java.security.InvalidAlgorithmParameterException only grew a cause-taking constructor in Java 5, so code that has to compile for the legacy Java 4 distributions attaches the cause through initCause instead. Use the factory rather than rolling that call at the throw site.</li>
170170
<li>The BCJSSE provider now treats the ML-KEM based named groups as FIPS approved, and offers the hybrids among them by default. FipsUtils.isFipsNamedGroup answers true for X25519MLKEM768, MLKEM512, MLKEM768 and MLKEM1024 as well as the two SecP hybrids it already accepted - the key establishment in each is ML-KEM (FIPS 203), and in the X25519 hybrid the approved component supplies the shared secret the X25519 half is combined with - so a provider constructed in FIPS mode no longer filters any of them out. NamedGroupInfo's default candidate list, which applies when the jdk.tls.namedGroups property is not set, gains SecP256r1MLKEM768 and SecP384r1MLKEM1024 alongside the X25519MLKEM768 it already carried; they are appended, so the classical groups keep their existing preference and these are additional offers rather than a change of first choice. The pure ML-KEM groups (MLKEM512, MLKEM768, MLKEM1024) are deliberately <b>not</b> in that list, following TLS working group feedback that a key exchange should retain a classical component: they are available in FIPS mode and out of it, but a caller has to ask for one through the jdk.tls.namedGroups property or BCSSLParameters.setNamedGroups rather than getting it by default. curveSM2MLKEM768 remains outside the FIPS set, as do plain x25519 and x448. A new test, org.bouncycastle.jsse.provider.test.TlsFipsTest, drives a TLS 1.3 handshake through the FIPS mode provider for each of the six groups with both ends restricted to the group under test, checks that a pure ML-KEM group does not reach a default configured server while a hybrid does, and also asserts that the FIPS approved GCM cipher suites and the TLSv1.3 protocol preference are present - the complement of the existing FIPS cipher suite suites, which check that nothing outside the FIPS set is exposed.</li>
171171
<li>FrodoKEM and Classic McEliece are now reachable through the javax.crypto.KEM API (JDK 21, JEP 452), which previously only ML-KEM, SM9, NTRU, NTRU Prime and HQC were. The standard BC provider registers KEM.FRODOKEM and KEM.CMCE, plus one parameter-set locked service for each of FrodoKEM's eight and Classic McEliece's sixteen ISO/IEC 18033-2:2006/Amd 2:2026 sets, each with the usual object identifier aliases so a caller dispatching on the OID in a received encoding finds the service. As with the other KEMs the implementations live in the multi-release jar's version 17 tree (org.bouncycastle.jcajce.provider.asymmetric.frodokem.FrodoKEMSpi and .cmce.CMCEKEMSpi with their Encapsulator/Decapsulator peers) and the registrations are gated on SpiUtil.hasKEM(), so on a JDK where javax.crypto.KEM is absent nothing is registered and the existing Cipher, KeyGenerator and KeyFactory services are unaffected. With a null spec the shared secret is the mechanism's own session key - the interoperable form - and a KTSParameterSpec KDF may be layered on top for generic use. Note FrodoKEM differs from ML-KEM in that its session key size follows the parameter set, 192 bits for the 976 sets and 256 for the 1344 sets, so the no-KDF secret size is taken from the key rather than assumed to be 256 bits; Classic McEliece is 256 bits throughout. For the same reason a KDF-less spec asking for more bits than the parameter set produces is refused with an InvalidAlgorithmParameterException naming the set and both sizes, rather than being quietly shortened the way the KTS key-wrapping path does - javax.crypto.KEM validates encapsulate()'s range against secretSize(), so that size has to be honest. The same applies to everything else a KTSParameterSpec can carry that a KEM cannot honour, since the spec validates none of it itself and each otherwise failed as an undeclared unchecked exception out of encapsulate() / decapsulate() rather than as a spec failure the caller can act on: a key size that is not a positive whole number of bytes (one below eight bits yielded a zero-length secret key, one that was not a whole number of bytes silently delivered fewer bits than were asked for, and one within seven of Integer.MAX_VALUE overflowed the rounding up of the byte count), a KDF algorithm identifier naming a KDF or digest the provider cannot service, and an absent key algorithm name. The validation and the algorithm-name reconciliation are shared as new org.bouncycastle.jcajce.provider.asymmetric.util.KdfUtil.resolveKemSpec and resolveAlgorithm methods rather than duplicated per KEM, and every javax.crypto.KEM encapsulator and decapsulator in the provider - ML-KEM, SM9, NTRU, NTRU Prime and HQC as well as the two added here - now reconciles the requested algorithm name through the shared method, which each previously carried its own identical copy of. Behaviour is unchanged, including the exception text for a name the spec does not authorise.</li>
172-
<li>NTRU LPRime, NTRU+ and SMAUG-T are now reachable through the javax.crypto.KEM API as well, which completes the BCPQC KEMs: each already had Cipher, KeyGenerator, KeyFactory and KeyPairGenerator services and only the KEM one was missing. NTRU LPRime gets KEM.NTRULPRIME, a family level service matching the SNTRU Prime counterpart registered beside it in the same class, whose absence was the whole difference between the two. NTRU+ gets KEM.NTRUPLUS and SMAUG-T KEM.SMAUGT, each with one parameter-set locked service per set, mirroring their other services. As elsewhere the implementations are multi-release jar version 17 classes gated on SpiUtil.hasKEM(), and they share KdfUtil.resolveKemSpec and resolveAlgorithm with the other KEMs rather than repeating the spec validation. NTRULPRimeParameters and SmaugTParameters gain a getEncapsulationLength() so the encapsulating side, which holds only a public key, derives the size from the same place the extractor does instead of repeating the expression or reaching for a package-private engine. Note the NTRU+ decapsulator constructs its extractor per call: an NTRUPlusKEMExtractor builds an NTRUPlusEngine, which keeps one SHAKE instance in a field, so sharing one across the concurrent decapsulate calls javax.crypto.KEM permits returned shared secrets that did not match the sender's. NTRU LPRime and SMAUG-T carry no such state and share an extractor.</li>
172+
<li>NTRU LPRime, NTRU+ and SMAUG-T are now reachable through the javax.crypto.KEM API as well, which completes the BCPQC KEMs: each already had Cipher, KeyGenerator, KeyFactory and KeyPairGenerator services and only the KEM one was missing. NTRU LPRime gets KEM.NTRULPRIME, a family level service matching the SNTRU Prime counterpart registered beside it in the same class, whose absence was the whole difference between the two. NTRU+ gets KEM.NTRUPLUS and SMAUG-T KEM.SMAUGT, each with one parameter-set locked service per set, mirroring their other services. As elsewhere the implementations are multi-release jar version 17 classes gated on SpiUtil.hasKEM(), and they share KdfUtil.resolveKemSpec and resolveAlgorithm with the other KEMs rather than repeating the spec validation. NTRULPRimeParameters and SmaugTParameters gain a getEncapsulationLength() so the encapsulating side, which holds only a public key, derives the size from the same place the extractor does instead of repeating the expression or reaching for a package-private engine. Note the NTRU+ decapsulator constructs its extractor per call: an NTRUPlusKEMExtractor builds an NTRUPlusEngine, which keeps one SHAKE instance in a field, so sharing one across the concurrent decapsulate calls javax.crypto.KEM permits returned shared secrets that did not match the sender's. NTRU LPRime and SMAUG-T carry no such state and share an extractor. The spec validation added for FrodoKEM and Classic McEliece is now applied by every KEM in the provider except SM9: ML-KEM, HQC, NTRU and SNTRU Prime previously accepted a KDF-less KTSParameterSpec asking for more bits than the mechanism produces and then failed with an ArrayIndexOutOfBoundsException out of encapsulate(), where they now refuse the spec with an InvalidAlgorithmParameterException naming the parameter set and both sizes. SM9 is excluded deliberately, as its own GM/T 0044.4 KDF produces the shared secret at whatever size was requested and so has no fixed session key to bound against.</li>
173173
<li>The new org.bouncycastle.x509.CRLDP_protocols property is an optional whitelist of the protocols a CRL Distribution Point may name, applied by the CrlCache behind both the provider's CertPath validator and X509RevocationChecker before any connection is opened, and ahead of the cache, so an entry already held for a distribution point is no way around it. It is a comma separated list matched without regard to case - "http,https,ldap" refuses a distribution point naming ftp, file, jar or anything else the JVM happens to have a URL handler registered for, with a CRLException naming the protocol. Unset or empty, the default, leaves the protocol unrestricted: RFC 5280 sec. 4.2.1.13 requires a distribution point URI to name a protocol but does not restrict which, and BouncyCastle supports http, https, ftp and ldap here, so this is a policy for deployments that want a narrower set rather than a new default. Note the fetch it governs only happens at all where org.bouncycastle.x509.enableCRLDP is set (see Defects Fixed above).</li>
174174
</ul>
175175

‎prov/build.gradle‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,11 @@ compileJava15Java {
190190
options.sourcepath = files(['src/main/java', 'src/main/jdk1.15'])
191191
}
192192

193+
// NOTE: deliberately targetCompatibility/sourceCompatibility rather than options.release, so this
194+
// tree compiles against the driving JDK's class library. That is what lets the KEM SPIs here
195+
// implement javax.crypto.KEMSpi (Java 21) while shipping under META-INF/versions/17, where one
196+
// overlay serves 17 upwards and SpiUtil.hasKEM() keeps them dormant below 21. The consequence is
197+
// that a JDK 21+ Gradle daemon is required to compile this source set.
193198
compileJava17Java {
194199
targetCompatibility = 17
195200
sourceCompatibility = 17

‎prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/NTRUPlus.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ public void configure(ConfigurableProvider provider)
5858

5959
if (SpiUtil.hasKEM())
6060
{
61-
provider.addAlgorithm("KEM.NTRUPLUS", PREFIX + "NTRUPlusKEMSpi$Base");
61+
addKEMAlgorithm(provider, "NTRUPLUS", PREFIX + "NTRUPlusKEMSpi$Base", BCObjectIdentifiers.pqc_kem_ntruplus);
6262

6363
addKEMAlgorithm(provider, "NTRU+KEM768", PREFIX + "NTRUPlusKEMSpi$NTRUPlus768", BCObjectIdentifiers.ntruplus768);
6464
addKEMAlgorithm(provider, "NTRU+KEM864", PREFIX + "NTRUPlusKEMSpi$NTRUPlus864", BCObjectIdentifiers.ntruplus864);

‎prov/src/main/java/org/bouncycastle/pqc/jcajce/provider/NTRUPrime.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ public void configure(ConfigurableProvider provider)
5656
if (SpiUtil.hasKEM())
5757
{
5858
// TODO Per-parameter-set SPI classes?
59-
addKEMAlgorithm(provider, "NTRULPRIME", PREFIX + "NTRULPRimeKEMSpi", BCObjectIdentifiers.pqc_kem_ntrulprime);
59+
addKEMAlgorithm(provider, "NTRULPRIME", PREFIX + "NTRULPRimeKEMSpi$NTRULPRime", BCObjectIdentifiers.pqc_kem_ntrulprime);
6060
addKEMAlgorithm(provider, "SNTRUPRIME", PREFIX + "SNTRUPrimeKEMSpi$SNTRUPrime", BCObjectIdentifiers.pqc_kem_sntruprime);
6161
}
6262
}

0 commit comments

Comments
 (0)