undefect. CWE-407 — 63 sites patched across 27 ecosystems
Authors: russell@unturf.com · brackishbert@gmail.com · foxhop.net · TimeHexOn.com Patches, unit tests, benchmarks, whitepaper, and outreach briefs. Public domain — no copyright claimed. Use freely.
This commit is contained in:
commit
0a580b313d
70422 changed files with 17213626 additions and 0 deletions
79
test/jdk/java/security/KeyAgreement/Generic.java
Normal file
79
test/jdk/java/security/KeyAgreement/Generic.java
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
/*
|
||||
* Copyright (c) 2025, 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 8189441
|
||||
* @library /test/lib /test/jdk/sun/security/pkcs11
|
||||
* @summary make sure Generic is accepted by all KeyAgreement implementations
|
||||
* @run main Generic builtin
|
||||
* @run main/othervm Generic nss
|
||||
* @run main/othervm -DCUSTOM_P11_CONFIG_NAME=p11-nss-sensitive.txt Generic nss
|
||||
*/
|
||||
import jdk.test.lib.Asserts;
|
||||
|
||||
import javax.crypto.KeyAgreement;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.Provider;
|
||||
import java.security.Security;
|
||||
import java.util.List;
|
||||
|
||||
public class Generic {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
if (args[0].equals("nss")) {
|
||||
test(PKCS11Test.getSunPKCS11(PKCS11Test.getNssConfig()));
|
||||
} else {
|
||||
for (var p : Security.getProviders()) {
|
||||
test(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void test(Provider p) throws Exception {
|
||||
for (var s : p.getServices()) {
|
||||
if (s.getType().equalsIgnoreCase("KeyAgreement")) {
|
||||
try {
|
||||
System.out.println(s.getProvider().getName() + "." + s.getAlgorithm());
|
||||
var g = KeyPairGenerator.getInstance(ka2kpg(s.getAlgorithm()), p);
|
||||
var kp1 = g.generateKeyPair();
|
||||
var kp2 = g.generateKeyPair();
|
||||
var ka = KeyAgreement.getInstance(s.getAlgorithm(), s.getProvider());
|
||||
for (var alg : List.of("TlsPremasterSecret", "Generic")) {
|
||||
ka.init(kp1.getPrivate());
|
||||
ka.doPhase(kp2.getPublic(), true);
|
||||
Asserts.assertEquals(
|
||||
ka.generateSecret(alg).getAlgorithm(), alg);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Find key algorithm from KeyAgreement algorithm
|
||||
private static String ka2kpg(String ka) {
|
||||
return ka.equals("ECDH") ? "EC" : ka;
|
||||
}
|
||||
}
|
||||
156
test/jdk/java/security/KeyAgreement/KeyAgreementTest.java
Normal file
156
test/jdk/java/security/KeyAgreement/KeyAgreementTest.java
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
/*
|
||||
* Copyright (c) 2018, 2024, 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 4936763 8184359 8205476 8226307
|
||||
* @summary KeyAgreement Test with all supported algorithms from JCE.
|
||||
* Arguments order <KeyExchangeAlgorithm> <KeyGenAlgorithm> <Provider>
|
||||
* It removes com/sun/crypto/provider/KeyAgreement/DHGenSecretKey.java
|
||||
* as the same functionality for DiffieHellman is covered along with
|
||||
* this test file was covered before with JDK-4936763.
|
||||
* @run main/othervm -Djdk.crypto.KeyAgreement.legacyKDF=true KeyAgreementTest
|
||||
* DiffieHellman DH SunJCE
|
||||
* @run main KeyAgreementTest ECDH EC SunEC
|
||||
* @run main KeyAgreementTest XDH XDH SunEC
|
||||
*/
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.spec.NamedParameterSpec;
|
||||
import java.security.spec.AlgorithmParameterSpec;
|
||||
import java.security.spec.ECGenParameterSpec;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import javax.crypto.KeyAgreement;
|
||||
import javax.crypto.spec.DHGenParameterSpec;
|
||||
|
||||
public class KeyAgreementTest {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
String kaAlgo = args[0];
|
||||
String kpgAlgo = args[1];
|
||||
String provider = System.getProperty("test.provider.name", args[2]);
|
||||
System.out.println("Testing " + kaAlgo);
|
||||
AlgoSpec aSpec = AlgoSpec.valueOf(AlgoSpec.class, kaAlgo);
|
||||
List<AlgorithmParameterSpec> specs = aSpec.getAlgorithmParameterSpecs();
|
||||
for (AlgorithmParameterSpec spec : specs) {
|
||||
testKeyAgreement(provider, kaAlgo, kpgAlgo, spec);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate AlgorithmParameterSpec using all possible supported curve for
|
||||
* KeyExchangeAlgorithm.
|
||||
*/
|
||||
private enum AlgoSpec {
|
||||
// EC curve supported for KeyGeneration can found between intersection
|
||||
// of curves define in
|
||||
// "java.base/share/classes/sun/security/util/CurveDB.java"
|
||||
|
||||
ECDH("secp256r1", "secp384r1", "secp521r1"),
|
||||
XDH("X25519", "X448", "x25519"),
|
||||
// There is no curve for DiffieHellman
|
||||
DiffieHellman(new String[]{});
|
||||
|
||||
private final List<AlgorithmParameterSpec> specs = new ArrayList<>();
|
||||
|
||||
private AlgoSpec(String... curves) {
|
||||
// Generate AlgorithmParameterSpec for each KeyExchangeAlgorithm
|
||||
for (String crv : curves) {
|
||||
switch (this.name()) {
|
||||
case "ECDH":
|
||||
specs.add(new ECGenParameterSpec(crv));
|
||||
break;
|
||||
case "XDH":
|
||||
specs.add(new NamedParameterSpec(crv));
|
||||
break;
|
||||
case "DiffieHellman":
|
||||
specs.add(new DHGenParameterSpec(512, 64));
|
||||
break;
|
||||
default:
|
||||
throw new RuntimeException("Invalid Algo name "
|
||||
+ this.name());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public List<AlgorithmParameterSpec> getAlgorithmParameterSpecs() {
|
||||
return this.specs;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform KeyAgreement operation
|
||||
*/
|
||||
private static void testKeyAgreement(String provider, String kaAlgo,
|
||||
String kpgAlgo, AlgorithmParameterSpec spec) throws Exception {
|
||||
|
||||
KeyPairGenerator kpg = KeyPairGenerator.getInstance(kpgAlgo, provider);
|
||||
kpg.initialize(spec);
|
||||
if (spec instanceof ECGenParameterSpec) {
|
||||
System.out.println("Testing curve: " +
|
||||
((ECGenParameterSpec)spec).getName());
|
||||
} else if (spec instanceof NamedParameterSpec) {
|
||||
System.out.println("Testing curve: " +
|
||||
((NamedParameterSpec)spec).getName());
|
||||
}
|
||||
KeyPair kp1 = kpg.generateKeyPair();
|
||||
KeyPair kp2 = kpg.generateKeyPair();
|
||||
|
||||
// Uses KeyAgreement based on Provider search order.
|
||||
KeyAgreement ka1 = KeyAgreement.getInstance(kaAlgo);
|
||||
ka1.init(kp1.getPrivate());
|
||||
ka1.doPhase(kp2.getPublic(), true);
|
||||
byte[] secret1 = ka1.generateSecret();
|
||||
|
||||
// Uses SunJCE provider
|
||||
KeyAgreement ka2 = KeyAgreement.getInstance(kaAlgo, provider);
|
||||
ka2.init(kp2.getPrivate());
|
||||
ka2.doPhase(kp1.getPublic(), true);
|
||||
// Keeping the legacy generateSecret method for DiffieHellman as it was
|
||||
// defined in removed Test file from JDK-4936763,
|
||||
// com/sun/crypto/provider/KeyAgreement/DHGenSecretKey.java.
|
||||
byte[] secret2 = "DiffieHellman".equals(kaAlgo)
|
||||
? ka2.generateSecret("AES").getEncoded() : ka2.generateSecret();
|
||||
|
||||
// With related keypairs, each provider should generate same
|
||||
// KeyAgreement secret.
|
||||
if (!Arrays.equals(secret1, secret2)) {
|
||||
throw new Exception("KeyAgreement secret mismatch.");
|
||||
}
|
||||
|
||||
// ensure that a new secret cannot be produced before the next doPhase
|
||||
try {
|
||||
ka2.generateSecret();
|
||||
throw new RuntimeException("state not reset");
|
||||
} catch (IllegalStateException ex) {
|
||||
// this is expected
|
||||
}
|
||||
|
||||
// calling doPhase and then generateSecret should succeed
|
||||
ka2.doPhase(kp1.getPublic(), true);
|
||||
ka2.generateSecret();
|
||||
}
|
||||
}
|
||||
237
test/jdk/java/security/KeyAgreement/KeySizeTest.java
Normal file
237
test/jdk/java/security/KeyAgreement/KeySizeTest.java
Normal file
|
|
@ -0,0 +1,237 @@
|
|||
/*
|
||||
* Copyright (c) 2018, 2024, 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 8184359
|
||||
* @summary KeyLength support test for DiffieHellman, EC, XDH.
|
||||
* Arguments order <KeyExchangeAlgorithm> <Provider> <KeyGenAlgorithm> <keyLen>
|
||||
* @library /test/lib
|
||||
* @run main KeySizeTest DiffieHellman SunJCE DiffieHellman 512
|
||||
* @run main KeySizeTest DiffieHellman SunJCE DiffieHellman 768
|
||||
* @run main KeySizeTest DiffieHellman SunJCE DiffieHellman 832
|
||||
* @run main KeySizeTest DiffieHellman SunJCE DiffieHellman 1024
|
||||
* @run main KeySizeTest DiffieHellman SunJCE DiffieHellman 2048
|
||||
* @run main KeySizeTest DiffieHellman SunJCE DiffieHellman 3072
|
||||
* @run main KeySizeTest DiffieHellman SunJCE DiffieHellman 4096
|
||||
* @run main KeySizeTest DiffieHellman SunJCE DiffieHellman 6144
|
||||
* @run main KeySizeTest DiffieHellman SunJCE DiffieHellman 8192
|
||||
* @run main/othervm KeySizeTest ECDH SunEC EC 256
|
||||
* @run main/othervm KeySizeTest ECDH SunEC EC 384
|
||||
* @run main/othervm KeySizeTest ECDH SunEC EC 521
|
||||
* @run main KeySizeTest XDH SunEC XDH 255
|
||||
* @run main KeySizeTest XDH SunEC XDH 448
|
||||
*/
|
||||
import java.math.BigInteger;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.interfaces.ECPrivateKey;
|
||||
import java.security.interfaces.ECPublicKey;
|
||||
import java.security.interfaces.XECPrivateKey;
|
||||
import java.security.interfaces.XECPublicKey;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.security.spec.NamedParameterSpec;
|
||||
import java.util.Arrays;
|
||||
import java.util.HexFormat;
|
||||
import javax.crypto.KeyAgreement;
|
||||
import javax.crypto.interfaces.DHPrivateKey;
|
||||
import javax.crypto.interfaces.DHPublicKey;
|
||||
|
||||
public class KeySizeTest {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
String kaAlgo = args[0];
|
||||
String provider = System.getProperty("test.provider.name", args[1]);
|
||||
String kpgAlgo = args[2];
|
||||
int keySize = Integer.parseInt(args[3]);
|
||||
testKeyAgreement(provider, kaAlgo, kpgAlgo, keySize);
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform KeyAgreement operation.
|
||||
*/
|
||||
private static void testKeyAgreement(String provider, String kaAlgo,
|
||||
String kpgAlgo, int keySize) throws Exception {
|
||||
|
||||
KeyPairGenerator kpg = KeyPairGenerator.getInstance(kpgAlgo, provider);
|
||||
kpg.initialize(keySize);
|
||||
KeyPair kp = kpg.generateKeyPair();
|
||||
// Test standard Key attributes.
|
||||
testKeyAttributes(provider, kpgAlgo, kp, keySize);
|
||||
// Test KeyAgreement.
|
||||
KeyAgreement ka = KeyAgreement.getInstance(kaAlgo, provider);
|
||||
ka.init(kp.getPrivate());
|
||||
ka.doPhase(kp.getPublic(), true);
|
||||
ka.generateSecret();
|
||||
}
|
||||
|
||||
/**
|
||||
* Test standard Key attributes.
|
||||
*/
|
||||
private static void testKeyAttributes(String provider, String kpgAlgo,
|
||||
KeyPair kp, int keySize) throws Exception {
|
||||
|
||||
KeyFactory kf = KeyFactory.getInstance(kpgAlgo, provider);
|
||||
switch (kpgAlgo) {
|
||||
case "DiffieHellman":
|
||||
// Verify PrivateKey attributes.
|
||||
DHPrivateKey dhPri = (DHPrivateKey) kp.getPrivate();
|
||||
BigInteger p = dhPri.getParams().getP();
|
||||
if (p.bitLength() != keySize) {
|
||||
throw new Exception(String.format("Invalid modulus size: "
|
||||
+ "%s/%s", p.bitLength(), keySize));
|
||||
}
|
||||
if (!p.isProbablePrime(128)) {
|
||||
throw new Exception("The modulus is composite!");
|
||||
}
|
||||
PKCS8EncodedKeySpec dhPriSpec
|
||||
= new PKCS8EncodedKeySpec(dhPri.getEncoded());
|
||||
DHPrivateKey dhPriDecod
|
||||
= (DHPrivateKey) kf.generatePrivate(dhPriSpec);
|
||||
equals(dhPri.getX(), dhPriDecod.getX());
|
||||
equals(dhPri.getFormat(), dhPriDecod.getFormat());
|
||||
equals(dhPri.getEncoded(), dhPriDecod.getEncoded());
|
||||
equals(dhPri.getParams().getG(), dhPriDecod.getParams().getG());
|
||||
equals(dhPri.getParams().getL(), dhPriDecod.getParams().getL());
|
||||
equals(dhPri.getParams().getP(), dhPriDecod.getParams().getP());
|
||||
|
||||
// Verify PublicKey attributes.
|
||||
DHPublicKey dhPub = (DHPublicKey) kp.getPublic();
|
||||
p = dhPub.getParams().getP();
|
||||
if (p.bitLength() != keySize) {
|
||||
throw new Exception(String.format("Invalid modulus size: "
|
||||
+ "%s/%s", p.bitLength(), keySize));
|
||||
}
|
||||
X509EncodedKeySpec dhPubSpec
|
||||
= new X509EncodedKeySpec(dhPub.getEncoded());
|
||||
DHPublicKey dhPubDecod
|
||||
= (DHPublicKey) kf.generatePublic(dhPubSpec);
|
||||
equals(dhPub.getY(), dhPubDecod.getY());
|
||||
equals(dhPub.getFormat(), dhPubDecod.getFormat());
|
||||
equals(dhPub.getEncoded(), dhPubDecod.getEncoded());
|
||||
equals(dhPub.getParams().getG(), dhPubDecod.getParams().getG());
|
||||
equals(dhPub.getParams().getL(), dhPubDecod.getParams().getL());
|
||||
equals(dhPub.getParams().getP(), dhPubDecod.getParams().getP());
|
||||
|
||||
BigInteger left = BigInteger.ONE;
|
||||
BigInteger right = p.subtract(BigInteger.ONE);
|
||||
BigInteger x = dhPri.getX();
|
||||
if ((x.compareTo(left) <= 0) || (x.compareTo(right) >= 0)) {
|
||||
throw new Exception(
|
||||
"X outside range [2, p - 2]: x: " + x + " p: " + p);
|
||||
}
|
||||
BigInteger y = dhPub.getY();
|
||||
if ((y.compareTo(left) <= 0) || (y.compareTo(right) >= 0)) {
|
||||
throw new Exception(
|
||||
"Y outside range [2, p - 2]: x: " + x + " p: " + p);
|
||||
}
|
||||
break;
|
||||
case "EC":
|
||||
// Verify PrivateKey attributes.
|
||||
ECPrivateKey ecPriv = (ECPrivateKey) kp.getPrivate();
|
||||
PKCS8EncodedKeySpec ecPriSpec
|
||||
= new PKCS8EncodedKeySpec(ecPriv.getEncoded());
|
||||
ECPrivateKey ecPriDecod
|
||||
= (ECPrivateKey) kf.generatePrivate(ecPriSpec);
|
||||
equals(ecPriv.getS(), ecPriDecod.getS());
|
||||
equals(ecPriv.getFormat(), ecPriDecod.getFormat());
|
||||
equals(ecPriv.getEncoded(), ecPriDecod.getEncoded());
|
||||
equals(ecPriv.getParams().getCofactor(),
|
||||
ecPriDecod.getParams().getCofactor());
|
||||
equals(ecPriv.getParams().getCurve(),
|
||||
ecPriDecod.getParams().getCurve());
|
||||
equals(ecPriv.getParams().getGenerator(),
|
||||
ecPriDecod.getParams().getGenerator());
|
||||
equals(ecPriv.getParams().getOrder(),
|
||||
ecPriDecod.getParams().getOrder());
|
||||
|
||||
// Verify PublicKey attributes.
|
||||
ECPublicKey ecPub = (ECPublicKey) kp.getPublic();
|
||||
X509EncodedKeySpec ecPubSpec
|
||||
= new X509EncodedKeySpec(ecPub.getEncoded());
|
||||
ECPublicKey ecPubDecod
|
||||
= (ECPublicKey) kf.generatePublic(ecPubSpec);
|
||||
equals(ecPub.getW(), ecPubDecod.getW());
|
||||
equals(ecPub.getFormat(), ecPubDecod.getFormat());
|
||||
equals(ecPub.getEncoded(), ecPubDecod.getEncoded());
|
||||
equals(ecPub.getParams().getCofactor(),
|
||||
ecPubDecod.getParams().getCofactor());
|
||||
equals(ecPub.getParams().getCurve(),
|
||||
ecPubDecod.getParams().getCurve());
|
||||
equals(ecPub.getParams().getGenerator(),
|
||||
ecPubDecod.getParams().getGenerator());
|
||||
equals(ecPub.getParams().getOrder(),
|
||||
ecPubDecod.getParams().getOrder());
|
||||
break;
|
||||
case "XDH":
|
||||
// Verify PrivateKey attributes.
|
||||
XECPrivateKey xdhPri = (XECPrivateKey) kp.getPrivate();
|
||||
PKCS8EncodedKeySpec xdhPriSpec
|
||||
= new PKCS8EncodedKeySpec(xdhPri.getEncoded());
|
||||
XECPrivateKey xdhPriDec
|
||||
= (XECPrivateKey) kf.generatePrivate(xdhPriSpec);
|
||||
equals(xdhPri.getScalar().get(), xdhPriDec.getScalar().get());
|
||||
equals(xdhPri.getFormat(), xdhPriDec.getFormat());
|
||||
equals(xdhPri.getEncoded(), xdhPriDec.getEncoded());
|
||||
equals(((NamedParameterSpec) xdhPri.getParams()).getName(),
|
||||
((NamedParameterSpec) xdhPriDec.getParams()).getName());
|
||||
|
||||
// Verify PublicKey attributes.
|
||||
XECPublicKey xdhPub = (XECPublicKey) kp.getPublic();
|
||||
X509EncodedKeySpec xdhPubSpec
|
||||
= new X509EncodedKeySpec(xdhPub.getEncoded());
|
||||
XECPublicKey xdhPubDec
|
||||
= (XECPublicKey) kf.generatePublic(xdhPubSpec);
|
||||
equals(xdhPub.getU(), xdhPubDec.getU());
|
||||
equals(xdhPub.getFormat(), xdhPubDec.getFormat());
|
||||
equals(xdhPub.getEncoded(), xdhPubDec.getEncoded());
|
||||
equals(((NamedParameterSpec) xdhPub.getParams()).getName(),
|
||||
((NamedParameterSpec) xdhPubDec.getParams()).getName());
|
||||
break;
|
||||
default:
|
||||
throw new RuntimeException("Invalid Algo name " + kpgAlgo);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean equals(Object actual, Object expected) {
|
||||
boolean equals = actual.equals(expected);
|
||||
if (!equals) {
|
||||
throw new RuntimeException(String.format("Actual: %s, Expected: %s",
|
||||
actual, expected));
|
||||
}
|
||||
return equals;
|
||||
}
|
||||
|
||||
private static boolean equals(byte[] actual, byte[] expected) {
|
||||
boolean equals = Arrays.equals(actual, expected);
|
||||
if (!equals) {
|
||||
throw new RuntimeException(String.format("Actual array: %s, Expected array:%s",
|
||||
HexFormat.of().withUpperCase().formatHex(actual),
|
||||
HexFormat.of().withUpperCase().formatHex(expected)));
|
||||
}
|
||||
return equals;
|
||||
}
|
||||
}
|
||||
318
test/jdk/java/security/KeyAgreement/KeySpecTest.java
Normal file
318
test/jdk/java/security/KeyAgreement/KeySpecTest.java
Normal file
|
|
@ -0,0 +1,318 @@
|
|||
/*
|
||||
* Copyright (c) 2018, 2024, 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 8184359
|
||||
* @library /test/lib
|
||||
* @summary Standard tests on KeySpec, KeyFactory, KeyPairs and Keys.
|
||||
* Arguments order <KeyExchangeAlgorithm> <Provider> <KeyGenAlgorithm> <Curve*>
|
||||
* @run main KeySpecTest DiffieHellman SunJCE DiffieHellman
|
||||
* @run main KeySpecTest ECDH SunEC EC
|
||||
* @run main KeySpecTest XDH SunEC XDH X25519
|
||||
* @run main KeySpecTest XDH SunEC XDH X448
|
||||
*/
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.security.spec.ECPrivateKeySpec;
|
||||
import java.security.spec.ECPublicKeySpec;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.security.spec.NamedParameterSpec;
|
||||
import java.security.spec.XECPublicKeySpec;
|
||||
import java.security.spec.XECPrivateKeySpec;
|
||||
import java.security.spec.KeySpec;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Arrays;
|
||||
import javax.crypto.KeyAgreement;
|
||||
import javax.crypto.spec.DHPrivateKeySpec;
|
||||
import javax.crypto.spec.DHPublicKeySpec;
|
||||
import jdk.test.lib.security.SecurityUtils;
|
||||
|
||||
public class KeySpecTest {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
String kaAlgo = args[0];
|
||||
String provider = System.getProperty("test.provider.name", args[1]);
|
||||
String kpgAlgo = args[2];
|
||||
KeyPair kp = genKeyPair(provider, kpgAlgo,
|
||||
(args.length > 3) ? args[3] : kpgAlgo);
|
||||
testKeySpecs(provider, kaAlgo, kpgAlgo, kp);
|
||||
testEncodedKeySpecs(provider, kaAlgo, kpgAlgo, kp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate keyPair based on KeyPairGenerator algorithm.
|
||||
*/
|
||||
private static KeyPair genKeyPair(String provider, String kpgAlgo,
|
||||
String kpgInit) throws Exception {
|
||||
|
||||
KeyPairGenerator kpg = KeyPairGenerator.getInstance(kpgAlgo, provider);
|
||||
switch (kpgInit) {
|
||||
case "DiffieHellman":
|
||||
kpg.initialize(SecurityUtils.getTestKeySize(kpgInit));
|
||||
break;
|
||||
case "EC":
|
||||
kpg.initialize(256);
|
||||
break;
|
||||
case "X25519":
|
||||
kpg.initialize(255);
|
||||
break;
|
||||
case "X448":
|
||||
kpg.initialize(448);
|
||||
break;
|
||||
default:
|
||||
throw new RuntimeException("Invalid Algo name " + kpgInit);
|
||||
}
|
||||
return kpg.generateKeyPair();
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Test with Keys and the one generated through Spec.
|
||||
*/
|
||||
private static void testKeySpecs(String provider, String kaAlgo,
|
||||
String kpgAlgo, KeyPair kp) throws Exception {
|
||||
|
||||
KeyFactory kf = KeyFactory.getInstance(kpgAlgo, provider);
|
||||
// For each public KeySpec supported by KeyPairGenerator
|
||||
for (Class pubSpecType
|
||||
: getCompatibleKeySpecs(kpgAlgo, KeyType.PUBLIC)) {
|
||||
//For each private KeySpec supported by KeyPairGenerator
|
||||
for (Class priSpecType
|
||||
: getCompatibleKeySpecs(kpgAlgo, KeyType.PRIVATE)) {
|
||||
// Transform original PublicKey through KeySpec
|
||||
KeySpec pubSpec = kf.getKeySpec(kp.getPublic(), pubSpecType);
|
||||
PublicKey pubKey = kf.generatePublic(pubSpec);
|
||||
// Transform original PrivateKey through KeySpec
|
||||
KeySpec priSpec = kf.getKeySpec(kp.getPrivate(), priSpecType);
|
||||
PrivateKey priKey = kf.generatePrivate(priSpec);
|
||||
|
||||
// Test the keys are equal after transformation through KeySpec.
|
||||
testKeyEquals(kp, pubKey, priKey);
|
||||
// Test the keys are serializable.
|
||||
testSerialize(kp);
|
||||
// Test Parameter name.
|
||||
if (!kaAlgo.equals("DiffieHellman")) {
|
||||
testParamName(priSpec, pubSpec);
|
||||
}
|
||||
// Compare KeyAgreement secret generated from original keys
|
||||
// and by the keys after transformed through KeySpec.
|
||||
if (!Arrays.equals(getKeyAgreementSecret(provider, kaAlgo,
|
||||
kp.getPublic(), kp.getPrivate()),
|
||||
getKeyAgreementSecret(provider, kaAlgo,
|
||||
pubKey, priKey))) {
|
||||
throw new RuntimeException("KeyAgreement secret mismatch.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard Test with Keys and the one generated from encoded bytes.
|
||||
*/
|
||||
private static void testEncodedKeySpecs(String provider, String kaAlgo,
|
||||
String kpgAlgo, KeyPair kp) throws Exception {
|
||||
|
||||
KeyFactory kf = KeyFactory.getInstance(kpgAlgo, provider);
|
||||
PKCS8EncodedKeySpec priSpec
|
||||
= new PKCS8EncodedKeySpec(kp.getPrivate().getEncoded());
|
||||
PrivateKey priKey = kf.generatePrivate(priSpec);
|
||||
|
||||
X509EncodedKeySpec pubSpec
|
||||
= new X509EncodedKeySpec(kp.getPublic().getEncoded());
|
||||
PublicKey pubKey = kf.generatePublic(pubSpec);
|
||||
|
||||
// Test the keys are equal after transformation through KeySpec.
|
||||
testKeyEquals(kp, pubKey, priKey);
|
||||
// Test the keys are serializable.
|
||||
testSerialize(kp);
|
||||
// Test Parameter name.
|
||||
if (!kaAlgo.equals("DiffieHellman")) {
|
||||
testParamName(priSpec, pubSpec);
|
||||
}
|
||||
// Compare KeyAgreement secret generated from original keys
|
||||
// and by the keys after transformed through KeySpec.
|
||||
if (!Arrays.equals(getKeyAgreementSecret(provider, kaAlgo,
|
||||
kp.getPublic(), kp.getPrivate()),
|
||||
getKeyAgreementSecret(provider, kaAlgo, pubKey, priKey))) {
|
||||
throw new RuntimeException("KeyAgreement secret mismatch.");
|
||||
}
|
||||
}
|
||||
|
||||
private enum KeyType {
|
||||
PUBLIC, PRIVATE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides Compatible KeySpec Type list for KeyPairGenerator algorithm.
|
||||
*/
|
||||
private static List<Class> getCompatibleKeySpecs(String kpgAlgo,
|
||||
KeyType type) {
|
||||
|
||||
List<Class> specs = new ArrayList<>();
|
||||
switch (kpgAlgo) {
|
||||
case "DiffieHellman":
|
||||
if (type == KeyType.PUBLIC) {
|
||||
return Arrays.asList(X509EncodedKeySpec.class,
|
||||
DHPublicKeySpec.class);
|
||||
} else {
|
||||
return Arrays.asList(PKCS8EncodedKeySpec.class,
|
||||
DHPrivateKeySpec.class);
|
||||
}
|
||||
case "EC":
|
||||
if (type == KeyType.PUBLIC) {
|
||||
return Arrays.asList(X509EncodedKeySpec.class,
|
||||
ECPublicKeySpec.class);
|
||||
} else {
|
||||
return Arrays.asList(PKCS8EncodedKeySpec.class,
|
||||
ECPrivateKeySpec.class);
|
||||
}
|
||||
case "XDH":
|
||||
if (type == KeyType.PUBLIC) {
|
||||
return Arrays.asList(X509EncodedKeySpec.class,
|
||||
XECPublicKeySpec.class);
|
||||
} else {
|
||||
return Arrays.asList(PKCS8EncodedKeySpec.class,
|
||||
XECPrivateKeySpec.class);
|
||||
}
|
||||
}
|
||||
return specs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate KeyAgreement Secret.
|
||||
*/
|
||||
private static byte[] getKeyAgreementSecret(String provider, String kaAlgo,
|
||||
PublicKey pubKey, PrivateKey priKey) throws Exception {
|
||||
|
||||
KeyAgreement ka = KeyAgreement.getInstance(kaAlgo, provider);
|
||||
ka.init(priKey);
|
||||
ka.doPhase(pubKey, true);
|
||||
return ka.generateSecret();
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare original KeyPair with transformed ones.
|
||||
*/
|
||||
private static void testKeyEquals(KeyPair kp, PublicKey pubKey,
|
||||
PrivateKey priKey) {
|
||||
|
||||
if (!kp.getPrivate().equals(priKey)
|
||||
&& kp.getPrivate().hashCode() != priKey.hashCode()) {
|
||||
throw new RuntimeException("PrivateKey is not equal with PrivateKey"
|
||||
+ " generated through KeySpec");
|
||||
}
|
||||
if (!kp.getPublic().equals(pubKey)
|
||||
&& kp.getPublic().hashCode() != pubKey.hashCode()) {
|
||||
throw new RuntimeException("PublicKey is not equal with PublicKey"
|
||||
+ " generated through KeySpec");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare the parameter names of Public/Private KeySpec from a pair.
|
||||
*/
|
||||
private static void testParamName(KeySpec priSpec, KeySpec pubSpec) {
|
||||
|
||||
if (priSpec instanceof XECPrivateKeySpec
|
||||
&& pubSpec instanceof XECPublicKeySpec) {
|
||||
if (((NamedParameterSpec) ((XECPrivateKeySpec) priSpec)
|
||||
.getParams()).getName()
|
||||
!= ((NamedParameterSpec) ((XECPublicKeySpec) pubSpec)
|
||||
.getParams()).getName()) {
|
||||
throw new RuntimeException("Curve name mismatch found");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test serialization of KeyPair and Keys it holds.
|
||||
*/
|
||||
private static void testSerialize(KeyPair keyPair) throws Exception {
|
||||
|
||||
// Verify Serialized PrivateKey instance.
|
||||
if (!keyPair.getPrivate().equals(
|
||||
deserializedCopy(keyPair.getPrivate(), PrivateKey.class))) {
|
||||
throw new RuntimeException("PrivateKey is not equal with PrivateKey"
|
||||
+ " generated through Serialization");
|
||||
}
|
||||
// Verify Serialized PublicKey instance.
|
||||
if (!keyPair.getPublic().equals(
|
||||
deserializedCopy(keyPair.getPublic(), PublicKey.class))) {
|
||||
throw new RuntimeException("PublicKey is not equal with PublicKey"
|
||||
+ " generated through Serialization");
|
||||
}
|
||||
// Verify Serialized KeyPair instance.
|
||||
KeyPair copy = deserializedCopy(keyPair, KeyPair.class);
|
||||
if (!keyPair.getPrivate().equals(copy.getPrivate())) {
|
||||
throw new RuntimeException("PrivateKey is not equal with PrivateKey"
|
||||
+ " generated through Serialized KeyPair");
|
||||
}
|
||||
if (!keyPair.getPublic().equals(copy.getPublic())) {
|
||||
throw new RuntimeException("PublicKey is not equal with PublicKey"
|
||||
+ " generated through Serialized KeyPair");
|
||||
}
|
||||
}
|
||||
|
||||
private static <T extends Object> T deserializedCopy(T orig, Class<T> type)
|
||||
throws IOException, ClassNotFoundException {
|
||||
return deserialize(serialize(orig), type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserialize the Key object.
|
||||
*/
|
||||
private static <T extends Object> T deserialize(byte[] serialized,
|
||||
Class<T> type) throws IOException, ClassNotFoundException {
|
||||
|
||||
T key = null;
|
||||
try (ByteArrayInputStream bis = new ByteArrayInputStream(serialized);
|
||||
ObjectInputStream ois = new ObjectInputStream(bis)) {
|
||||
key = (T) ois.readObject();
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize the given Key object.
|
||||
*/
|
||||
private static <T extends Object> byte[] serialize(T key)
|
||||
throws IOException {
|
||||
|
||||
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
ObjectOutputStream oos = new ObjectOutputStream(bos)) {
|
||||
oos.writeObject(key);
|
||||
return bos.toByteArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
152
test/jdk/java/security/KeyAgreement/MultiThreadTest.java
Normal file
152
test/jdk/java/security/KeyAgreement/MultiThreadTest.java
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
/*
|
||||
* Copyright (c) 2018, 2024, 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 8184359
|
||||
* @library /test/lib
|
||||
* @summary KeyPairGenerator Test with multiple threads.
|
||||
* Arguments order <KeyExchangeAlgorithm> <Provider> <KeyGenAlgorithm> <Curve*>
|
||||
* @run main MultiThreadTest DiffieHellman SunJCE DiffieHellman
|
||||
* @run main MultiThreadTest ECDH SunEC EC
|
||||
* @run main MultiThreadTest XDH SunEC XDH X25519
|
||||
* @run main MultiThreadTest XDH SunEC XDH X448
|
||||
*/
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import javax.crypto.KeyAgreement;
|
||||
import jdk.test.lib.security.SecurityUtils;
|
||||
|
||||
/**
|
||||
* This test targets KeyPairGenerator API related issue in a multi threaded
|
||||
* context.
|
||||
*/
|
||||
public class MultiThreadTest {
|
||||
|
||||
// Tested a shared KeyPairGenerator with 100 number of threads.
|
||||
private static final int THREAD_COUNT = 100;
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
String kaAlgo = args[0];
|
||||
String provider = System.getProperty("test.provider.name", args[1]);
|
||||
String kpgAlgo = args[2];
|
||||
KeyPairGenerator kpg = genKeyGenerator(provider, kpgAlgo,
|
||||
(args.length > 3) ? args[3] : kpgAlgo);
|
||||
new MultiThreadTest().runTest(provider, kaAlgo, kpg);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize KeyPairGenerator based on different algorithm names.
|
||||
*/
|
||||
private static KeyPairGenerator genKeyGenerator(String provider,
|
||||
String kpgAlgo, String kpgInit) throws Exception {
|
||||
|
||||
KeyPairGenerator kpg = KeyPairGenerator.getInstance(kpgAlgo, provider);
|
||||
switch (kpgInit) {
|
||||
case "DiffieHellman":
|
||||
kpg.initialize(SecurityUtils.getTestKeySize(kpgInit));
|
||||
break;
|
||||
case "EC":
|
||||
kpg.initialize(256);
|
||||
break;
|
||||
case "X25519":
|
||||
kpg.initialize(255);
|
||||
break;
|
||||
case "X448":
|
||||
kpg.initialize(448);
|
||||
break;
|
||||
default:
|
||||
throw new RuntimeException("Invalid Algo name " + kpgInit);
|
||||
}
|
||||
return kpg;
|
||||
}
|
||||
|
||||
private void runTest(String provider, String kaAlgo, KeyPairGenerator kpg)
|
||||
throws Exception {
|
||||
|
||||
ExecutorService executor = null;
|
||||
try {
|
||||
executor = Executors.newCachedThreadPool(new ThreadFactory() {
|
||||
@Override
|
||||
public Thread newThread(Runnable r) {
|
||||
Thread t = Executors.defaultThreadFactory().newThread(r);
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
}
|
||||
});
|
||||
CountDownLatch latch = new CountDownLatch(THREAD_COUNT);
|
||||
|
||||
for (int i = 0; i < THREAD_COUNT; i++) {
|
||||
executor.execute(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
testKeyAgreement(provider, kaAlgo, kpg);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
} finally {
|
||||
// Indicate a task completed.
|
||||
latch.countDown();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
// Wait till all tasks get complete.
|
||||
latch.await();
|
||||
} finally {
|
||||
if (executor != null) {
|
||||
executor.shutdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform KeyAgreement operation with a shared KeyPairGenerator instance.
|
||||
*/
|
||||
private static void testKeyAgreement(String provider, String kaAlgo,
|
||||
KeyPairGenerator kpg) throws Exception {
|
||||
|
||||
KeyPair kp1 = kpg.generateKeyPair();
|
||||
KeyPair kp2 = kpg.generateKeyPair();
|
||||
|
||||
KeyAgreement ka1 = KeyAgreement.getInstance(kaAlgo, provider);
|
||||
ka1.init(kp1.getPrivate());
|
||||
ka1.doPhase(kp2.getPublic(), true);
|
||||
byte[] secret1 = ka1.generateSecret();
|
||||
KeyAgreement ka2 = KeyAgreement.getInstance(kaAlgo, provider);
|
||||
ka2.init(kp2.getPrivate());
|
||||
ka2.doPhase(kp1.getPublic(), true);
|
||||
byte[] secret2 = ka2.generateSecret();
|
||||
|
||||
// With related keypairs, generated KeyAgreement secret should be same.
|
||||
if (!Arrays.equals(secret1, secret2)) {
|
||||
throw new Exception("KeyAgreement secret mismatch.");
|
||||
}
|
||||
}
|
||||
}
|
||||
408
test/jdk/java/security/KeyAgreement/NegativeTest.java
Normal file
408
test/jdk/java/security/KeyAgreement/NegativeTest.java
Normal file
|
|
@ -0,0 +1,408 @@
|
|||
/*
|
||||
* Copyright (c) 2018, 2024, 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 8200219
|
||||
* @summary Negative tests for Key related Test with DiffieHellman, ECDH, XDH.
|
||||
* It Tests,
|
||||
* Use modified encoding while generating Public/Private Keys
|
||||
* Short, long, unsupported keysize
|
||||
* Invalid Algo names including Null
|
||||
* Invalid provider names including Null
|
||||
* Invalid curve names
|
||||
* Invalid spec usage
|
||||
* Arguments order <KeyExchangeAlgorithm> <Provider> <KeyGenAlgorithm>
|
||||
* <keySize> <Curve*>
|
||||
* @library /test/lib
|
||||
* @run main NegativeTest DiffieHellman SunJCE DiffieHellman 2048
|
||||
* @run main NegativeTest ECDH SunEC EC 256
|
||||
* @run main NegativeTest XDH SunEC XDH 255 X25519
|
||||
* @run main NegativeTest XDH SunEC XDH 448 X448
|
||||
*/
|
||||
import java.math.BigInteger;
|
||||
import java.security.InvalidAlgorithmParameterException;
|
||||
import java.security.InvalidParameterException;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.NoSuchProviderException;
|
||||
import java.security.Security;
|
||||
import java.security.spec.InvalidKeySpecException;
|
||||
import java.security.spec.NamedParameterSpec;
|
||||
import java.security.spec.KeySpec;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.security.spec.XECPrivateKeySpec;
|
||||
import java.security.spec.XECPublicKeySpec;
|
||||
import java.util.Arrays;
|
||||
import java.util.HexFormat;
|
||||
import javax.crypto.KeyAgreement;
|
||||
import jdk.test.lib.security.SecurityUtils;
|
||||
|
||||
public class NegativeTest {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
String kaAlgo = args[0];
|
||||
String provider = System.getProperty("test.provider.name", args[1]);
|
||||
String kpgAlgo = args[2];
|
||||
int keySize = Integer.parseInt(args[3]);
|
||||
String kpgInit = (args.length > 4) ? args[4] : args[2];
|
||||
testModifiedKeyEncodingTest(provider, kpgAlgo, kpgInit);
|
||||
testInvalidKeyLen(provider, kaAlgo, kpgAlgo, kpgInit);
|
||||
testInvalidKpgAlgo(provider, kaAlgo, keySize);
|
||||
testInvalidKaAlgo(provider, kpgAlgo, keySize);
|
||||
testInvalidProvider(kaAlgo, kpgAlgo, keySize);
|
||||
if (!kaAlgo.equals("DiffieHellman")) {
|
||||
testNamedParameter(provider, kpgAlgo);
|
||||
}
|
||||
if (kaAlgo.equals("XDH")) {
|
||||
testInvalidSpec(provider, kpgAlgo, kpgInit);
|
||||
testInCompatibleSpec(provider, kpgAlgo, kpgInit);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate keyPair based on KeyPairGenerator algorithm.
|
||||
*/
|
||||
private static KeyPair genKeyPair(String provider, String kpgAlgo,
|
||||
String kpgInit) throws Exception {
|
||||
|
||||
KeyPairGenerator kpg = KeyPairGenerator.getInstance(kpgAlgo,
|
||||
Security.getProvider(provider));
|
||||
switch (kpgInit) {
|
||||
case "DiffieHellman":
|
||||
kpg.initialize(SecurityUtils.getTestKeySize(kpgInit));
|
||||
break;
|
||||
case "EC":
|
||||
kpg.initialize(256);
|
||||
break;
|
||||
case "X25519":
|
||||
kpg.initialize(255);
|
||||
break;
|
||||
case "X448":
|
||||
kpg.initialize(448);
|
||||
break;
|
||||
default:
|
||||
throw new RuntimeException("Invalid Algo name " + kpgInit);
|
||||
}
|
||||
return kpg.generateKeyPair();
|
||||
}
|
||||
|
||||
private static void testModifiedKeyEncodingTest(String provider,
|
||||
String kpgAlgo, String kpgInit) throws Exception {
|
||||
|
||||
KeyFactory kf = KeyFactory.getInstance(kpgAlgo, provider);
|
||||
KeyPair kp = genKeyPair(provider, kpgAlgo, kpgInit);
|
||||
// Test modified PrivateKey encoding
|
||||
byte[] encoded = kp.getPrivate().getEncoded();
|
||||
byte[] modified = modifyEncoded(encoded);
|
||||
PKCS8EncodedKeySpec priSpec = new PKCS8EncodedKeySpec(modified);
|
||||
try {
|
||||
// Generate PrivateKey with modified encoding
|
||||
kf.generatePrivate(priSpec);
|
||||
throw new RuntimeException(
|
||||
"testModifiedKeyTest should fail but passed.");
|
||||
} catch (InvalidKeySpecException e) {
|
||||
System.out.printf("Expected InvalidKeySpecException for invalid "
|
||||
+ "PrivateKey %s%n and modified encoding: %s, %s%n",
|
||||
HexFormat.of().withUpperCase().formatHex(encoded),
|
||||
HexFormat.of().withUpperCase().formatHex(modified), e.getMessage());
|
||||
}
|
||||
// Test modified PublicKey encoding
|
||||
encoded = kp.getPublic().getEncoded();
|
||||
modified = modifyEncoded(encoded);
|
||||
X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(modified);
|
||||
try {
|
||||
// Generate PublicKey with modified encoding
|
||||
kf.generatePublic(pubSpec);
|
||||
throw new RuntimeException(
|
||||
"testModifiedKeyTest should fail but passed.");
|
||||
} catch (InvalidKeySpecException e) {
|
||||
System.out.printf("Expected InvalidKeySpecException for invalid "
|
||||
+ "PublicKey %s%n and modified encoding: %s, %s%n",
|
||||
HexFormat.of().withUpperCase().formatHex(encoded),
|
||||
HexFormat.of().withUpperCase().formatHex(modified), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test with all Invalid key length.
|
||||
*/
|
||||
private static void testInvalidKeyLen(String provider, String kaAlgo,
|
||||
String kpgAlgo, String kpgInit) throws Exception {
|
||||
|
||||
for (int keySize : selectInvalidKeylength(kpgInit)) {
|
||||
try {
|
||||
startKeyAgreement(provider, kaAlgo, kpgAlgo, keySize);
|
||||
throw new RuntimeException(
|
||||
"testInvalidKeyLen should fail but passed.");
|
||||
} catch (InvalidParameterException e) {
|
||||
System.out.printf("Expected InvalidParameterException for "
|
||||
+ "keyLength: %s, %s%n", keySize, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test with all Invalid KeyPairGenerator algorithms.
|
||||
*/
|
||||
private static void testInvalidKpgAlgo(String provider, String algo,
|
||||
int keySize) throws Exception {
|
||||
|
||||
for (String kpgAlgo : new String[]{null, " ", "", "NoSuchAlgorithm"}) {
|
||||
try {
|
||||
startKeyAgreement(provider, algo, kpgAlgo, keySize);
|
||||
throw new RuntimeException(
|
||||
"testInvalidKpgAlgo should fail but passed.");
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
System.out.printf("Expected NoSuchAlgorithmException for "
|
||||
+ "KeyAgreement algo: %s, %s%n",
|
||||
kpgAlgo, e.getMessage());
|
||||
} catch (NullPointerException e) {
|
||||
if (kpgAlgo == null) {
|
||||
System.out.printf("Expected NullPointerException for "
|
||||
+ "KeyPairGenerator algo: %s, %s%n",
|
||||
kpgAlgo, e.getMessage());
|
||||
continue;
|
||||
}
|
||||
throw new RuntimeException(
|
||||
"Unknown failure in testInvalidKpgAlgo.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test with all Invalid KeyAgreement algorithms.
|
||||
*/
|
||||
private static void testInvalidKaAlgo(String provider, String kpgAlgo,
|
||||
int keySize) throws Exception {
|
||||
|
||||
for (String algo : new String[]{null, " ", "", "NoSuchAlgorithm"}) {
|
||||
try {
|
||||
startKeyAgreement(provider, algo, kpgAlgo, keySize);
|
||||
throw new RuntimeException(
|
||||
"testInvalidKaAlgo should fail but passed.");
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
System.out.printf("Expected NoSuchAlgorithmException for "
|
||||
+ "KeyAgreement algo: %s, %s%n", algo, e.getMessage());
|
||||
} catch (NullPointerException e) {
|
||||
if (algo == null) {
|
||||
System.out.printf("Expected NullPointerException for "
|
||||
+ "KeyAgreement algo: %s, %s%n",
|
||||
algo, e.getMessage());
|
||||
continue;
|
||||
}
|
||||
throw new RuntimeException(
|
||||
"Unknown failure in testInvalidKaAlgo.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test with all Invalid Provider names.
|
||||
*/
|
||||
private static void testInvalidProvider(String kaAlgo, String kpgAlgo,
|
||||
int keySize) throws Exception {
|
||||
|
||||
for (String provider : new String[]{null, " ", "", "NoSuchProvider"}) {
|
||||
try {
|
||||
startKeyAgreement(provider, kaAlgo, kpgAlgo, keySize);
|
||||
throw new RuntimeException(
|
||||
"testInvalidProvider should fail but passed.");
|
||||
} catch (NoSuchProviderException e) {
|
||||
System.out.printf("Expected NoSuchProviderException for "
|
||||
+ "Provider: %s, %s%n", provider, e.getMessage());
|
||||
} catch (IllegalArgumentException e) {
|
||||
System.out.printf("Expected IllegalArgumentException for "
|
||||
+ "Provider: %s, %s%n", provider, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test for (in)valid curve names as argument to NamedParameterSpec
|
||||
*/
|
||||
private static void testNamedParameter(String provider, String kpgAlgo)
|
||||
throws Exception {
|
||||
|
||||
for (String name : new String[]{null, " ", "", "NoSuchCurve"}) {
|
||||
try {
|
||||
NamedParameterSpec spec = new NamedParameterSpec(name);
|
||||
KeyPairGenerator kpg
|
||||
= KeyPairGenerator.getInstance(kpgAlgo, provider);
|
||||
kpg.initialize(spec);
|
||||
kpg.generateKeyPair();
|
||||
throw new RuntimeException(
|
||||
"testNamedParameter should fail but passed.");
|
||||
} catch (NullPointerException e) {
|
||||
if (name == null) {
|
||||
System.out.printf("Expected NullPointerException for "
|
||||
+ "NamedParameterSpec name: %s, %s%n",
|
||||
name, e.getMessage());
|
||||
continue;
|
||||
}
|
||||
throw new RuntimeException(
|
||||
"Unknown failure in testNamedParameter.");
|
||||
} catch (InvalidAlgorithmParameterException e) {
|
||||
System.out.printf("Expected InvalidAlgorithmParameterException"
|
||||
+ " for NamedParameterSpec name: %s, %s%n",
|
||||
name, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test to generate Public/Private keys using (in)valid coordinate/scalar.
|
||||
*/
|
||||
private static void testInvalidSpec(String provider,
|
||||
String kpgAlgo, String curve) throws Exception {
|
||||
|
||||
NamedParameterSpec spec = new NamedParameterSpec(curve);
|
||||
KeyFactory kf = KeyFactory.getInstance(kpgAlgo, provider);
|
||||
int validLen = curve.equalsIgnoreCase("X448") ? 56 : 32;
|
||||
for (byte[] scalarBytes : new byte[][]{null, new byte[]{},
|
||||
new byte[32], new byte[56], new byte[65535]}) {
|
||||
try {
|
||||
KeySpec privateSpec = new XECPrivateKeySpec(spec, scalarBytes);
|
||||
kf.generatePrivate(privateSpec);
|
||||
if (scalarBytes.length != validLen) {
|
||||
throw new RuntimeException(String.format("testInvalidSpec "
|
||||
+ "should fail but passed when Scalar bytes length "
|
||||
+ "!= %s for curve %s", validLen, curve));
|
||||
}
|
||||
} catch (NullPointerException e) {
|
||||
if (scalarBytes == null) {
|
||||
System.out.printf("Expected NullPointerException for "
|
||||
+ "scalar: %s, %s%n", scalarBytes, e.getMessage());
|
||||
continue;
|
||||
}
|
||||
throw new RuntimeException(e);
|
||||
} catch (InvalidKeySpecException e) {
|
||||
if (scalarBytes.length != validLen) {
|
||||
System.out.printf("Expected InvalidKeySpecException for "
|
||||
+ "scalar length %s and curve %s: %s%n",
|
||||
scalarBytes.length, curve, e.getMessage());
|
||||
continue;
|
||||
}
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
for (BigInteger coordinate : new BigInteger[]{null, BigInteger.ZERO,
|
||||
BigInteger.ONE, new BigInteger("2").pow(255),
|
||||
new BigInteger("2").pow(448)}) {
|
||||
try {
|
||||
KeySpec publicSpec = new XECPublicKeySpec(spec, coordinate);
|
||||
kf.generatePublic(publicSpec);
|
||||
} catch (NullPointerException e) {
|
||||
if (coordinate == null) {
|
||||
System.out.printf("Expected NullPointerException for "
|
||||
+ "coordinate : %s, %s%n", coordinate,
|
||||
e.getMessage());
|
||||
continue;
|
||||
}
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void testInCompatibleSpec(String provider,
|
||||
String kpgAlgo, String curve) throws Exception {
|
||||
|
||||
int validLen = curve.equalsIgnoreCase("X448") ? 56 : 32;
|
||||
NamedParameterSpec spec = new NamedParameterSpec(curve);
|
||||
KeyFactory kf = KeyFactory.getInstance(kpgAlgo, provider);
|
||||
KeySpec privateSpec = new XECPrivateKeySpec(spec, new byte[validLen]);
|
||||
KeySpec publicSpec = new XECPublicKeySpec(spec, BigInteger.ONE);
|
||||
try {
|
||||
kf.generatePrivate(publicSpec);
|
||||
throw new RuntimeException(
|
||||
"testInCompatibleSpec should fail but passed.");
|
||||
} catch (InvalidKeySpecException e) {
|
||||
System.out.printf("Expected XECPublicKeySpec to XECPrivateKeySpec :"
|
||||
+ " %s%n", e.getMessage());
|
||||
}
|
||||
try {
|
||||
kf.generatePublic(privateSpec);
|
||||
throw new RuntimeException(
|
||||
"testInCompatibleSpec should fail but passed.");
|
||||
} catch (InvalidKeySpecException e) {
|
||||
System.out.printf("Expected XECPrivateKeySpec to XECPublicKeySpec :"
|
||||
+ " %s%n", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform KeyAgreement operation.
|
||||
*/
|
||||
private static void startKeyAgreement(String provider, String kaAlgo,
|
||||
String kpgAlgo, int keySize) throws Exception {
|
||||
|
||||
KeyPairGenerator kpg = KeyPairGenerator.getInstance(kpgAlgo, provider);
|
||||
kpg.initialize(keySize);
|
||||
KeyPair kp = kpg.generateKeyPair();
|
||||
KeyAgreement ka = KeyAgreement.getInstance(kaAlgo, provider);
|
||||
ka.init(kp.getPrivate());
|
||||
ka.doPhase(kp.getPublic(), true);
|
||||
ka.generateSecret();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return manipulated encoded bytes.
|
||||
*/
|
||||
private static byte[] modifyEncoded(byte[] encoded) {
|
||||
|
||||
byte[] copy = Arrays.copyOf(encoded, encoded.length);
|
||||
for (int i = 0; i < copy.length; i++) {
|
||||
copy[i] = (byte) ~copy[i];
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Select invalid key sizes for different Key generation algorithms.
|
||||
*/
|
||||
private static int[] selectInvalidKeylength(String kpgInit) {
|
||||
|
||||
int[] keySize = new int[]{};
|
||||
switch (kpgInit) {
|
||||
case "DiffieHellman":
|
||||
keySize = new int[]{256, 513, 1023, 2176, 4032, 6400, 8200};
|
||||
break;
|
||||
case "EC":
|
||||
keySize = new int[]{100, 300};
|
||||
break;
|
||||
case "X25519":
|
||||
keySize = new int[]{100, 300};
|
||||
break;
|
||||
case "X448":
|
||||
keySize = new int[]{100, 500};
|
||||
break;
|
||||
default:
|
||||
throw new RuntimeException("Invalid Algo name " + kpgInit);
|
||||
}
|
||||
return keySize;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue