Skip to content

Commit b2f6375

Browse files
committed
The XDH KeyFactory now accepts and returns the JDK's own java.security.spec.XECPublicKeySpec and XECPrivateKeySpec on JDK 11 and later, through the jdk1.11 XDHKeys twin that already produces the XEC-implementing key classes, so an X25519 or X448 key round-trips through the standard spec as an Edwards key has done since the JDK 15 EdEC specs, with the u-coordinate reduced modulo the field prime and encoded little-endian by the conversion an incoming XECPublicKey already went through, RFC 7748 sec. 5 requiring a value at or past the prime to be taken as though it had been reduced.
1 parent a219442 commit b2f6375

7 files changed

Lines changed: 467 additions & 7 deletions

File tree

‎docs/releasenotes.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,7 @@ Date: 2026, TBD
168168
- The PKCS#12 key stores let an unchecked exception escape KeyStore.setKeyEntry() and KeyStore.setCertificateEntry(), both of which declare only KeyStoreException. The two methods key their internal certificate map on a SHA-1 digest taken over the certificate's public key, and a certificate naming an algorithm the provider has no key info converter for has a null public key - BouncyCastleProvider.getPublicKey() returns null for a SubjectPublicKeyInfo whose algorithm it cannot convert, and the provider's X.509 certificate implementation passes that on - so the digest step dereferenced null and an IllegalStateException("error creating key") came out, a plain RuntimeException in the case of the RFC 9579 PBMAC1 store. A caller handling the declared KeyStoreException was bypassed. Both methods had also stored the entry by the time the digest was taken, so a rejected key or certificate was left behind in the store under its alias. Both stores now require a resolvable public key of every certificate before anything is stored, and report a missing one as the KeyStoreException they declare; a zero-length certificate chain, which KeyStore.setKeyEntry() screens itself but a direct SPI caller does not, is now reported like a null one rather than as an ArrayIndexOutOfBoundsException. The read side was already covered, engineLoad translating any unchecked exception from the safe contents to the IOException it declares. The jdk1.3 and jdk1.4 provider copies carry the same corrections (github #2419).
169169
- Reading a prefixed (old style, non-one-pass) signed message through the high-level OpenPGP API (org.bouncycastle.openpgp.api.OpenPGPMessageProcessor) threw a NullPointerException out of OpenPGPMessageInputStream.read() whenever the signer's certificate had not been supplied to the processor, which is the ordinary case of a message arriving before its sender's key has been fetched. In a prefixed message the signature packet precedes the literal data, so the signature can only be initialised for verification once the issuer's public key is known; the reader recorded such a signature with a null issuer and then fed the message data to it regardless, reaching an uninitialised PGPSignature. Only a signature whose PGPSignature was successfully initialised is now updated and verified, so an unavailable certificate or a failed initialisation leaves the signature out of the reported verification results and the plaintext is returned as it already was on the one-pass signature path (github #2417).
170170
- Every classical signer assembled the signature component s with plain BigInteger arithmetic over the signing key: ECDSASigner formed k^-1 \* (e + d \* r) mod n, SM2Signer (1 + d)^-1 \* (k - r \* d) mod n, DSASigner k^-1 \* (m + x \* r) mod q, GOST3410Signer k \* m + x \* r mod q, ECGOST3410Signer k \* e + d \* r mod n, ECNRSigner u - r \* x mod n, BIP340Signer k + e \* d mod n and DSTU4145Signer r \* d + e mod n, and while the inverse in each had already been moved to the constant-time BigIntegers.modOddInverse, the multiplications and reductions around it had not. BigInteger.mod does an amount of work set by the quotient, so the cost of forming s answered a question about the long-lived signing key once per signature, and since r and e (SM2: r and k) vary publicly from one signature to the next those answers combine over a run of signatures; the same reasoning moved the ECCSI and SAKKE arithmetic in this release. All eight now go through BigIntegers.modMult, modAdd and the new modSubtract (see Additional Features below), which need their operands already reduced. The five elliptic-curve signers take their key as an ECPrivateKeyParameters, so the signing key is in [1, n-1] by ECDomainParameters.validatePrivateScalar, and each nonce and each r is reduced where it is produced - EC-NR's ephemeral comes from a generated key pair, BIP 340's nonce and challenge are reduced and its two conditional negations leave both operands in range, and DSTU 4145 draws its e in [1, n-1] and truncates r below 2^(n.bitLength()-1). The hash-derived value is the one that needed handling in four of them: ECDSA's e, DSA's m, and the GOST 3410 and ECGOST 3410 digests can all sit at or past the order, and all four are public, so each is reduced on the way in at no cost. DSA and GOST 3410 needed one further thing. Unlike ECPrivateKeyParameters, neither DSAPrivateKeyParameters nor GOST3410PrivateKeyParameters checked the range of x, so a key outside [1, q-1] - which FIPS 186-4 sec. 4.1 does not permit - was silently reduced by the arithmetic that formed s. Both now reject such a key when it is constructed, which is where the check belongs: unlike the ECCSI signing key, which does not carry its curve and so has to be checked at the signer, a DSA or GOST key carries the parameters that bound it. A key with no parameters attached is left alone, as it cannot sign in any case. Signatures are unchanged: the RFC 6979 deterministic ECDSA vectors, the SM2 GM/T 0003.2 vectors, the BIP-340 vectors and the GOST R 34.10 fixed-nonce vectors reproduce byte for byte, EC-NR reproduces its fixed-nonce expected values, and DSTU 4145 still verifies what it signs. One behavioural edge: modMult requires an odd modulus, so a caller-built curve whose order is even - which no standard curve has, and which the group structure does not admit - is now refused rather than signed with. The substitutions preserve the result and so cannot be caught by any signing or verification test, and are covered instead by the class-file scan in ConstantTimeUsageTest, which gains rows for all eight signers.
171+
- The XDH KeyFactory did not accept the JDK's own X25519 / X448 key specs. On JDK 11 and later BC's X25519 and X448 keys implement java.security.interfaces.XECPublicKey and XECPrivateKey, so a caller can read the u-coordinate and the scalar through the standard interfaces, but the reverse direction was missing: KeyFactory.getInstance("X25519", "BC").generatePublic(new XECPublicKeySpec(NamedParameterSpec.X25519, u)) failed with InvalidKeySpecException("key spec not recognized"), as did XECPrivateKeySpec and both of them for X448, and asking for either spec back through KeyFactory.getKeySpec() reached the "not implemented yet" fall-through in BaseKeyFactorySpi. A key could therefore be exported through the standard interface but not re-imported through the standard spec, which breaks code that moves a key between BC and another provider by coordinates rather than by encoding. Both specs are now accepted by generatePublic / generatePrivate and returned by getKeySpec, through the same jdk1.11 multi-release hook (XDHKeys) that produces the XEC-implementing key classes; the Edwards side has done this since the JDK 15 EdEC specs, and this is the X25519 / X448 analogue of it. The u-coordinate arrives as a BigInteger and is reduced modulo the field prime before being encoded little-endian into 32 or 56 octets, which RFC 7748 sec. 5 requires - "Implementations MUST accept non-canonical values and process them as if they had been reduced modulo the field prime" - and which the JDK's own provider also does; the reduction went into the conversion both entry points share, so an incoming third-party XECPublicKey carrying a non-canonical or over-wide u is now reduced rather than kept as it stands or rejected. A negative u is still refused, as it already was on the key path. Note that BC and the JDK provider agree on the coordinate but not always on the whole SubjectPublicKeyInfo: SunEC on JDK 11 writes an explicit NULL in the AlgorithmIdentifier parameters where RFC 8410 sec. 3 requires them absent ("For all of the OIDs, the parameters MUST be absent"), which BC does not follow and later JDKs no longer do. Because only the jdk1.11 copy of the hook implements any of this, the coverage is a new multi-release test, prov/src/test/jdk1.11 XDHKeySpecMRTest, registered in AllTests11 and run by the test11 task.
171172
- The GOST R 34.10-2001 / 2012 signer (org.bouncycastle.crypto.signers.ECGOST3410Signer, and ECGOST3410_2012Signer which extends it) drew its per-signature nonce uniformly over the bit length of the group order and rejected only a draw of zero, where the GOST R 34.10-94 signer beside it already redraws anything at or past the order. A draw that landed at or past n was therefore not discarded but folded to k mod n by the reductions that followed, which makes the bottom of the range likelier than the top. On most of the named curves that costs nothing - the order is either just below the next power of two, so such a draw essentially never happens, or close to half of it, so the fold covers the range exactly twice and the result stays uniform - but on the three whose order is about 0.61 of 2^256 (GostR3410-2001-CryptoPro-C, GostR3410-2001-CryptoPro-XchB and Tc26-Gost-3410-12-256-paramSetD) the bottom 64.5% of the range takes 78.4% of the draws, so a nonce fell below n/2 about 61% of the time rather than 50%. A nonce that is not uniform over [1, n-1] is the input a lattice attack on the signing key consumes, and while no key recovery is demonstrated here, the scheme's security argument assumes a uniform one. The nonce is now redrawn until it is below the order, as the GOST R 34.10-94 signer does. That signer had the mirror of the same gap and is corrected with it: it redrew a nonce at or past q but accepted one of zero, which is the single value that gives the signing key away outright - the blinded exponent becomes a multiple of q, so r is 1 and s = k * m + x * r collapses to x. It is a 2^-256 draw, but free to close, and it is now redrawn like any other unusable value. A caller supplying a deterministic stream of test randomness will see further bytes requested where a draw is out of range and previously was not redrawn; the GOST R 34.10 vectors all draw in range and are unaffected. Note the redraw is also what the constant-time assembly above depends on, since that rejects rather than reduces an operand at or past the modulus.
172173

