Skip to content

Commit 703270c

Browse files
author
gefeili
committed
Add javax.crypto.KEM support for the ISO/IEC 18033-2 FrodoKEM and Classic McEliece KEMs, which had Cipher, KeyGenerator and KeyFactory services but no KEMSpi, as ML-KEM and SM9 do - jdk17 MR-jar KEMSpi/Encapsulator/Decapsulator trios modelled on the ML-KEM ones, registered by the standard BC provider behind SpiUtil.hasKEM() as a family service plus one parameter-set locked service per set with the usual OID aliases. Unlike ML-KEM, FrodoKEM's session key size follows the parameter set (192 bits for the 976 sets, 256 for the 1344 sets), so the no-KDF secret size is taken from the key rather than assumed to be 256, and a KDF-less spec asking for more bits than the set produces is refused with an InvalidAlgorithmParameterException naming the set and both sizes rather than quietly shortened the way WrapUtil clamps a KEK - javax.crypto.KEM validates encapsulate()'s range against secretSize(), so that size has to be honest.
1 parent e6b360d commit 703270c

12 files changed

Lines changed: 1507 additions & 0 deletions

File tree

‎docs/releasenotes.html‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +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.</li>
169170
<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>
170171
</ul>
171172

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

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import org.bouncycastle.jcajce.provider.config.ConfigurableProvider;
66
import org.bouncycastle.jcajce.provider.util.AsymmetricAlgorithmProvider;
77
import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter;
8+
import org.bouncycastle.jcajce.util.SpiUtil;
89

910
public class CMCE
1011
{
@@ -117,6 +118,28 @@ public void configure(ConfigurableProvider provider)
117118
provider.addKeyInfoConverter(ISOIECObjectIdentifiers.mceliece8192128f, keyFact);
118119
provider.addKeyInfoConverter(ISOIECObjectIdentifiers.mceliece8192128pc, keyFact);
119120
provider.addKeyInfoConverter(ISOIECObjectIdentifiers.mceliece8192128pcf, keyFact);
121+
122+
if (SpiUtil.hasKEM())
123+
{
124+
provider.addAlgorithm("KEM.CMCE", PREFIX + "CMCEKEMSpi$Base");
125+
126+
addKEMAlgorithm(provider, "mceliece460896", PREFIX + "CMCEKEMSpi$Mceliece460896", ISOIECObjectIdentifiers.mceliece460896);
127+
addKEMAlgorithm(provider, "mceliece460896f", PREFIX + "CMCEKEMSpi$Mceliece460896F", ISOIECObjectIdentifiers.mceliece460896f);
128+
addKEMAlgorithm(provider, "mceliece460896pc", PREFIX + "CMCEKEMSpi$Mceliece460896Pc", ISOIECObjectIdentifiers.mceliece460896pc);
129+
addKEMAlgorithm(provider, "mceliece460896pcf", PREFIX + "CMCEKEMSpi$Mceliece460896Pcf", ISOIECObjectIdentifiers.mceliece460896pcf);
130+
addKEMAlgorithm(provider, "mceliece6688128", PREFIX + "CMCEKEMSpi$Mceliece6688128", ISOIECObjectIdentifiers.mceliece6688128);
131+
addKEMAlgorithm(provider, "mceliece6688128f", PREFIX + "CMCEKEMSpi$Mceliece6688128F", ISOIECObjectIdentifiers.mceliece6688128f);
132+
addKEMAlgorithm(provider, "mceliece6688128pc", PREFIX + "CMCEKEMSpi$Mceliece6688128Pc", ISOIECObjectIdentifiers.mceliece6688128pc);
133+
addKEMAlgorithm(provider, "mceliece6688128pcf", PREFIX + "CMCEKEMSpi$Mceliece6688128Pcf", ISOIECObjectIdentifiers.mceliece6688128pcf);
134+
addKEMAlgorithm(provider, "mceliece6960119", PREFIX + "CMCEKEMSpi$Mceliece6960119", ISOIECObjectIdentifiers.mceliece6960119);
135+
addKEMAlgorithm(provider, "mceliece6960119f", PREFIX + "CMCEKEMSpi$Mceliece6960119F", ISOIECObjectIdentifiers.mceliece6960119f);
136+
addKEMAlgorithm(provider, "mceliece6960119pc", PREFIX + "CMCEKEMSpi$Mceliece6960119Pc", ISOIECObjectIdentifiers.mceliece6960119pc);
137+
addKEMAlgorithm(provider, "mceliece6960119pcf", PREFIX + "CMCEKEMSpi$Mceliece6960119Pcf", ISOIECObjectIdentifiers.mceliece6960119pcf);
138+
addKEMAlgorithm(provider, "mceliece8192128", PREFIX + "CMCEKEMSpi$Mceliece8192128", ISOIECObjectIdentifiers.mceliece8192128);
139+
addKEMAlgorithm(provider, "mceliece8192128f", PREFIX + "CMCEKEMSpi$Mceliece8192128F", ISOIECObjectIdentifiers.mceliece8192128f);
140+
addKEMAlgorithm(provider, "mceliece8192128pc", PREFIX + "CMCEKEMSpi$Mceliece8192128Pc", ISOIECObjectIdentifiers.mceliece8192128pc);
141+
addKEMAlgorithm(provider, "mceliece8192128pcf", PREFIX + "CMCEKEMSpi$Mceliece8192128Pcf", ISOIECObjectIdentifiers.mceliece8192128pcf);
142+
}
120143
}
121144
}
122145
}

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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import org.bouncycastle.jcajce.provider.config.ConfigurableProvider;
66
import org.bouncycastle.jcajce.provider.util.AsymmetricAlgorithmProvider;
77
import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter;
8+
import org.bouncycastle.jcajce.util.SpiUtil;
89

