Skip to content

Commit 5fd08f7

Browse files
author
gefeili
committed
Address the code review of the FrodoKEM and Classic McEliece KEM support. Build the FrodoKEMExtractor per decapsulation rather than caching it, as FrodoKEMCipherSpi.engineUnwrap already does: it holds one FrodoKEMEngine whose SHAKE digest is mutable, so a shared KEM.Decapsulator - the use javax.crypto.KEM documents as safe, and which this class' own header comment quotes - returned wrong shared secrets and threw "attempt to absorb while squeezing" past its DecapsulateException contract, measured at 31 of 320 concurrent decapsulations. Complete the spec validation, which caught only a non-positive key size: a size below eight bits passed it and produced a zero-length secret key, since makeKeyBytes rounds the byte count up while secretSize() rounds it down and SecretKeySpec's own empty-key check therefore never fired; a size that was not a whole number of bytes silently delivered fewer bits than were asked for; a size within seven of Integer.MAX_VALUE overflowed the rounding up; a KDF identifier the provider cannot service, and an absent key algorithm name, both escaped as undeclared unchecked exceptions from encapsulate. Share the validation and the algorithm-name reconciliation as KdfUtil.resolveKemSpec and resolveAlgorithm instead of a copy per KEM, and hoist the encapsulation length into the constructor rather than rebuilding an engine per call. Cover each of these, the decapsulator's own algorithm reconciliation and the range and null guards - none of which any test reached - and assert all sixteen and all eight parameter-set locked services resolve to their own class and agree with their object identifier, which needs no key generation.
1 parent e9e6da2 commit 5fd08f7

10 files changed

Lines changed: 828 additions & 223 deletions

File tree

‎docs/releasenotes.html‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ <h3>2.1.3 Additional Features and Functionality</h3>
166166
<li>org.bouncycastle.operator.KemAlgorithmIdentifierFinder and its DefaultKemAlgorithmIdentifierFinder implementation are the KEM counterpart of SignatureAlgorithmIdentifierFinder, turning a KEM algorithm name into the AlgorithmIdentifier that names it in a SubjectPublicKeyInfo, a CMS KEMRecipientInfo (RFC 9629) or a CMP KemCiphertextInfo - previously a caller had to assemble that identifier from the OID constants by hand, as BouncyCastle's own TLS and composite-KEM code still does through private switches. Names are matched without regard to case and cover the same set the name finder now names, so the two directions round-trip; an unrecognised name raises IllegalArgumentException rather than returning null, and hasAlgorithm(String) tests for support without catching, in the same way AlgorithmNameFinder.hasAlgorithmName does for the reverse direction. DefaultSignatureAlgorithmIdentifierFinder gains the same hasAlgorithm(String) method; it sits on the implementation rather than on SignatureAlgorithmIdentifierFinder, since adding a method to that long-published interface would break every implementation outside the library. Each KEM parameter set has its own OID, so every identifier returned has an absent parameters field - compare received identifiers with AlgorithmIdentifier.areEquivalent rather than equals, so a peer that spells the algorithm with an explicit NULL still matches. A new parent interface, org.bouncycastle.operator.AlgorithmIdentifierFinder, carries the shared find(String) contract, extended by SignatureAlgorithmIdentifierFinder, KemAlgorithmIdentifierFinder and DigestAlgorithmIdentifierFinder - the finders that behave alike, matching names without regard to case and throwing IllegalArgumentException for a name they do not recognise. MacAlgorithmIdentifierFinder stays outside the hierarchy, as it returns null for an unrecognised name instead. Existing implementations are unaffected, as the parent requires only the method its subinterfaces already declared. Two changes to DefaultDigestAlgorithmIdentifierFinder bring it into that contract. Its name lookup now throws IllegalArgumentException("Unknown digest algorithm requested: ...") where it used to return null, matching the signature and KEM finders; its other two overloads are untouched, so find(AlgorithmIdentifier) still returns null when it cannot derive a digest from a signature algorithm, which github #1767 relies on, and a name given in dotted OID form is still read as one. Callers that treated the null as an error are unaffected beyond the exception type - org.bouncycastle.est.HttpAuth, the only one in the library that branched on it, still reports an unrecognised HTTP Digest algorithm as an IOException - while JcaContentSignerBuilder and JcaAlgorithmParametersConverter, which dereferenced the result without checking, now name the offending algorithm instead of raising a bare NullPointerException. DefaultDigestAlgorithmIdentifierFinder also gains a hasAlgorithm(String), answering for exactly the names find(String) accepts - the digest name table or a name in dotted OID form - so the two cannot disagree. And name matching now folds case in all four finders: DefaultDigestAlgorithmIdentifierFinder was the one that did not, looking its digest names up verbatim, and it now upper cases the supplied name first. Every key in its table was already upper case, so that only widens what matches and cannot change a lookup that already succeeded; a name given in dotted OID form is still passed through unfolded.</li>
167167
<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>
168168
<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>
169-
<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. A KTSParameterSpec whose key size is zero or negative is refused there too, as KTSParameterSpec does not check its own key size and such a spec otherwise failed as an undeclared unchecked exception out of encapsulate() / decapsulate() rather than as a spec failure the caller can act on.</li>
169+
<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.</li>
170170
<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>
171171
</ul>
172172