173174
### 2.1.3 Additional Features and Functionality

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

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -117,24 +117,35 @@ static X448PrivateKeyParameters getX448PrivateKey(byte[] keyData)
117117
return new X448PrivateKeyParameters(keyData, 0);
118118
}
119119

120+
private static final BigInteger X25519_P = BigIntegers.ONE.shiftLeft(255).subtract(BigInteger.valueOf(19));
121+
private static final BigInteger X448_P = BigIntegers.ONE.shiftLeft(448).subtract(BigIntegers.ONE.shiftLeft(224)).subtract(BigIntegers.ONE);
122+
120123
static X25519PublicKeyParameters getX25519PublicKey(BigInteger u)
121124
throws InvalidKeyException
122125
{
123-
return new X25519PublicKeyParameters(getXDHPublicKeyData(X25519PublicKeyParameters.KEY_SIZE, u), 0);
126+
return new X25519PublicKeyParameters(getXDHPublicKeyData(X25519PublicKeyParameters.KEY_SIZE, X25519_P, u), 0);
124127
}
125128

126129
static X448PublicKeyParameters getX448PublicKey(BigInteger u)
127130
throws InvalidKeyException
128131
{
129-
return new X448PublicKeyParameters(getXDHPublicKeyData(X448PublicKeyParameters.KEY_SIZE, u), 0);
132+
return new X448PublicKeyParameters(getXDHPublicKeyData(X448PublicKeyParameters.KEY_SIZE, X448_P, u), 0);
130133
}
131134