910
public class FrodoKEM
1011
{
@@ -77,6 +78,21 @@ public void configure(ConfigurableProvider provider)
7778
provider.addKeyInfoConverter(ISOIECObjectIdentifiers.frodokem1344_aes, keyFact);
7879
provider.addKeyInfoConverter(ISOIECObjectIdentifiers.efrodokem976_aes, keyFact);
7980
provider.addKeyInfoConverter(ISOIECObjectIdentifiers.efrodokem1344_aes, keyFact);
81+
82+
if (SpiUtil.hasKEM())
83+
{
84+
provider.addAlgorithm("KEM.FRODOKEM", PREFIX + "FrodoKEMSpi$Base");
85+
provider.addAlgorithm("Alg.Alias.KEM.FrodoKEM", "FRODOKEM");
86+
87+
addKEMAlgorithm(provider, "frodokem976shake", PREFIX + "FrodoKEMSpi$Frodokem976Shake", ISOIECObjectIdentifiers.frodokem976_shake);
88+
addKEMAlgorithm(provider, "frodokem1344shake", PREFIX + "FrodoKEMSpi$Frodokem1344Shake", ISOIECObjectIdentifiers.frodokem1344_shake);
89+
addKEMAlgorithm(provider, "efrodokem976shake", PREFIX + "FrodoKEMSpi$EFrodokem976Shake", ISOIECObjectIdentifiers.efrodokem976_shake);
90+
addKEMAlgorithm(provider, "efrodokem1344shake", PREFIX + "FrodoKEMSpi$EFrodokem1344Shake", ISOIECObjectIdentifiers.efrodokem1344_shake);
91+
addKEMAlgorithm(provider, "frodokem976aes", PREFIX + "FrodoKEMSpi$Frodokem976Aes", ISOIECObjectIdentifiers.frodokem976_aes);
92+
addKEMAlgorithm(provider, "frodokem1344aes", PREFIX + "FrodoKEMSpi$Frodokem1344Aes", ISOIECObjectIdentifiers.frodokem1344_aes);
93+
addKEMAlgorithm(provider, "efrodokem976aes", PREFIX + "FrodoKEMSpi$EFrodokem976Aes", ISOIECObjectIdentifiers.efrodokem976_aes);
94+
addKEMAlgorithm(provider, "efrodokem1344aes", PREFIX + "FrodoKEMSpi$EFrodokem1344Aes", ISOIECObjectIdentifiers.efrodokem1344_aes);
95+
}
8096
}
8197
}
8298
}
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
package org.bouncycastle.jcajce.provider.asymmetric.cmce;
2+
3+
import java.util.Objects;
4+
5+
import javax.crypto.DecapsulateException;
6+
import javax.crypto.KEMSpi;
7+
import javax.crypto.SecretKey;
8+
import javax.crypto.spec.SecretKeySpec;
9+
10+
import org.bouncycastle.crypto.kems.CMCEKEMExtractor;
11+
import org.bouncycastle.jcajce.provider.asymmetric.util.KdfUtil;
12+
import org.bouncycastle.jcajce.spec.KTSParameterSpec;
13+
import org.bouncycastle.util.Arrays;
14+
15+
/*
16+
* NOTE: Per javadoc for javax.crypto.KEM, "Encapsulator and Decapsulator objects are also immutable. It is safe to
17+
* invoke multiple encapsulate and decapsulate methods on the same Encapsulator or Decapsulator object at the same
18+
* time. Each invocation of encapsulate will generate a new shared secret and key encapsulation message."
19+
*/
20+
class CMCEDecapsulatorSpi
21+
implements KEMSpi.DecapsulatorSpi
22+
{
23+
private final KTSParameterSpec parameterSpec;
24+
private final CMCEKEMExtractor kemExt;
25+
26+
CMCEDecapsulatorSpi(BCCMCEPrivateKey privateKey, KTSParameterSpec parameterSpec)
27+
{
28+
this.parameterSpec = parameterSpec;
29+
this.kemExt = new CMCEKEMExtractor(privateKey.getKeyParams());
30+
}
31+
32+
@Override
33+
public SecretKey engineDecapsulate(byte[] encapsulation, int from, int to, String algorithm)
34+
throws DecapsulateException
35+
{
36+
Objects.checkFromToIndex(from, to, engineSecretSize());
37+
Objects.requireNonNull(algorithm, "null algorithm");
38+
Objects.requireNonNull(encapsulation, "null encapsulation");
39+
40+
if (encapsulation.length != engineEncapsulationSize())
41+
{
42+
throw new DecapsulateException("incorrect encapsulation size");
43+
}
44+
45+
String keyAlgName = parameterSpec.getKeyAlgorithmName();
46+
if (!"Generic".equals(keyAlgName))
47+
{
48+
// if algorithm is Generic then use parameterSpec to wrap key
49+
if ("Generic".equals(algorithm))
50+
{
51+
algorithm = keyAlgName;
52+
}
53+
// check spec algorithm mismatch provided algorithm
54+
else if (!algorithm.equals(keyAlgName))
55+
{
56+
throw new UnsupportedOperationException(keyAlgName + " does not match " + algorithm);
57+
}
58+
}
59+
60+
byte[] kemSecret = kemExt.extractSecret(encapsulation);
61+
byte[] kdfSecret = KdfUtil.makeKeyBytes(parameterSpec, kemSecret);
62+
63+
try
64+
{
65+
return new SecretKeySpec(kdfSecret, from, to - from, algorithm);
66+
}
67+
finally
68+
{
69+
Arrays.clear(kdfSecret);
70+
}
71+
}
72+
73+
@Override
74+
public int engineSecretSize()
75+
{
76+
return parameterSpec.getKeySize() / 8;
77+
}
78+
79+
@Override
80+
public int engineEncapsulationSize()
81+
{
82+
return kemExt.getEncapsulationLength();
83+
}
84+
}
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
package org.bouncycastle.jcajce.provider.asymmetric.cmce;
2+
3+
import java.security.SecureRandom;
4+
import java.util.Objects;
5+
6+
import javax.crypto.KEM;
7+
import javax.crypto.KEMSpi;
8+
import javax.crypto.SecretKey;
9+
import javax.crypto.spec.SecretKeySpec;
10+
11+
import org.bouncycastle.crypto.SecretWithEncapsulation;
12+
import org.bouncycastle.crypto.kems.CMCEKEMGenerator;
13+
import org.bouncycastle.jcajce.provider.asymmetric.util.KdfUtil;
14+
import org.bouncycastle.jcajce.spec.KTSParameterSpec;
15+
import org.bouncycastle.util.Arrays;
16+
17+
/*
18+
* NOTE: Per javadoc for javax.crypto.KEM, "Encapsulator and Decapsulator objects are also immutable. It is safe to
19+
* invoke multiple encapsulate and decapsulate methods on the same Encapsulator or Decapsulator object at the same
20+
* time. Each invocation of encapsulate will generate a new shared secret and key encapsulation message."
21+
*/
22+
class CMCEEncapsulatorSpi
23+
implements KEMSpi.EncapsulatorSpi
24+
{
25+
private final BCCMCEPublicKey publicKey;
26+
private final KTSParameterSpec parameterSpec;
27+
private final CMCEKEMGenerator kemGen;
28+
29+
CMCEEncapsulatorSpi(BCCMCEPublicKey publicKey, KTSParameterSpec parameterSpec, SecureRandom random)
30+
{
31+
this.publicKey = publicKey;
32+
this.parameterSpec = parameterSpec;
33+
this.kemGen = new CMCEKEMGenerator(random);
34+
}
35+
36+
@Override
37+
public KEM.Encapsulated engineEncapsulate(int from, int to, String algorithm)
38+
{
39+
Objects.checkFromToIndex(from, to, engineSecretSize());
40+
Objects.requireNonNull(algorithm, "null algorithm");
41+
42+
String keyAlgName = parameterSpec.getKeyAlgorithmName();
43+
if (!"Generic".equals(keyAlgName))
44+
{
45+
// if algorithm is Generic then use parameterSpec to wrap key
46+
if ("Generic".equals(algorithm))
47+
{
48+
algorithm = keyAlgName;
49+
}
50+
// check spec algorithm mismatch provided algorithm
51+
else if (!algorithm.equals(keyAlgName))
52+
{
53+
throw new UnsupportedOperationException(keyAlgName + " does not match " + algorithm);
54+
}
55+
}
56+
57+
SecretWithEncapsulation secEnc = kemGen.generateEncapsulated(publicKey.getKeyParams());
58+
59+
byte[] encapsulation = secEnc.getEncapsulation();
60+
61+
byte[] kemSecret = secEnc.getSecret();
62+
byte[] kdfSecret = KdfUtil.makeKeyBytes(parameterSpec, kemSecret);
63+
64+
try
65+
{
66+
SecretKey secretKey = new SecretKeySpec(kdfSecret, from, to - from, algorithm);
67+
return new KEM.Encapsulated(secretKey, encapsulation, null);
68+
}
69+
finally
70+
{
71+
Arrays.clear(kdfSecret);
72+
}
73+
}
74+
75+
@Override
76+
public int engineSecretSize()
77+
{
78+
return parameterSpec.getKeySize() / 8;
79+
}
80+
81+
@Override
82+
public int engineEncapsulationSize()
83+
{
84+
return publicKey.getKeyParams().getParameters().getEncapsulationLength();
85+
}
86+
}

0 commit comments

Comments
 (0)