‎prov/src/main/java/org/bouncycastle/jcajce/provider/asymmetric/util/KdfUtil.java‎

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
package org.bouncycastle.jcajce.provider.asymmetric.util;
22

3+
import java.security.InvalidAlgorithmParameterException;
4+
import java.security.spec.AlgorithmParameterSpec;
5+
36
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
47
import org.bouncycastle.asn1.ASN1OctetString;
58
import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
@@ -21,10 +24,164 @@
2124
import org.bouncycastle.crypto.params.KDFParameters;
2225
import org.bouncycastle.crypto.params.KeyParameter;
2326
import org.bouncycastle.jcajce.spec.KEMKDFSpec;
27+
import org.bouncycastle.jcajce.spec.KTSParameterSpec;
2428
import org.bouncycastle.util.Arrays;
2529

2630
public class KdfUtil
2731
{
32+
/**
33+
* Validate a KTSParameterSpec offered to a KEM, or build the default spec - the shared secret
34+
* used as it comes, with no KDF - when the caller supplied none.
35+
* <p>
36+
* Everything a KEM cannot honour is rejected here rather than at encapsulate/decapsulate time,
37+
* where it would surface as an unchecked exception the javax.crypto.KEM API does not declare.
38+
* Note that without a KDF the secret is the mechanism's own session key, so the requested size
39+
* must be a whole number of bytes no larger than that key: javax.crypto.KEM validates
40+
* encapsulate()'s range against secretSize(), so that size has to be honest rather than
41+
* quietly shortened the way {@link WrapUtil} shortens a KEK to the secret it has.
42+
*
43+
* @param spec the caller-supplied spec, or null for the default.
44+
* @param algorithmName the KEM's name, used in the exception messages.
45+
* @param parameterSetName the name of the key's parameter set, used in the exception messages.
46+
* @param sessionKeySize the size in bits of the mechanism's own session key for that set.
47+
* @return the spec to use.
48+
* @throws InvalidAlgorithmParameterException if the spec cannot be honoured.
49+
*/
50+
public static KTSParameterSpec resolveKemSpec(AlgorithmParameterSpec spec, String algorithmName,
51+
String parameterSetName, int sessionKeySize)
52+
throws InvalidAlgorithmParameterException
53+
{
54+
if (spec == null)
55+
{
56+
// Do not wrap key, no KDF
57+
return new KTSParameterSpec.Builder("Generic", sessionKeySize).withNoKdf().build();
58+
}
59+
60+
if (!(spec instanceof KTSParameterSpec))
61+
{
62+
throw new InvalidAlgorithmParameterException(algorithmName + " can only accept KTSParameterSpec");
63+
}
64+
65+
KTSParameterSpec ktsSpec = (KTSParameterSpec)spec;
66+
67+
// KTSParameterSpec does not check its own algorithm name, and a null one is only noticed
68+
// once it has been substituted for a "Generic" request and handed to the SecretKey.
69+
if (ktsSpec.getKeyAlgorithmName() == null)
70+
{
71+
throw new InvalidAlgorithmParameterException("KTSParameterSpec has no key algorithm name");
72+
}
73+
74+
// Nor does it check its own key size. A size below 8 would yield a zero-length secret key
75+
// (makeKeyBytes rounds the byte count up while a KEM's secretSize() rounds it down), one
76+
// that is not a whole number of bytes would silently deliver fewer bits than were asked
77+
// for, and one within 7 of Integer.MAX_VALUE would overflow the rounding-up itself.
78+
int keySize = ktsSpec.getKeySize();
79+
if (keySize <= 0 || (keySize % 8) != 0)
80+
{
81+
throw new InvalidAlgorithmParameterException(
82+
"KTSParameterSpec key size must be a positive whole number of bytes: " + keySize);
83+
}
84+
85+
if (ktsSpec.getKdfAlgorithm() == null)
86+
{
87+
if (keySize > sessionKeySize)
88+
{
89+
throw new InvalidAlgorithmParameterException("no KDF specified and " + parameterSetName
90+
+ " produces a " + sessionKeySize + " bit secret, " + keySize + " requested");
91+
}
92+
}
93+
else if (!isSupportedKdf(ktsSpec.getKdfAlgorithm()))
94+
{
95+
throw new InvalidAlgorithmParameterException("unsupported KDF: "
96+
+ ktsSpec.getKdfAlgorithm().getAlgorithm());
97+
}
98+
99+
return ktsSpec;
100+
}
101+
102+
/**
103+
* Reconcile the algorithm name passed to a KEM's encapsulate/decapsulate with the one its
104+
* KTSParameterSpec names: "Generic" on either side defers to the other, and a genuine mismatch
105+
* is refused.
106+
*
107+
* @param parameterSpec the spec the KEM was created with.
108+
* @param algorithm the algorithm name the caller asked for.
109+
* @return the algorithm name to label the secret key with.
110+
*/
111+
public static String resolveAlgorithm(KTSParameterSpec parameterSpec, String algorithm)
112+
{
113+
String keyAlgName = parameterSpec.getKeyAlgorithmName();
114+
115+
if ("Generic".equals(keyAlgName))
116+
{
117+
return algorithm;
118+
}
119+
// if algorithm is Generic then use parameterSpec to wrap key
120+
if ("Generic".equals(algorithm))
121+
{
122+
return keyAlgName;
123+
}
124+
// check spec algorithm mismatch provided algorithm
125+
if (!algorithm.equals(keyAlgName))
126+
{
127+
throw new UnsupportedOperationException(keyAlgName + " does not match " + algorithm);
128+
}
129+
130+
return algorithm;
131+
}
132+
133+
/**
134+
* Return true if makeKeyBytes can service the passed in KDF algorithm identifier.
135+
*/
136+
private static boolean isSupportedKdf(AlgorithmIdentifier kdfAlgorithm)
137+
{
138+
ASN1ObjectIdentifier kdfOid = kdfAlgorithm.getAlgorithm();
139+
140+
try
141+
{
142+
if (X9ObjectIdentifiers.id_kdf_kdf2.equals(kdfOid) || X9ObjectIdentifiers.id_kdf_kdf3.equals(kdfOid))
143+
{
144+
if (kdfAlgorithm.getParameters() == null)
145+
{
146+
return false;
147+
}
148+
149+
ASN1ObjectIdentifier digOid = AlgorithmIdentifier.getInstance(
150+
kdfAlgorithm.getParameters()).getAlgorithm();
151+
152+
// the digests getDigest() knows
153+
return NISTObjectIdentifiers.id_sha256.equals(digOid)
154+
|| NISTObjectIdentifiers.id_sha512.equals(digOid)
155+
|| NISTObjectIdentifiers.id_shake128.equals(digOid)
156+
|| NISTObjectIdentifiers.id_shake256.equals(digOid);
157+
}
158+
159+
if (PKCSObjectIdentifiers.id_alg_hkdf_with_sha256.equals(kdfOid)
160+
|| PKCSObjectIdentifiers.id_alg_hkdf_with_sha384.equals(kdfOid)
161+
|| PKCSObjectIdentifiers.id_alg_hkdf_with_sha512.equals(kdfOid))
162+
{
163+
// HKDF parameter support has not been added
164+
return kdfAlgorithm.getParameters() == null;
165+
}
166+
167+
if (NISTObjectIdentifiers.id_Kmac128.equals(kdfOid) || NISTObjectIdentifiers.id_Kmac256.equals(kdfOid))
168+
{
169+
if (kdfAlgorithm.getParameters() != null)
170+
{
171+
ASN1OctetString.getInstance(kdfAlgorithm.getParameters());
172+
}
173+
return true;
174+
}
175+
176+
return NISTObjectIdentifiers.id_shake256.equals(kdfOid);
177+
}
178+
catch (IllegalArgumentException e)
179+
{
180+
// a parameters field that will not decode as the branch requires
181+
return false;
182+
}
183+
}
184+
28185
/**
29186
* Generate a byte[] secret key from the passed in secret. Note: passed in secret will be erased after use.
30187
*

0 commit comments

Comments
 (0)