Skip to content

Commit 374272f

Browse files
author
Anthony Scarpino
committedMar 25, 2021
8261502: ECDHKeyAgreement: Allows alternate ECPrivateKey impl and revised exception handling
Reviewed-by: jnimeh
1 parent dbc9e4b commit 374272f

File tree

2 files changed

+171
-66
lines changed

2 files changed

+171
-66
lines changed
 

‎src/jdk.crypto.ec/share/classes/sun/security/ec/ECDHKeyAgreement.java

+83-66
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright (c) 2009, 2020, Oracle and/or its affiliates. All rights reserved.
2+
* Copyright (c) 2009, 2021, Oracle and/or its affiliates. All rights reserved.
33
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
44
*
55
* This code is free software; you can redistribute it and/or modify it
@@ -25,21 +25,33 @@
2525

2626
package sun.security.ec;
2727

28-
import java.math.*;
29-
import java.security.*;
30-
import java.security.interfaces.*;
31-
import java.security.spec.*;
32-
import java.util.Optional;
33-
34-
import javax.crypto.*;
35-
import javax.crypto.spec.*;
36-
28+
import sun.security.ec.point.AffinePoint;
29+
import sun.security.ec.point.Point;
3730
import sun.security.util.ArrayUtil;
3831
import sun.security.util.CurveDB;
39-
import sun.security.util.ECUtil;
4032
import sun.security.util.NamedCurve;
41-
import sun.security.util.math.*;
42-
import sun.security.ec.point.*;
33+
import sun.security.util.math.ImmutableIntegerModuloP;
34+
import sun.security.util.math.IntegerFieldModuloP;
35+
import sun.security.util.math.MutableIntegerModuloP;
36+
import sun.security.util.math.SmallValue;
37+
38+
import javax.crypto.KeyAgreementSpi;
39+
import javax.crypto.SecretKey;
40+
import javax.crypto.ShortBufferException;
41+
import javax.crypto.spec.SecretKeySpec;
42+
import java.math.BigInteger;
43+
import java.security.InvalidAlgorithmParameterException;
44+
import java.security.InvalidKeyException;
45+
import java.security.Key;
46+
import java.security.NoSuchAlgorithmException;
47+
import java.security.PrivateKey;
48+
import java.security.SecureRandom;
49+
import java.security.interfaces.ECPrivateKey;
50+
import java.security.interfaces.ECPublicKey;
51+
import java.security.spec.AlgorithmParameterSpec;
52+
import java.security.spec.ECParameterSpec;
53+
import java.security.spec.EllipticCurve;
54+
import java.util.Optional;
4355

