Initial working XDH support in TLS. I should try to refactor the code a bit.
--- a/src/java.base/share/classes/sun/security/ssl/KeyShareExtension.java Mon May 21 11:14:44 2018 -0400
+++ b/src/java.base/share/classes/sun/security/ssl/KeyShareExtension.java Tue May 22 13:44:02 2018 -0400
@@ -42,6 +42,8 @@
import sun.security.ssl.DHKeyExchange.DHEPossession;
import sun.security.ssl.ECDHKeyExchange.ECDHECredentials;
import sun.security.ssl.ECDHKeyExchange.ECDHEPossession;
+import sun.security.ssl.XDHKeyExchange.XDHEPossession;
+import sun.security.ssl.XDHKeyExchange.XDHECredentials;
import sun.security.ssl.KeyShareExtension.CHKeyShareSpec;
import sun.security.ssl.SSLExtension.ExtensionConsumer;
import sun.security.ssl.SSLExtension.SSLExtensionSpec;
@@ -265,7 +267,8 @@
// update the context
chc.handshakePossessions.add(pos);
if (!(pos instanceof ECDHEPossession) &&
- !(pos instanceof DHEPossession)) {
+ !(pos instanceof DHEPossession) &&
+ !(pos instanceof XDHEPossession)) {
// May need more possesion types in the future.
continue;
}
@@ -394,6 +397,26 @@
"Cannot decode named group: " +
NamedGroup.nameOf(entry.namedGroupId));
}
+ } else if (ng.type == NamedGroupType.NAMED_GROUP_XDH) {
+ try {
+ XDHECredentials xdhec =
+ XDHECredentials.valueOf(ng, entry.keyExchange);
+ if (xdhec != null) {
+ if (!shc.algorithmConstraints.permits(
+ EnumSet.of(CryptoPrimitive.KEY_AGREEMENT),
+ xdhec.popPublicKey)) {
+ SSLLogger.warning(
+ "XDHE key share entry does not " +
+ "comply to algorithm constraints");
+ } else {
+ credentials.add(xdhec);
+ }
+ }
+ } catch (IOException | GeneralSecurityException ex) {
+ SSLLogger.warning(
+ "Cannot decode named group: " +
+ NamedGroup.nameOf(entry.namedGroupId));
+ }
}
}
@@ -531,6 +554,8 @@
ng = ((ECDHECredentials)cd).namedGroup;
} else if (cd instanceof DHECredentials) {
ng = ((DHECredentials)cd).namedGroup;
+ } else if (cd instanceof XDHECredentials) {
+ ng = ((XDHECredentials)cd).namedGroup;
}
if (ng == null) {
@@ -549,7 +574,8 @@
SSLPossession[] poses = ke.createPossessions(shc);
for (SSLPossession pos : poses) {
if (!(pos instanceof ECDHEPossession) &&
- !(pos instanceof DHEPossession)) {
+ !(pos instanceof DHEPossession) &&
+ !(pos instanceof XDHEPossession)) {
// May need more possesion types in the future.
continue;
}
@@ -689,6 +715,26 @@
"Cannot decode named group: " +
NamedGroup.nameOf(keyShare.namedGroupId));
}
+ } else if (ng.type == NamedGroupType.NAMED_GROUP_XDH) {
+ try {
+ XDHECredentials xdhec =
+ XDHECredentials.valueOf(ng, keyShare.keyExchange);
+ if (xdhec != null) {
+ if (!chc.algorithmConstraints.permits(
+ EnumSet.of(CryptoPrimitive.KEY_AGREEMENT),
+ xdhec.popPublicKey)) {
+ chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE,
+ "XDHE key share entry does not " +
+ "comply to algorithm constraints");
+ } else {
+ credentials = xdhec;
+ }
+ }
+ } catch (IOException | GeneralSecurityException ex) {
+ chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE,
+ "Cannot decode named group: " +
+ NamedGroup.nameOf(keyShare.namedGroupId));
+ }
} else {
chc.conContext.fatal(Alert.UNEXPECTED_MESSAGE,
"Unsupported named group: " +
--- a/src/java.base/share/classes/sun/security/ssl/SSLKeyExchange.java Mon May 21 11:14:44 2018 -0400
+++ b/src/java.base/share/classes/sun/security/ssl/SSLKeyExchange.java Tue May 22 13:44:02 2018 -0400
@@ -32,6 +32,7 @@
import java.util.Map;
import sun.security.ssl.DHKeyExchange.DHEPossession;
import sun.security.ssl.ECDHKeyExchange.ECDHEPossession;
+import sun.security.ssl.XDHKeyExchange.XDHEPossession;
import sun.security.ssl.SupportedGroupsExtension.NamedGroup;
import sun.security.ssl.SupportedGroupsExtension.NamedGroupType;
import sun.security.ssl.SupportedGroupsExtension.SupportedGroups;
@@ -564,6 +565,9 @@
} else if (namedGroup.type == NamedGroupType.NAMED_GROUP_FFDHE) {
return new DHEPossession(
namedGroup, hc.sslContext.getSecureRandom());
+ } else if (namedGroup.type == NamedGroupType.NAMED_GROUP_XDH) {
+ return new XDHEPossession(
+ namedGroup, hc.sslContext.getSecureRandom());
}
return null;
@@ -576,6 +580,8 @@
return ECDHKeyExchange.ecdheKAGenerator.createKeyDerivation(hc);
} else if (namedGroup.type == NamedGroupType.NAMED_GROUP_FFDHE) {
return DHKeyExchange.kaGenerator.createKeyDerivation(hc);
+ } else if (namedGroup.type == NamedGroupType.NAMED_GROUP_XDH) {
+ return XDHKeyExchange.xdheKAGenerator.createKeyDerivation(hc);
}
return null;
--- a/src/java.base/share/classes/sun/security/ssl/SupportedGroupsExtension.java Mon May 21 11:14:44 2018 -0400
+++ b/src/java.base/share/classes/sun/security/ssl/SupportedGroupsExtension.java Tue May 22 13:44:02 2018 -0400
@@ -36,6 +36,7 @@
import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECParameterSpec;
import java.security.spec.InvalidParameterSpecException;
+import java.security.spec.NamedParameterSpec;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
@@ -454,6 +455,8 @@
return SupportedGroups.getECGenParamSpec(this);
} else if (this.type == NamedGroupType.NAMED_GROUP_FFDHE) {
return SupportedGroups.getDHParameterSpec(this);
+ } else if (this.type == NamedGroupType.NAMED_GROUP_XDH) {
+ return new NamedParameterSpec(this.algorithm);
}
return null;
@@ -552,6 +555,10 @@
// non-NIST curves
NamedGroup.SECP256_K1,
+ // XDH
+ NamedGroup.X25519,
+ NamedGroup.X448,
+
// FFDHE 2048
NamedGroup.FFDHE_2048,
NamedGroup.FFDHE_3072,
@@ -601,6 +608,14 @@
} catch (NoSuchAlgorithmException e) {
return false;
}
+ } else if (namedGroup.type == NamedGroupType.NAMED_GROUP_XDH) {
+ try {
+ JsseJce.getKeyAgreement(namedGroup.algorithm);
+ // no parameters
+ return true;
+ } catch (NoSuchAlgorithmException e) {
+ return false;
+ }
} // Otherwise, unsupported.
if ((params != null) && (spec != null)) {
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/sun/security/ssl/XDHKeyExchange.java Tue May 22 13:44:02 2018 -0400
@@ -0,0 +1,478 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.security.ssl;
+
+import java.io.IOException;
+import java.security.AlgorithmConstraints;
+import java.security.CryptoPrimitive;
+import java.security.GeneralSecurityException;
+import java.security.KeyFactory;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.SecureRandom;
+import java.security.interfaces.XECPrivateKey;
+import java.security.interfaces.XECPublicKey;
+import java.security.spec.*;
+import java.util.EnumSet;
+import javax.crypto.KeyAgreement;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.SecretKeySpec;
+import javax.net.ssl.SSLHandshakeException;
+import sun.security.ssl.CipherSuite.HashAlg;
+import sun.security.ssl.SupportedGroupsExtension.NamedGroup;
+import sun.security.ssl.SupportedGroupsExtension.NamedGroupType;
+import sun.security.ssl.SupportedGroupsExtension.SupportedGroups;
+import sun.security.ssl.X509Authentication.X509Credentials;
+import sun.security.ssl.X509Authentication.X509Possession;
+import sun.security.util.ECUtil;
+
+final class XDHKeyExchange {
+ static final SSLPossessionGenerator poGenerator =
+ new XDHEPossessionGenerator();
+ static final SSLKeyAgreementGenerator xdheKAGenerator =
+ new XDHEKAGenerator();
+ static final SSLKeyAgreementGenerator xdhKAGenerator =
+ new XDHKAGenerator();
+
+ static final class XDHECredentials implements SSLCredentials {
+ final XECPublicKey popPublicKey;
+ final NamedGroup namedGroup;
+
+ XDHECredentials(XECPublicKey popPublicKey, NamedGroup namedGroup) {
+ this.popPublicKey = popPublicKey;
+ this.namedGroup = namedGroup;
+ }
+
+ static XDHECredentials valueOf(NamedGroup namedGroup,
+ byte[] encodedPoint) throws IOException, GeneralSecurityException {
+
+ if (namedGroup.type != NamedGroupType.NAMED_GROUP_XDH) {
+ throw new RuntimeException(
+ "Credentials decoding: Not XDH named group");
+ }
+
+ if (encodedPoint == null || encodedPoint.length == 0) {
+ return null;
+ }
+
+ NamedParameterSpec namedSpec = new NamedParameterSpec(namedGroup.algorithm);
+ XECPublicKeySpec xecKeySpec = ECUtil.decodeXecPublicKey(encodedPoint, namedSpec);
+ KeyFactory factory = JsseJce.getKeyFactory(namedGroup.algorithm);
+
+ XECPublicKey publicKey = (XECPublicKey)factory.generatePublic(xecKeySpec);
+ return new XDHECredentials(publicKey, namedGroup);
+ }
+ }
+
+ static final class XDHEPossession implements SSLPossession {
+ final PrivateKey privateKey;
+ final XECPublicKey publicKey;
+ final NamedGroup namedGroup;
+
+ XDHEPossession(NamedGroup namedGroup, SecureRandom random) {
+ try {
+ KeyPairGenerator kpg = JsseJce.getKeyPairGenerator(namedGroup.algorithm);
+ AlgorithmParameterSpec params = namedGroup.getParameterSpec();
+ kpg.initialize(params, random);
+ KeyPair kp = kpg.generateKeyPair();
+ privateKey = kp.getPrivate();
+ publicKey = (XECPublicKey)kp.getPublic();
+ } catch (GeneralSecurityException e) {
+ throw new RuntimeException(
+ "Could not generate XDH keypair", e);
+ }
+
+ this.namedGroup = namedGroup;
+ }
+
+ XDHEPossession(XDHECredentials credentials, SecureRandom random) {
+ AlgorithmParameterSpec params = credentials.popPublicKey.getParams();
+ try {
+ KeyPairGenerator kpg = JsseJce.getKeyPairGenerator(credentials.namedGroup.algorithm);
+ kpg.initialize(params, random);
+ KeyPair kp = kpg.generateKeyPair();
+ privateKey = kp.getPrivate();
+ publicKey = (XECPublicKey)kp.getPublic();
+ } catch (GeneralSecurityException e) {
+ throw new RuntimeException(
+ "Could not generate XDH keypair", e);
+ }
+
+ this.namedGroup = credentials.namedGroup;
+ }
+
+ @Override
+ public byte[] encode() {
+ try {
+ return ECUtil.encodeXecPublicKey(publicKey.getU(), publicKey.getParams());
+ } catch (InvalidParameterSpecException ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+
+ // called by client handshaker
+ SecretKey getAgreedSecret(
+ PublicKey peerPublicKey) throws SSLHandshakeException {
+
+ try {
+ KeyAgreement ka = JsseJce.getKeyAgreement("XDH");
+ ka.init(privateKey);
+ ka.doPhase(peerPublicKey, true);
+ return ka.generateSecret("TlsPremasterSecret");
+ } catch (GeneralSecurityException e) {
+ throw (SSLHandshakeException) new SSLHandshakeException(
+ "Could not generate secret").initCause(e);
+ }
+ }
+
+ // called by ServerHandshaker
+ SecretKey getAgreedSecret(
+ byte[] encodedKey) throws SSLHandshakeException {
+ try {
+ AlgorithmParameterSpec params = publicKey.getParams();
+
+ KeyFactory kf = JsseJce.getKeyFactory("XDH");
+ XECPublicKeySpec spec = ECUtil.decodeXecPublicKey(encodedKey, params);
+ PublicKey peerPublicKey = kf.generatePublic(spec);
+ return getAgreedSecret(peerPublicKey);
+ } catch (GeneralSecurityException | java.io.IOException e) {
+ throw (SSLHandshakeException) new SSLHandshakeException(
+ "Could not generate secret").initCause(e);
+ }
+ }
+
+ // Check constraints of the specified EC public key.
+ void checkConstraints(AlgorithmConstraints constraints,
+ byte[] encodedKey) throws SSLHandshakeException {
+ try {
+
+ AlgorithmParameterSpec params = publicKey.getParams();
+ XECPublicKeySpec spec = ECUtil.decodeXecPublicKey(encodedKey, params);
+
+ KeyFactory kf = JsseJce.getKeyFactory("XDH");
+ PublicKey pubKey = kf.generatePublic(spec);
+
+ // check constraints of ECPublicKey
+ if (!constraints.permits(
+ EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), pubKey)) {
+ throw new SSLHandshakeException(
+ "ECPublicKey does not comply to algorithm constraints");
+ }
+ } catch (GeneralSecurityException | java.io.IOException e) {
+ throw (SSLHandshakeException) new SSLHandshakeException(
+ "Could not generate ECPublicKey").initCause(e);
+ }
+ }
+ }
+
+ private static final
+ class XDHEPossessionGenerator implements SSLPossessionGenerator {
+ // Prevent instantiation of this class.
+ private XDHEPossessionGenerator() {
+ // blank
+ }
+
+ @Override
+ public SSLPossession createPossession(HandshakeContext context) {
+ NamedGroup preferableNamedGroup = null;
+ if ((context.clientRequestedNamedGroups != null) &&
+ (!context.clientRequestedNamedGroups.isEmpty())) {
+ preferableNamedGroup = SupportedGroups.getPreferredGroup(
+ context.negotiatedProtocol,
+ context.algorithmConstraints,
+ NamedGroupType.NAMED_GROUP_XDH,
+ context.clientRequestedNamedGroups);
+ } else {
+ preferableNamedGroup = SupportedGroups.getPreferredGroup(
+ context.negotiatedProtocol,
+ context.algorithmConstraints,
+ NamedGroupType.NAMED_GROUP_XDH);
+ }
+
+ if (preferableNamedGroup != null) {
+ return new XDHEPossession(preferableNamedGroup,
+ context.sslContext.getSecureRandom());
+ }
+
+ // no match found, cannot use this cipher suite.
+ //
+ return null;
+ }
+ }
+
+ private static final
+ class XDHKAGenerator implements SSLKeyAgreementGenerator {
+ // Prevent instantiation of this class.
+ private XDHKAGenerator() {
+ // blank
+ }
+
+ @Override
+ public SSLKeyDerivation createKeyDerivation(
+ HandshakeContext context) throws IOException {
+ if (context instanceof ServerHandshakeContext) {
+ return createServerKeyDerivation(
+ (ServerHandshakeContext)context);
+ } else {
+ return createClientKeyDerivation(
+ (ClientHandshakeContext)context);
+ }
+ }
+
+ private SSLKeyDerivation createServerKeyDerivation(
+ ServerHandshakeContext shc) throws IOException {
+ X509Possession x509Possession = null;
+ XDHECredentials xdheCredentials = null;
+ for (SSLPossession poss : shc.handshakePossessions) {
+ if (!(poss instanceof X509Possession)) {
+ continue;
+ }
+
+ PrivateKey privateKey = ((X509Possession)poss).popPrivateKey;
+ if (! (privateKey instanceof XECPrivateKey)) {
+ continue;
+ }
+ AlgorithmParameterSpec params = ((XECPrivateKey)privateKey).getParams();
+ // group must be specified by name
+ if (!(params instanceof NamedParameterSpec)) {
+ continue;
+ }
+ NamedParameterSpec namedParams = (NamedParameterSpec) params;
+ NamedGroup ng = NamedGroup.valueOf(namedParams.getName());
+ if (ng == null) {
+ // unlikely, have been checked during cipher suite negotiation.
+ shc.conContext.fatal(Alert.ILLEGAL_PARAMETER,
+ "Unsupported server cert for XDH key exchange");
+ }
+
+ for (SSLCredentials cred : shc.handshakeCredentials) {
+ if (!(cred instanceof XDHECredentials)) {
+ continue;
+ }
+ if (ng.equals(((XDHECredentials)cred).namedGroup)) {
+ xdheCredentials = (XDHECredentials)cred;
+ break;
+ }
+ }
+
+ if (xdheCredentials != null) {
+ x509Possession = (X509Possession)poss;
+ break;
+ }
+ }
+
+ if (x509Possession == null || xdheCredentials == null) {
+ shc.conContext.fatal(Alert.HANDSHAKE_FAILURE,
+ "No sufficient XDHE key agreement parameters negotiated");
+ }
+
+ return new XDHEKAKeyDerivation(shc,
+ x509Possession.popPrivateKey, xdheCredentials.popPublicKey);
+ }
+
+ private SSLKeyDerivation createClientKeyDerivation(
+ ClientHandshakeContext chc) throws IOException {
+
+ XDHEPossession xdhePossession = null;
+ X509Credentials x509Credentials = null;
+ for (SSLPossession poss : chc.handshakePossessions) {
+ if (!(poss instanceof XDHEPossession)) {
+ continue;
+ }
+
+ NamedGroup ng = ((XDHEPossession)poss).namedGroup;
+ for (SSLCredentials cred : chc.handshakeCredentials) {
+ if (!(cred instanceof X509Credentials)) {
+ continue;
+ }
+
+ PublicKey publicKey = ((X509Credentials)cred).popPublicKey;
+ if (!(publicKey instanceof XECPublicKey)) {
+ continue;
+ }
+ XECPublicKey xecPublicKey = (XECPublicKey) publicKey;
+ AlgorithmParameterSpec params = xecPublicKey.getParams();
+ // group must be specified by name
+ if (!(params instanceof NamedParameterSpec)) {
+ continue;
+ }
+ NamedParameterSpec namedParams = (NamedParameterSpec) params;
+
+ NamedGroup namedGroup = NamedGroup.valueOf(namedParams.getName());
+ if (namedGroup == null) {
+ // unlikely, should have been checked previously
+ chc.conContext.fatal(Alert.ILLEGAL_PARAMETER,
+ "Unsupported EC server cert for XDH key exchange");
+ }
+
+ if (ng.equals(namedGroup)) {
+ x509Credentials = (X509Credentials)cred;
+ break;
+ }
+ }
+
+ if (x509Credentials != null) {
+ xdhePossession = (XDHEPossession)poss;
+ break;
+ }
+ }
+
+ if (xdhePossession == null || x509Credentials == null) {
+ chc.conContext.fatal(Alert.HANDSHAKE_FAILURE,
+ "No sufficient XDH key agreement parameters negotiated");
+ }
+
+ return new XDHEKAKeyDerivation(chc,
+ xdhePossession.privateKey, x509Credentials.popPublicKey);
+ }
+ }
+
+ private static final
+ class XDHEKAGenerator implements SSLKeyAgreementGenerator {
+ // Prevent instantiation of this class.
+ private XDHEKAGenerator() {
+ // blank
+ }
+
+ @Override
+ public SSLKeyDerivation createKeyDerivation(
+ HandshakeContext context) throws IOException {
+ XDHEPossession xdhePossession = null;
+ XDHECredentials xdheCredentials = null;
+ for (SSLPossession poss : context.handshakePossessions) {
+ if (!(poss instanceof XDHEPossession)) {
+ continue;
+ }
+
+ NamedGroup ng = ((XDHEPossession)poss).namedGroup;
+ for (SSLCredentials cred : context.handshakeCredentials) {
+ if (!(cred instanceof XDHECredentials)) {
+ continue;
+ }
+ if (ng.equals(((XDHECredentials)cred).namedGroup)) {
+ xdheCredentials = (XDHECredentials)cred;
+ break;
+ }
+ }
+
+ if (xdheCredentials != null) {
+ xdhePossession = (XDHEPossession)poss;
+ break;
+ }
+ }
+
+ if (xdhePossession == null || xdheCredentials == null) {
+ context.conContext.fatal(Alert.HANDSHAKE_FAILURE,
+ "No sufficient XDHE key agreement parameters negotiated");
+ }
+
+ return new XDHEKAKeyDerivation(context,
+ xdhePossession.privateKey, xdheCredentials.popPublicKey);
+ }
+ }
+
+ private static final
+ class XDHEKAKeyDerivation implements SSLKeyDerivation {
+ private final HandshakeContext context;
+ private final PrivateKey localPrivateKey;
+ private final PublicKey peerPublicKey;
+
+ XDHEKAKeyDerivation(HandshakeContext context,
+ PrivateKey localPrivateKey,
+ PublicKey peerPublicKey) {
+ this.context = context;
+ this.localPrivateKey = localPrivateKey;
+ this.peerPublicKey = peerPublicKey;
+ }
+
+ @Override
+ public SecretKey deriveKey(String algorithm,
+ AlgorithmParameterSpec params) throws IOException {
+ if (!context.negotiatedProtocol.useTLS13PlusSpec()) {
+ return t12DeriveKey(algorithm, params);
+ } else {
+ return t13DeriveKey(algorithm, params);
+ }
+ }
+
+ private SecretKey t12DeriveKey(String algorithm,
+ AlgorithmParameterSpec params) throws IOException {
+ try {
+ KeyAgreement ka = JsseJce.getKeyAgreement("XDH");
+ ka.init(localPrivateKey);
+ ka.doPhase(peerPublicKey, true);
+ SecretKey preMasterSecret =
+ ka.generateSecret("TlsPremasterSecret");
+
+ SSLMasterKeyDerivation mskd =
+ SSLMasterKeyDerivation.valueOf(
+ context.negotiatedProtocol);
+ SSLKeyDerivation kd = mskd.createKeyDerivation(
+ context, preMasterSecret);
+ return kd.deriveKey("TODO", params);
+ } catch (GeneralSecurityException gse) {
+ throw (SSLHandshakeException) new SSLHandshakeException(
+ "Could not generate secret").initCause(gse);
+ }
+ }
+
+ private SecretKey t13DeriveKey(String algorithm,
+ AlgorithmParameterSpec params) throws IOException {
+ try {
+ KeyAgreement ka = JsseJce.getKeyAgreement("XDH");
+ ka.init(localPrivateKey);
+ ka.doPhase(peerPublicKey, true);
+ SecretKey sharedSecret =
+ ka.generateSecret("TlsPremasterSecret");
+
+ HashAlg hashAlg = context.negotiatedCipherSuite.hashAlg;
+ SSLKeyDerivation kd = context.handshakeKeyDerivation;
+ HKDF hkdf = new HKDF(hashAlg.name);
+ if (kd == null) { // No PSK is in use.
+ // If PSK is not in use Early Secret will still be
+ // HKDF-Extract(0, 0).
+ byte[] zeros = new byte[hashAlg.hashLength];
+ SecretKeySpec ikm =
+ new SecretKeySpec(zeros, "TlsPreSharedSecret");
+ SecretKey earlySecret =
+ hkdf.extract(zeros, ikm, "TlsEarlySecret");
+ kd = new SSLSecretDerivation(context, earlySecret);
+ }
+
+ // derive salt secret
+ SecretKey saltSecret = kd.deriveKey("TlsSaltSecret", null);
+
+ // derive handshake secret
+ return hkdf.extract(saltSecret, sharedSecret, algorithm);
+ } catch (GeneralSecurityException gse) {
+ throw (SSLHandshakeException) new SSLHandshakeException(
+ "Could not generate secret").initCause(gse);
+ }
+ }
+ }
+}
--- a/src/java.base/share/classes/sun/security/util/ECUtil.java Mon May 21 11:14:44 2018 -0400
+++ b/src/java.base/share/classes/sun/security/util/ECUtil.java Tue May 22 13:44:02 2018 -0400
@@ -227,5 +227,65 @@
return nameSpec.getName();
}
+ public static BigInteger decodeXecPublicKey(byte[] key,
+ XECParameters params) {
+
+ reverse(key);
+
+ // clear the extra bits
+ int bitsMod8 = params.getBits() % 8;
+ if (bitsMod8 != 0) {
+ int mask = (1 << bitsMod8) - 1;
+ key[0] &= mask;
+ }
+
+ return new BigInteger(1, key);
+ }
+
+ public static XECPublicKeySpec decodeXecPublicKey(byte[] key,
+ AlgorithmParameterSpec spec)
+ throws InvalidParameterSpecException {
+
+ XECParameters params = XECParameters.get(
+ InvalidParameterSpecException::new, spec);
+ BigInteger u = decodeXecPublicKey(key, params);
+ return new XECPublicKeySpec(spec, u);
+ }
+
+ public static byte[] encodeXecPublicKey(BigInteger u,
+ XECParameters params) {
+
+ byte[] u_arr = u.toByteArray();
+ ECUtil.reverse(u_arr);
+ // u_arr may be too large or too small, depending on the value of u
+ return Arrays.copyOf(u_arr, params.getBytes());
+ }
+
+ public static byte[] encodeXecPublicKey(BigInteger u,
+ AlgorithmParameterSpec spec)
+ throws InvalidParameterSpecException {
+
+ XECParameters params = XECParameters.get(
+ InvalidParameterSpecException::new, spec);
+ return encodeXecPublicKey(u, params);
+ }
+
+ private static void swap(byte[] arr, int i, int j) {
+ byte tmp = arr[i];
+ arr[i] = arr[j];
+ arr[j] = tmp;
+ }
+
+ public static void reverse(byte [] arr) {
+ int i = 0;
+ int j = arr.length - 1;
+
+ while (i < j) {
+ swap(arr, i, j);
+ i++;
+ j--;
+ }
+ }
+
private ECUtil() {}
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/java.base/share/classes/sun/security/util/XECParameters.java Tue May 22 13:44:02 2018 -0400
@@ -0,0 +1,263 @@
+/*
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.security.util;
+
+import java.io.IOException;
+import java.math.BigInteger;
+import java.security.spec.AlgorithmParameterSpec;
+import java.security.spec.NamedParameterSpec;
+import java.util.Collections;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.Optional;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+import sun.security.util.ObjectIdentifier;
+import sun.security.x509.AlgorithmId;
+
+public class XECParameters {
+
+ // Naming/identification parameters
+ private final ObjectIdentifier oid;
+ private final String name;
+
+ // Curve/field parameters
+ private final int bits;
+ private final BigInteger p;
+ private final int logCofactor;
+ private final int a24;
+ private final byte basePoint;
+
+ /**
+ *
+ * Construct an object holding the supplied parameters. No parameters are
+ * checked, so this method always succeeds. This method supports
+ * Montgomery curves of the form y^2 = x^3 + ax^2 + x.
+ *
+ * @param bits The number of relevant bits in a public/private key.
+ * @param p The prime that defines the finite field.
+ * @param a24 The value of (a - 2) / 4, where a is the second-degree curve
+ * coefficient.
+ * @param basePoint The point that generates the desired group
+ * @param logCofactor The base-2 logarithm of the cofactor of the curve
+ * @param oid
+ * @param name
+ */
+ public XECParameters(int bits, BigInteger p, int a24,
+ byte basePoint, int logCofactor,
+ ObjectIdentifier oid, String name) {
+
+ this.bits = bits;
+ this.logCofactor = logCofactor;
+ this.p = p;
+ this.a24 = a24;
+ this.basePoint = basePoint;
+ this.oid = oid;
+ this.name = name;
+
+ }
+
+ public int getBits() {
+ return bits;
+ }
+ public int getBytes() {
+ return (bits + 7) / 8;
+ }
+ public int getLogCofactor() {
+ return logCofactor;
+ }
+ public BigInteger getP() {
+ return p;
+ }
+ public int getA24() {
+ return a24;
+ }
+ public byte getBasePoint() {
+ return basePoint;
+ }
+ public ObjectIdentifier getOid() {
+ return oid;
+ }
+ public String getName() {
+ return name;
+ }
+
+ private static final Map<Integer, XECParameters> SIZE_MAP;
+ private static final Map<ObjectIdentifier, XECParameters> OID_MAP;
+ private static final Map<String, XECParameters> NAME_MAP;
+
+ static {
+ final BigInteger TWO = BigInteger.valueOf(2);
+
+ Map<Integer, XECParameters> bySize = new HashMap<>();
+ Map<ObjectIdentifier, XECParameters> byOid = new HashMap<>();
+ Map<String, XECParameters> byName = new HashMap<>();
+
+ // set up X25519
+ try {
+ BigInteger p = TWO.pow(255).subtract(BigInteger.valueOf(19));
+ addParameters(255, p, 121665, (byte) 0x09, 3,
+ new int[]{1, 3, 101, 110}, NamedParameterSpec.X25519.getName(),
+ bySize, byOid, byName);
+
+ } catch (IOException ex) {
+ // Unable to set X25519 parameters---it will be disabled
+ }
+
+ // set up X448
+ try {
+ BigInteger p = TWO.pow(448).subtract(TWO.pow(224))
+ .subtract(BigInteger.ONE);
+ addParameters(448, p, 39081, (byte) 0x05, 2,
+ new int[]{1, 3, 101, 111}, NamedParameterSpec.X448.getName(),
+ bySize, byOid, byName);
+
+ } catch (IOException ex) {
+ // Unable to set X448 parameters---it will be disabled
+ }
+
+ SIZE_MAP = Collections.unmodifiableMap(bySize);
+ OID_MAP = Collections.unmodifiableMap(byOid);
+ NAME_MAP = Collections.unmodifiableMap(byName);
+ }
+
+ private static void addParameters(int bits, BigInteger p, int a24,
+ byte basePoint, int logCofactor, int[] oidBytes, String name,
+ Map<Integer, XECParameters> bySize,
+ Map<ObjectIdentifier, XECParameters> byOid,
+ Map<String, XECParameters> byName) throws IOException {
+
+ ObjectIdentifier oid = new ObjectIdentifier(oidBytes);
+ XECParameters params =
+ new XECParameters(bits, p, a24, basePoint, logCofactor, oid, name);
+ bySize.put(bits, params);
+ byOid.put(oid, params);
+ byName.put(name.toLowerCase(), params);
+ }
+
+ public static Optional<XECParameters> getByOid(ObjectIdentifier id) {
+ return Optional.ofNullable(OID_MAP.get(id));
+ }
+ public static Optional<XECParameters> getBySize(int size) {
+ return Optional.ofNullable(SIZE_MAP.get(size));
+ }
+ public static Optional<XECParameters> getByName(String name) {
+ return Optional.ofNullable(NAME_MAP.get(name.toLowerCase()));
+ }
+
+ public boolean oidEquals(XECParameters other) {
+ return oid.equals(other.getOid());
+ }
+
+ // Utility method that is used by the methods below to handle exception
+ // suppliers
+ private static
+ <A, B> Supplier<B> apply(final Function<A, B> func, final A a) {
+ return new Supplier<B>() {
+ @Override
+ public B get() {
+ return func.apply(a);
+ }
+ };
+ }
+
+ /**
+ * Get parameters by key size, or throw an exception if no parameters are
+ * defined for the specified key size. This method is used in several
+ * contexts that should throw different exceptions when the parameters
+ * are not found. The first argument is a function that produces the
+ * desired exception.
+ *
+ * @param exception a function that produces an exception from a string
+ * @param size the desired key size
+ * @param <T> the type of exception that is thrown
+ * @return the parameters for the specified key size
+ * @throws T when suitable parameters do not exist
+ */
+ public static
+ <T extends Throwable>
+ XECParameters getBySize(Function<String, T> exception,
+ int size) throws T {
+
+ Optional<XECParameters> xecParams = getBySize(size);
+ return xecParams.orElseThrow(
+ apply(exception, "Unsupported size: " + size));
+ }
+
+ /**
+ * Get parameters by algorithm ID, or throw an exception if no
+ * parameters are defined for the specified ID. This method is used in
+ * several contexts that should throw different exceptions when the
+ * parameters are not found. The first argument is a function that produces
+ * the desired exception.
+ *
+ * @param exception a function that produces an exception from a string
+ * @param algId the algorithm ID
+ * @param <T> the type of exception that is thrown
+ * @return the parameters for the specified algorithm ID
+ * @throws T when suitable parameters do not exist
+ */
+ public static
+ <T extends Throwable>
+ XECParameters get(Function<String, T> exception,
+ AlgorithmId algId) throws T {
+
+ Optional<XECParameters> xecParams = getByOid(algId.getOID());
+ return xecParams.orElseThrow(
+ apply(exception, "Unsupported OID: " + algId.getOID()));
+ }
+
+ /**
+ * Get parameters by algorithm parameter spec, or throw an exception if no
+ * parameters are defined for the spec. This method is used in
+ * several contexts that should throw different exceptions when the
+ * parameters are not found. The first argument is a function that produces
+ * the desired exception.
+ *
+ * @param exception a function that produces an exception from a string
+ * @param params the algorithm parameters spec
+ * @param <T> the type of exception that is thrown
+ * @return the parameters for the spec
+ * @throws T when suitable parameters do not exist
+ */
+ public static
+ <T extends Throwable>
+ XECParameters get(Function<String, T> exception,
+ AlgorithmParameterSpec params) throws T {
+
+ if (params instanceof NamedParameterSpec) {
+ NamedParameterSpec namedParams = (NamedParameterSpec) params;
+ Optional<XECParameters> xecParams =
+ getByName(namedParams.getName());
+ return xecParams.orElseThrow(
+ apply(exception, "Unsupported name: " + namedParams.getName()));
+ } else {
+ throw exception.apply("Only NamedParameterSpec is supported.");
+ }
+ }
+}
+
--- a/src/jdk.crypto.ec/share/classes/sun/security/ec/XDHKeyAgreement.java Mon May 21 11:14:44 2018 -0400
+++ b/src/jdk.crypto.ec/share/classes/sun/security/ec/XDHKeyAgreement.java Tue May 22 13:44:02 2018 -0400
@@ -38,8 +38,11 @@
import javax.crypto.KeyAgreementSpi;
import javax.crypto.SecretKey;
import javax.crypto.ShortBufferException;
+import javax.crypto.spec.SecretKeySpec;
import java.util.function.Function;
+import sun.security.util.XECParameters;
+
public class XDHKeyAgreement extends KeyAgreementSpi {
private byte[] privateKey;
@@ -197,7 +200,14 @@
throws IllegalStateException, NoSuchAlgorithmException,
InvalidKeyException {
- throw new NoSuchAlgorithmException("Not supported");
+ if (algorithm == null) {
+ throw new NoSuchAlgorithmException("Algorithm must not be null");
+ }
+ if (!(algorithm.equals("TlsPremasterSecret"))) {
+ throw new NoSuchAlgorithmException
+ ("Only supported for algorithm TlsPremasterSecret");
+ }
+ return new SecretKeySpec(engineGenerateSecret(), "TlsPremasterSecret");
}
static class X25519 extends XDHKeyAgreement {
--- a/src/jdk.crypto.ec/share/classes/sun/security/ec/XDHKeyFactory.java Mon May 21 11:14:44 2018 -0400
+++ b/src/jdk.crypto.ec/share/classes/sun/security/ec/XDHKeyFactory.java Tue May 22 13:44:02 2018 -0400
@@ -44,6 +44,8 @@
import java.security.spec.XECPrivateKeySpec;
import java.util.function.Function;
+import sun.security.util.XECParameters;
+
public class XDHKeyFactory extends KeyFactorySpi {
private XECParameters lockedParams = null;
--- a/src/jdk.crypto.ec/share/classes/sun/security/ec/XDHKeyPairGenerator.java Mon May 21 11:14:44 2018 -0400
+++ b/src/jdk.crypto.ec/share/classes/sun/security/ec/XDHKeyPairGenerator.java Tue May 22 13:44:02 2018 -0400
@@ -37,6 +37,7 @@
import java.security.spec.NamedParameterSpec;
import sun.security.jca.JCAUtil;
+import sun.security.util.XECParameters;
/**
* Key pair generator for the XDH key agreement algorithm.
--- a/src/jdk.crypto.ec/share/classes/sun/security/ec/XDHPrivateKeyImpl.java Mon May 21 11:14:44 2018 -0400
+++ b/src/jdk.crypto.ec/share/classes/sun/security/ec/XDHPrivateKeyImpl.java Tue May 22 13:44:02 2018 -0400
@@ -28,11 +28,11 @@
import java.security.interfaces.XECPrivateKey;
import java.util.Optional;
import java.security.InvalidKeyException;
-import java.security.PrivateKey;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.NamedParameterSpec;
import sun.security.pkcs.PKCS8Key;
+import sun.security.util.XECParameters;
import sun.security.x509.AlgorithmId;
public final class XDHPrivateKeyImpl extends PKCS8Key implements XECPrivateKey {
--- a/src/jdk.crypto.ec/share/classes/sun/security/ec/XDHPublicKeyImpl.java Mon May 21 11:14:44 2018 -0400
+++ b/src/jdk.crypto.ec/share/classes/sun/security/ec/XDHPublicKeyImpl.java Tue May 22 13:44:02 2018 -0400
@@ -28,13 +28,13 @@
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyRep;
-import java.security.PublicKey;
import java.security.interfaces.XECPublicKey;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.NamedParameterSpec;
-import java.util.Arrays;
import sun.security.util.BitArray;
+import sun.security.util.ECUtil;
+import sun.security.util.XECParameters;
import sun.security.x509.AlgorithmId;
import sun.security.x509.X509Key;
@@ -52,11 +52,7 @@
this.algid = new AlgorithmId(params.getOid());
this.u = u.mod(params.getP());
- byte[] u_arr = this.u.toByteArray();
- reverse(u_arr);
- // u_arr may be too large or too small, depending on the value of u
- u_arr = Arrays.copyOf(u_arr, params.getBytes());
-
+ byte[] u_arr = ECUtil.encodeXecPublicKey(this.u, params);
setKey(new BitArray(u_arr.length * 8, u_arr));
checkLength(params);
@@ -70,16 +66,7 @@
this.paramSpec = new NamedParameterSpec(params.getName());
// construct the BigInteger representation
byte[] u_arr = getKey().toByteArray();
- reverse(u_arr);
-
- // clear the extra bits
- int bitsMod8 = params.getBits() % 8;
- if (bitsMod8 != 0) {
- int mask = (1 << bitsMod8) - 1;
- u_arr[0] &= mask;
- }
-
- this.u = new BigInteger(1, u_arr);
+ this.u = ECUtil.decodeXecPublicKey(u_arr, params);
checkLength(params);
}
@@ -113,22 +100,5 @@
getFormat(),
getEncoded());
}
-
- private static void swap(byte[] arr, int i, int j) {
- byte tmp = arr[i];
- arr[i] = arr[j];
- arr[j] = tmp;
- }
-
- private static void reverse(byte [] arr) {
- int i = 0;
- int j = arr.length - 1;
-
- while (i < j) {
- swap(arr, i, j);
- i++;
- j--;
- }
- }
}
--- a/src/jdk.crypto.ec/share/classes/sun/security/ec/XECOperations.java Mon May 21 11:14:44 2018 -0400
+++ b/src/jdk.crypto.ec/share/classes/sun/security/ec/XECOperations.java Tue May 22 13:44:02 2018 -0400
@@ -32,6 +32,7 @@
import sun.security.util.math.SmallValue;
import sun.security.util.math.intpoly.IntegerPolynomial25519;
import sun.security.util.math.intpoly.IntegerPolynomial448;
+import sun.security.util.XECParameters;
import java.math.BigInteger;
import java.security.ProviderException;
--- a/src/jdk.crypto.ec/share/classes/sun/security/ec/XECParameters.java Mon May 21 11:14:44 2018 -0400
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,263 +0,0 @@
-/*
- * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.security.ec;
-
-import java.io.IOException;
-import java.math.BigInteger;
-import java.security.spec.AlgorithmParameterSpec;
-import java.security.spec.NamedParameterSpec;
-import java.util.Collections;
-import java.util.Map;
-import java.util.HashMap;
-import java.util.Optional;
-import java.util.function.Function;
-import java.util.function.Supplier;
-
-import sun.security.util.ObjectIdentifier;
-import sun.security.x509.AlgorithmId;
-
-public class XECParameters {
-
- // Naming/identification parameters
- private final ObjectIdentifier oid;
- private final String name;
-
- // Curve/field parameters
- private final int bits;
- private final BigInteger p;
- private final int logCofactor;
- private final int a24;
- private final byte basePoint;
-
- /**
- *
- * Construct an object holding the supplied parameters. No parameters are
- * checked, so this method always succeeds. This method supports
- * Montgomery curves of the form y^2 = x^3 + ax^2 + x.
- *
- * @param bits The number of relevant bits in a public/private key.
- * @param p The prime that defines the finite field.
- * @param a24 The value of (a - 2) / 4, where a is the second-degree curve
- * coefficient.
- * @param basePoint The point that generates the desired group
- * @param logCofactor The base-2 logarithm of the cofactor of the curve
- * @param oid
- * @param name
- */
- public XECParameters(int bits, BigInteger p, int a24,
- byte basePoint, int logCofactor,
- ObjectIdentifier oid, String name) {
-
- this.bits = bits;
- this.logCofactor = logCofactor;
- this.p = p;
- this.a24 = a24;
- this.basePoint = basePoint;
- this.oid = oid;
- this.name = name;
-
- }
-
- public int getBits() {
- return bits;
- }
- public int getBytes() {
- return (bits + 7) / 8;
- }
- public int getLogCofactor() {
- return logCofactor;
- }
- public BigInteger getP() {
- return p;
- }
- public int getA24() {
- return a24;
- }
- public byte getBasePoint() {
- return basePoint;
- }
- public ObjectIdentifier getOid() {
- return oid;
- }
- public String getName() {
- return name;
- }
-
- private static final Map<Integer, XECParameters> SIZE_MAP;
- private static final Map<ObjectIdentifier, XECParameters> OID_MAP;
- private static final Map<String, XECParameters> NAME_MAP;
-
- static {
- final BigInteger TWO = BigInteger.valueOf(2);
-
- Map<Integer, XECParameters> bySize = new HashMap<>();
- Map<ObjectIdentifier, XECParameters> byOid = new HashMap<>();
- Map<String, XECParameters> byName = new HashMap<>();
-
- // set up X25519
- try {
- BigInteger p = TWO.pow(255).subtract(BigInteger.valueOf(19));
- addParameters(255, p, 121665, (byte) 0x09, 3,
- new int[]{1, 3, 101, 110}, NamedParameterSpec.X25519.getName(),
- bySize, byOid, byName);
-
- } catch (IOException ex) {
- // Unable to set X25519 parameters---it will be disabled
- }
-
- // set up X448
- try {
- BigInteger p = TWO.pow(448).subtract(TWO.pow(224))
- .subtract(BigInteger.ONE);
- addParameters(448, p, 39081, (byte) 0x05, 2,
- new int[]{1, 3, 101, 111}, NamedParameterSpec.X448.getName(),
- bySize, byOid, byName);
-
- } catch (IOException ex) {
- // Unable to set X448 parameters---it will be disabled
- }
-
- SIZE_MAP = Collections.unmodifiableMap(bySize);
- OID_MAP = Collections.unmodifiableMap(byOid);
- NAME_MAP = Collections.unmodifiableMap(byName);
- }
-
- private static void addParameters(int bits, BigInteger p, int a24,
- byte basePoint, int logCofactor, int[] oidBytes, String name,
- Map<Integer, XECParameters> bySize,
- Map<ObjectIdentifier, XECParameters> byOid,
- Map<String, XECParameters> byName) throws IOException {
-
- ObjectIdentifier oid = new ObjectIdentifier(oidBytes);
- XECParameters params =
- new XECParameters(bits, p, a24, basePoint, logCofactor, oid, name);
- bySize.put(bits, params);
- byOid.put(oid, params);
- byName.put(name, params);
- }
-
- public static Optional<XECParameters> getByOid(ObjectIdentifier id) {
- return Optional.ofNullable(OID_MAP.get(id));
- }
- public static Optional<XECParameters> getBySize(int size) {
- return Optional.ofNullable(SIZE_MAP.get(size));
- }
- public static Optional<XECParameters> getByName(String name) {
- return Optional.ofNullable(NAME_MAP.get(name));
- }
-
- boolean oidEquals(XECParameters other) {
- return oid.equals(other.getOid());
- }
-
- // Utility method that is used by the methods below to handle exception
- // suppliers
- private static
- <A, B> Supplier<B> apply(final Function<A, B> func, final A a) {
- return new Supplier<B>() {
- @Override
- public B get() {
- return func.apply(a);
- }
- };
- }
-
- /**
- * Get parameters by key size, or throw an exception if no parameters are
- * defined for the specified key size. This method is used in several
- * contexts that should throw different exceptions when the parameters
- * are not found. The first argument is a function that produces the
- * desired exception.
- *
- * @param exception a function that produces an exception from a string
- * @param size the desired key size
- * @param <T> the type of exception that is thrown
- * @return the parameters for the specified key size
- * @throws T when suitable parameters do not exist
- */
- public static
- <T extends Throwable>
- XECParameters getBySize(Function<String, T> exception,
- int size) throws T {
-
- Optional<XECParameters> xecParams = getBySize(size);
- return xecParams.orElseThrow(
- apply(exception, "Unsupported size: " + size));
- }
-
- /**
- * Get parameters by algorithm ID, or throw an exception if no
- * parameters are defined for the specified ID. This method is used in
- * several contexts that should throw different exceptions when the
- * parameters are not found. The first argument is a function that produces
- * the desired exception.
- *
- * @param exception a function that produces an exception from a string
- * @param algId the algorithm ID
- * @param <T> the type of exception that is thrown
- * @return the parameters for the specified algorithm ID
- * @throws T when suitable parameters do not exist
- */
- public static
- <T extends Throwable>
- XECParameters get(Function<String, T> exception,
- AlgorithmId algId) throws T {
-
- Optional<XECParameters> xecParams = getByOid(algId.getOID());
- return xecParams.orElseThrow(
- apply(exception, "Unsupported OID: " + algId.getOID()));
- }
-
- /**
- * Get parameters by algorithm parameter spec, or throw an exception if no
- * parameters are defined for the spec. This method is used in
- * several contexts that should throw different exceptions when the
- * parameters are not found. The first argument is a function that produces
- * the desired exception.
- *
- * @param exception a function that produces an exception from a string
- * @param params the algorithm parameters spec
- * @param <T> the type of exception that is thrown
- * @return the parameters for the spec
- * @throws T when suitable parameters do not exist
- */
- public static
- <T extends Throwable>
- XECParameters get(Function<String, T> exception,
- AlgorithmParameterSpec params) throws T {
-
- if (params instanceof NamedParameterSpec) {
- NamedParameterSpec namedParams = (NamedParameterSpec) params;
- Optional<XECParameters> xecParams =
- getByName(namedParams.getName());
- return xecParams.orElseThrow(
- apply(exception, "Unsupported name: " + namedParams.getName()));
- } else {
- throw exception.apply("Only NamedParameterSpec is supported.");
- }
- }
-}
-