132-
private static byte[] getXDHPublicKeyData(int length, BigInteger u)
135+
private static byte[] getXDHPublicKeyData(int length, BigInteger p, BigInteger u)
133136
throws InvalidKeyException
134137
{
138+
if (u.signum() < 0)
139+
{
140+
throw new InvalidKeyException("cannot use XEC public key with negative U value");
141+
}
142+
135143
try
136144
{
137-
return Arrays.reverseInPlace(BigIntegers.asUnsignedByteArray(length, u));
145+
// RFC 7748 sec. 5 requires a u at or past the field prime to be accepted and processed
146+
// as though it had been reduced, so reduce rather than reject; a conforming key or spec
147+
// carries a value already below p, for which this does nothing
148+
return Arrays.reverseInPlace(BigIntegers.asUnsignedByteArray(length, u.mod(p)));
138149
}
139150
catch (RuntimeException e)
140151
{

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

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -131,8 +131,13 @@ else if (spec.isAssignableFrom(RawEncodedKeySpec.class))
131131
}
132132
else
133133
{
134-
// on JDK 15+ the EdDSAKeys twin also serves the standard EdEC key specs here.
134+
// on JDK 15+ the EdDSAKeys twin also serves the standard EdEC key specs here, and
135+
// on JDK 11+ the XDHKeys twin the standard XEC ones.
135136
KeySpec versionSpec = EdDSAKeys.getKeySpec(key, spec);
137+
if (versionSpec == null)
138+
{
139+
versionSpec = XDHKeys.getKeySpec(key, spec);
140+
}
136141
if (versionSpec != null)
137142
{
138143
return versionSpec;
@@ -167,8 +172,13 @@ protected PrivateKey engineGeneratePrivate(
167172
throw new InvalidKeySpecException("openssh private key not Ed25519 private key");
168173
}
169174

170-
// on JDK 15+ the EdDSAKeys twin also serves the standard EdECPrivateKeySpec here.
175+
// on JDK 15+ the EdDSAKeys twin also serves the standard EdECPrivateKeySpec here, and
176+
// on JDK 11+ the XDHKeys twin the standard XECPrivateKeySpec.
171177
PrivateKey versionKey = EdDSAKeys.generatePrivate(keySpec);
178+
if (versionKey == null)
179+
{
180+
versionKey = XDHKeys.generatePrivate(keySpec);
181+
}
172182
if (versionKey != null)
173183
{
174184
return versionKey;
@@ -268,8 +278,13 @@ else if (keySpec instanceof OpenSSHPublicKeySpec)
268278
throw new InvalidKeySpecException("openssh public key not Ed25519 public key");
269279
}
270280

271-
// on JDK 15+ the EdDSAKeys twin also serves the standard EdECPublicKeySpec here.
281+
// on JDK 15+ the EdDSAKeys twin also serves the standard EdECPublicKeySpec here, and
282+
// on JDK 11+ the XDHKeys twin the standard XECPublicKeySpec.
272283
PublicKey versionKey = EdDSAKeys.generatePublic(keySpec);
284+
if (versionKey == null)
285+
{
286+
versionKey = XDHKeys.generatePublic(keySpec);
287+
}
273288
if (versionKey != null)
274289
{
275290
return versionKey;

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@
22

33
import java.io.IOException;
44
import java.security.InvalidKeyException;
5+
import java.security.Key;
56
import java.security.PrivateKey;
67
import java.security.PublicKey;
78
import java.security.spec.InvalidKeySpecException;
9+
import java.security.spec.KeySpec;
810

911
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
1012
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
@@ -58,4 +60,34 @@ static AsymmetricKeyParameter generatePublicKeyParameter(PublicKey key)
5860
{
5961
return EdECUtil.generatePublicKeyParameter(key);
6062
}
63+
64+
/**
65+
* Return a KeySpec for a version-specific spec type - on JDK 11+ the XEC key specs -
66+
* or null when the request is not one this JDK version bridges.
67+
*/
68+
static KeySpec getKeySpec(Key key, Class<?> spec)
69+
throws InvalidKeySpecException
70+
{
71+
return null;
72+
}
73+
74+
/**
75+
* Generate a private key from a version-specific KeySpec - on JDK 11+ the
76+
* XECPrivateKeySpec - or return null when the spec is not one this JDK version bridges.
77+
*/
78+
static PrivateKey generatePrivate(KeySpec keySpec)
79+
throws InvalidKeySpecException
80+
{
81+
return null;
82+
}
83+
84+
/**
85+
* Generate a public key from a version-specific KeySpec - on JDK 11+ the
86+
* XECPublicKeySpec - or return null when the spec is not one this JDK version bridges.
87+
*/
88+
static PublicKey generatePublic(KeySpec keySpec)
89+
throws InvalidKeySpecException
90+
{
91+
return null;
92+
}
6193
}

0 commit comments

Comments
 (0)