4456
/**
4557
* KeyAgreement implementation for ECDH.
@@ -50,6 +62,7 @@ public final class ECDHKeyAgreement extends KeyAgreementSpi {
5062

5163
// private key, if initialized
5264
private ECPrivateKey privateKey;
65+
ECOperations privateKeyOps;
5366

5467
// public key, non-null between doPhase() & generateSecret() only
5568
private ECPublicKey publicKey;
@@ -63,16 +76,34 @@ public final class ECDHKeyAgreement extends KeyAgreementSpi {
6376
public ECDHKeyAgreement() {
6477
}
6578

79+
// Generic init
80+
private void init(Key key) throws
81+
InvalidKeyException, InvalidAlgorithmParameterException {
82+
if (!(key instanceof PrivateKey)) {
83+
throw new InvalidKeyException("Key must be instance of PrivateKey");
84+
}
85+
privateKey = (ECPrivateKey)ECKeyFactory.toECKey(key);
86+
publicKey = null;
87+
Optional<ECOperations> opsOpt =
88+
ECOperations.forParameters(privateKey.getParams());
89+
if (opsOpt.isEmpty()) {
90+
NamedCurve nc = CurveDB.lookup(privateKey.getParams());
91+
throw new InvalidAlgorithmParameterException(
92+
"Curve not supported: " + (nc != null ? nc.toString() :
93+
"unknown"));
94+
}
95+
privateKeyOps = opsOpt.get();
96+
}
97+
6698
// see JCE spec
6799
@Override
68100
protected void engineInit(Key key, SecureRandom random)
69101
throws InvalidKeyException {
70-
if (!(key instanceof PrivateKey)) {
71-
throw new InvalidKeyException
72-
("Key must be instance of PrivateKey");
102+
try {
103+
init(key);
104+
} catch (InvalidAlgorithmParameterException e) {
105+
throw new InvalidKeyException(e);
73106
}
74-
privateKey = (ECPrivateKey) ECKeyFactory.toECKey(key);
75-
publicKey = null;
76107
}
77108

78109
// see JCE spec
@@ -84,7 +115,7 @@ protected void engineInit(Key key, AlgorithmParameterSpec params,
84115
throw new InvalidAlgorithmParameterException
85116
("Parameters not supported");
86117
}
87-
engineInit(key, random);
118+
init(key);
88119
}
89120

90121
// see JCE spec
@@ -108,28 +139,34 @@ protected Key engineDoPhase(Key key, boolean lastPhase)
108139

109140
this.publicKey = (ECPublicKey) key;
110141

111-
ECParameterSpec params = publicKey.getParams();
112-
int keyLenBits = params.getCurve().getField().getFieldSize();
142+
int keyLenBits =
143+
publicKey.getParams().getCurve().getField().getFieldSize();
113144
secretLen = (keyLenBits + 7) >> 3;
114145

146+
// Validate public key
147+
validate(privateKeyOps, publicKey);
148+
115149
return null;
116150
}
117151

118-
private static void validateCoordinate(BigInteger c, BigInteger mod) {
152+
private static void validateCoordinate(BigInteger c, BigInteger mod)
153+
throws InvalidKeyException{
119154
if (c.compareTo(BigInteger.ZERO) < 0) {
120-
throw new ProviderException("invalid coordinate");
155+
throw new InvalidKeyException("Invalid coordinate");
121156
}
122157

123158
if (c.compareTo(mod) >= 0) {
124-
throw new ProviderException("invalid coordinate");
159+
throw new InvalidKeyException("Invalid coordinate");
125160
}
126161
}
127162

128163
/*
129-
* Check whether a public key is valid. Throw ProviderException
130-
* if it is not valid or could not be validated.
164+
* Check whether a public key is valid.
131165
*/
132-
private static void validate(ECOperations ops, ECPublicKey key) {
166+
private static void validate(ECOperations ops, ECPublicKey key)
167+
throws InvalidKeyException {
168+
169+
ECParameterSpec spec = key.getParams();
133170

134171
// ensure that integers are in proper range
135172
BigInteger x = key.getW().getAffineX();
@@ -140,23 +177,23 @@ private static void validate(ECOperations ops, ECPublicKey key) {
140177
validateCoordinate(y, p);
141178

142179
// ensure the point is on the curve
143-
EllipticCurve curve = key.getParams().getCurve();
180+
EllipticCurve curve = spec.getCurve();
144181
BigInteger rhs = x.modPow(BigInteger.valueOf(3), p).add(curve.getA()
145182
.multiply(x)).add(curve.getB()).mod(p);
146183
BigInteger lhs = y.modPow(BigInteger.valueOf(2), p).mod(p);
147184
if (!rhs.equals(lhs)) {
148-
throw new ProviderException("point is not on curve");
185+
throw new InvalidKeyException("Point is not on curve");
149186
}
150187

151188
// check the order of the point
152189
ImmutableIntegerModuloP xElem = ops.getField().getElement(x);
153190
ImmutableIntegerModuloP yElem = ops.getField().getElement(y);
154191
AffinePoint affP = new AffinePoint(xElem, yElem);
155-
byte[] order = key.getParams().getOrder().toByteArray();
192+
byte[] order = spec.getOrder().toByteArray();
156193
ArrayUtil.reverse(order);
157194
Point product = ops.multiply(affP, order);
158195
if (!ops.isNeutral(product)) {
159-
throw new ProviderException("point has incorrect order");
196+
throw new InvalidKeyException("Point has incorrect order");
160197
}
161198

162199
}
@@ -167,15 +204,13 @@ protected byte[] engineGenerateSecret() throws IllegalStateException {
167204
if ((privateKey == null) || (publicKey == null)) {
168205
throw new IllegalStateException("Not initialized correctly");
169206
}
207+
170208
byte[] result;
171-
Optional<byte[]> resultOpt = deriveKeyImpl(privateKey, publicKey);
172-
if (resultOpt.isEmpty()) {
173-
NamedCurve nc = CurveDB.lookup(publicKey.getParams());
174-
throw new IllegalStateException(
175-
new InvalidAlgorithmParameterException("Curve not supported: " +
176-
(nc != null ? nc.toString() : "unknown")));
209+
try {
210+
result = deriveKeyImpl(privateKey, privateKeyOps, publicKey);
211+
} catch (Exception e) {
212+
throw new IllegalStateException(e);
177213
}
178-
result = resultOpt.get();
179214
publicKey = null;
180215
return result;
181216
}
@@ -210,48 +245,30 @@ protected SecretKey engineGenerateSecret(String algorithm)
210245
}
211246

212247
private static
213-
Optional<byte[]> deriveKeyImpl(ECPrivateKey priv, ECPublicKey pubKey) {
214-
215-
ECParameterSpec ecSpec = priv.getParams();
216-
EllipticCurve curve = ecSpec.getCurve();
217-
Optional<ECOperations> opsOpt = ECOperations.forParameters(ecSpec);
218-
if (opsOpt.isEmpty()) {
219-
return Optional.empty();
220-
}
221-
ECOperations ops = opsOpt.get();
222-
if (! (priv instanceof ECPrivateKeyImpl)) {
223-
return Optional.empty();
224-
}
225-
ECPrivateKeyImpl privImpl = (ECPrivateKeyImpl) priv;
226-
byte[] sArr = privImpl.getArrayS();
227-
228-
// to match the native implementation, validate the public key here
229-
// and throw ProviderException if it is invalid
230-
validate(ops, pubKey);
248+
byte[] deriveKeyImpl(ECPrivateKey priv, ECOperations ops,
249+
ECPublicKey pubKey) throws InvalidKeyException {
231250

232251
IntegerFieldModuloP field = ops.getField();
233252
// convert s array into field element and multiply by the cofactor
234-
MutableIntegerModuloP scalar = field.getElement(sArr).mutable();
253+
MutableIntegerModuloP scalar = field.getElement(priv.getS()).mutable();
235254
SmallValue cofactor =
236255
field.getSmallValue(priv.getParams().getCofactor());
237256
scalar.setProduct(cofactor);
238-
int keySize = (curve.getField().getFieldSize() + 7) / 8;
239-
byte[] privArr = scalar.asByteArray(keySize);
240-
257+
int keySize =
258+
(priv.getParams().getCurve().getField().getFieldSize() + 7) / 8;
241259
ImmutableIntegerModuloP x =
242260
field.getElement(pubKey.getW().getAffineX());
243261
ImmutableIntegerModuloP y =
244262
field.getElement(pubKey.getW().getAffineY());
245-
AffinePoint affPub = new AffinePoint(x, y);
246-
Point product = ops.multiply(affPub, privArr);
263+
Point product = ops.multiply(new AffinePoint(x, y),
264+
scalar.asByteArray(keySize));
247265
if (ops.isNeutral(product)) {
248-
throw new ProviderException("Product is zero");
266+
throw new InvalidKeyException("Product is zero");
249267
}
250-
AffinePoint affProduct = product.asAffine();
251268

252-
byte[] result = affProduct.getX().asByteArray(keySize);
269+
byte[] result = product.asAffine().getX().asByteArray(keySize);
253270
ArrayUtil.reverse(result);
254271

255-
return Optional.of(result);
272+
return result;
256273
}
257274
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
/*
2+
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
3+
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4+
*
5+
* This code is free software; you can redistribute it and/or modify it
6+
* under the terms of the GNU General Public License version 2 only, as
7+
* published by the Free Software Foundation.
8+
*
9+
* This code is distributed in the hope that it will be useful, but WITHOUT
10+
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11+
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12+
* version 2 for more details (a copy is included in the LICENSE file that
13+
* accompanied this code).
14+
*
15+
* You should have received a copy of the GNU General Public License version
16+
* 2 along with this work; if not, write to the Free Software Foundation,
17+
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18+
*
19+
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20+
* or visit www.oracle.com if you need additional information or have any
21+
* questions.
22+
*/
23+
24+
/*
25+
* @test
26+
* @bug 8261502
27+
* @summary Check that ECPrivateKey's that are not ECPrivateKeyImpl can use
28+
* ECDHKeyAgreement
29+
*/
30+
31+
import javax.crypto.KeyAgreement;
32+
import java.math.BigInteger;
33+
import java.security.KeyPairGenerator;
34+
import java.security.interfaces.ECPrivateKey;
35+
import java.security.interfaces.ECPublicKey;
36+
import java.security.spec.ECGenParameterSpec;
37+
import java.security.spec.ECParameterSpec;
38+
39+
public class ECKeyCheck {
40+
41+
public static final void main(String args[]) throws Exception {
42+
ECGenParameterSpec spec = new ECGenParameterSpec("secp256r1");
43+
KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
44+
kpg.initialize(spec);
45+
46+
ECPrivateKey privKey = (ECPrivateKey) kpg.generateKeyPair().getPrivate();
47+
ECPublicKey pubKey = (ECPublicKey) kpg.generateKeyPair().getPublic();
48+
generateECDHSecret(privKey, pubKey);
49+
generateECDHSecret(new newPrivateKeyImpl(privKey), pubKey);
50+
}
51+
52+
private static byte[] generateECDHSecret(ECPrivateKey privKey,
53+
ECPublicKey pubKey) throws Exception {
54+
KeyAgreement ka = KeyAgreement.getInstance("ECDH");
55+
ka.init(privKey);
56+
ka.doPhase(pubKey, true);
57+
return ka.generateSecret();
58+
}
59+
60+
// Test ECPrivateKey class
61+
private static class newPrivateKeyImpl implements ECPrivateKey {
62+
private ECPrivateKey p;
63+
64+
newPrivateKeyImpl(ECPrivateKey p) {
65+
this.p = p;
66+
}
67+
68+
public BigInteger getS() {
69+
return p.getS();
70+
}
71+
72+
public byte[] getEncoded() {
73+
return p.getEncoded();
74+
}
75+
76+
public String getFormat() {
77+
return p.getFormat();
78+
}
79+
80+
public String getAlgorithm() {
81+
return p.getAlgorithm();
82+
}
83+
84+
public ECParameterSpec getParams() {
85+
return p.getParams();
86+
}
87+
}
88+
}

0 commit comments

Comments
 (0)
Please sign in to comment.