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:
russell@unturf.com 2026-03-26 17:11:57 -04:00
commit 0a580b313d
70422 changed files with 17213626 additions and 0 deletions

View file

@ -0,0 +1,70 @@
/*
* Copyright (c) 2021, Huawei Technologies Co., Ltd. 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.
*/
package org.openjdk.bench.java.security;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import sun.security.util.DisabledAlgorithmConstraints;
import java.security.AlgorithmConstraints;
import java.security.CryptoPrimitive;
import java.util.concurrent.TimeUnit;
import java.util.EnumSet;
import java.util.Set;
import static sun.security.util.DisabledAlgorithmConstraints.PROPERTY_TLS_DISABLED_ALGS;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(value = 3, jvmArgs = {"--add-exports", "java.base/sun.security.util=ALL-UNNAMED"})
@State(Scope.Thread)
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
public class AlgorithmConstraintsPermits {
AlgorithmConstraints tlsDisabledAlgConstraints;
Set<CryptoPrimitive> primitives = EnumSet.of(CryptoPrimitive.KEY_AGREEMENT);
@Param({"SSLv3", "DES", "NULL", "TLS1.3"})
String algorithm;
@Setup
public void setup() {
tlsDisabledAlgConstraints = new DisabledAlgorithmConstraints(PROPERTY_TLS_DISABLED_ALGS);
}
@Benchmark
public boolean permits() {
return tlsDisabledAlgConstraints.permits(primitives, algorithm, null);
}
}

View file

@ -0,0 +1,132 @@
/*
* Copyright (c) 2021, Dynatrace LLC. 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.
*/
package org.openjdk.bench.java.security;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.openjdk.jmh.annotations.Warmup;
import sun.security.util.Cache;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(value = 3, jvmArgs = {"--add-exports", "java.base/sun.security.util=ALL-UNNAMED"})
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
public class CacheBench {
@State(Scope.Benchmark)
public static class SharedState {
Cache<Integer, Integer> cache;
@Param({"20480", "204800", "5120000"})
int size;
@Param({"86400", "0"})
int timeout;
@Setup
public void setup() {
cache = Cache.newSoftMemoryCache(size, timeout);
IntStream.range(0, size).boxed().forEach(i -> cache.put(i, i));
}
}
@State(Scope.Thread)
public static class GetPutState {
Integer[] intArray;
int index;
@Setup
public void setup(SharedState benchState) {
intArray = IntStream.range(0, benchState.size + 1).boxed().toArray(Integer[]::new);
index = 0;
}
@TearDown(Level.Invocation)
public void tearDown() {
index++;
if (index >= intArray.length) {
index = 0;
}
}
}
@Benchmark
public void put(SharedState benchState, GetPutState state) {
Integer i = state.intArray[state.index];
benchState.cache.put(i, i);
}
@Benchmark
public Integer get(SharedState benchState, GetPutState state) {
Integer i = state.intArray[state.index];
return benchState.cache.get(i);
}
@State(Scope.Thread)
public static class RemoveState {
Integer[] intArray;
int index;
SharedState benchState;
@Setup
public void setup(SharedState benchState) {
this.benchState = benchState;
intArray = IntStream.range(0, benchState.size).boxed().toArray(Integer[]::new);
index = 0;
}
@TearDown(Level.Invocation)
public void tearDown() {
// add back removed item
Integer i = intArray[index];
benchState.cache.put(i, i);
index++;
if (index >= intArray.length) {
index = 0;
}
}
}
@Benchmark
public void remove(SharedState benchState, RemoveState state) {
Integer i = state.intArray[state.index];
benchState.cache.remove(i);
}
}

View file

@ -0,0 +1,60 @@
/*
* Copyright Amazon.com Inc. 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.
*
*/
package org.openjdk.bench.java.security;
import org.openjdk.jmh.annotations.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
@Fork(value = 3, jvmArgs = {"--add-exports", "java.base/sun.security.ssl=ALL-UNNAMED", "--add-opens", "java.base/sun.security.ssl=ALL-UNNAMED"})
@State(Scope.Thread)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
public class CipherSuiteBench {
Method nameOf;
@Param({"TLS_AES_256_GCM_SHA384",
"TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384",
"TLS_DHE_DSS_WITH_AES_128_CBC_SHA256",
"TLS_DHE_RSA_WITH_AES_256_CBC_SHA" })
String cipherSuite;
@Setup
public void initilizeClass() throws ClassNotFoundException, NoSuchMethodException {
Class<?> cs = Class.forName("sun.security.ssl.CipherSuite");
nameOf = cs.getDeclaredMethod("nameOf", String.class);
nameOf.setAccessible(true);
}
@Benchmark
public Object benchmarkCipherSuite() throws InvocationTargetException, IllegalAccessException {
return nameOf.invoke(null, cipherSuite);
}
}

View file

@ -0,0 +1,70 @@
/*
* Copyright (c) 2014, 2022, 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.
*/
package org.openjdk.bench.java.security;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.concurrent.TimeUnit;
/**
* Benchmark measuring DoPrivileged
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(value = 3)
public class DoPrivileged {
private PrivilegedAction<Integer> privilegedAction;
@Setup
public void setup() {
privilegedAction = () -> 42;
}
@SuppressWarnings("removal")
@Benchmark
public int test() {
return AccessController.doPrivileged(privilegedAction);
}
@SuppressWarnings("removal")
@Benchmark
public int testInline() {
return AccessController.doPrivileged((PrivilegedAction<Integer>) () -> 42);
}
}

View file

@ -0,0 +1,95 @@
/*
* Copyright (c) 2014, 2022, 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.
*/
package org.openjdk.bench.java.security;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.concurrent.TimeUnit;
/**
* Benchmark measuring AccessController.getContext
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(value = 3)
public abstract class GetContext {
public static class Top extends GetContext {
@SuppressWarnings("removal")
@Benchmark
public AccessControlContext testNonPriv() {
return AccessController.getContext();
}
@SuppressWarnings("removal")
@Benchmark
public AccessControlContext testPriv() {
PrivilegedAction<AccessControlContext> pa = () -> AccessController.getContext();
return AccessController.doPrivileged(pa);
}
}
public static class Deep extends GetContext {
@Param({"2", "50"})
int depth;
@SuppressWarnings("removal")
private AccessControlContext recurse(int depth) {
if (depth > 0) {
return recurse(depth - 1);
} else {
return AccessController.getContext();
}
}
@SuppressWarnings("removal")
@Benchmark
public AccessControlContext testNonPrivRecurse() {
return recurse(depth);
}
@SuppressWarnings("removal")
@Benchmark
public AccessControlContext testPrivInline() {
PrivilegedAction<AccessControlContext> pa = () -> recurse(depth);
return AccessController.doPrivileged(pa);
}
}
}

View file

@ -0,0 +1,78 @@
/*
* Copyright (c) 2021, 2022, 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.
*/
package org.openjdk.bench.java.security;
import java.security.DigestException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
/**
* Micros for speed of looking up and instantiating MessageDigests.
*/
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(value = 3)
public class GetMessageDigest {
@Param({"md5", "SHA-1", "SHA-256"})
private String digesterName;
private MessageDigest messageDigest;
@Setup
public void setupMessageDigestForCloning() throws NoSuchAlgorithmException {
messageDigest = MessageDigest.getInstance(digesterName);
}
@Benchmark
public MessageDigest getInstance() throws NoSuchAlgorithmException {
return MessageDigest.getInstance(digesterName);
}
@Benchmark
public MessageDigest cloneInstance() throws NoSuchAlgorithmException, CloneNotSupportedException {
return (MessageDigest)messageDigest.clone();
}
@Benchmark
public MessageDigest getInstanceWithProvider() throws NoSuchAlgorithmException, NoSuchProviderException {
return MessageDigest.getInstance(digesterName, "SUN");
}
}

View file

@ -0,0 +1,91 @@
/*
* Copyright (c) 2014, 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.
*/
package org.openjdk.bench.java.security;
import java.security.DigestException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
/**
* Tests various digester algorithms. Sets Fork parameters as these tests are
* rather allocation intensive. Reduced number of forks and iterations as
* benchmarks are stable.
*/
@State(Scope.Thread)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(jvmArgs = {"-Xms1024m", "-Xmx1024m", "-Xmn768m", "-XX:+UseParallelGC"}, value = 3)
public class MessageDigests {
@Param({"64", "16384"})
private int length;
@Param({"md5", "SHA-1", "SHA-224", "SHA-256", "SHA-384", "SHA-512", "SHA3-256", "SHA3-512"})
private String digesterName;
@Param({"DEFAULT"})
protected String provider;
private byte[] inputBytes;
private MessageDigest digester;
@Setup
public void setup() throws NoSuchAlgorithmException, DigestException, NoSuchProviderException {
inputBytes = new byte[length];
new Random(1234567890).nextBytes(inputBytes);
if ("DEFAULT".equals(provider)) {
digester = MessageDigest.getInstance(digesterName);
} else {
digester = MessageDigest.getInstance(digesterName, provider);
}
}
@Benchmark
public byte[] digest() throws DigestException {
return digester.digest(inputBytes);
}
@Benchmark
public byte[] getAndDigest() throws DigestException, NoSuchAlgorithmException, NoSuchProviderException {
MessageDigest md;
if ("DEFAULT".equals(provider)) {
md = MessageDigest.getInstance(digesterName);
} else {
md = MessageDigest.getInstance(digesterName, provider);
}
return md.digest(inputBytes);
}
}

View file

@ -0,0 +1,186 @@
/*
* Copyright (c) 2020, 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.
*/
package org.openjdk.bench.java.security;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.*;
/**
* Tests various algorithm settings for PKCS12 keystores.
*/
@State(Scope.Benchmark)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
@BenchmarkMode(Mode.AverageTime)
@Fork(jvmArgs = {"-Xms1024m", "-Xmx1024m", "-Xmn768m", "-XX:+UseParallelGC"}, value = 3)
public class PKCS12KeyStores {
private static final char[] PASS = "changeit".toCharArray();
private Key pk;
private Certificate[] certs;
// Several pkcs12 keystores in byte arrays
private byte[] bw2048;
private byte[] bw50000; // Default old
private byte[] bs50000;
private byte[] bs10000; // Default new
private byte[] bs2048;
// Decodes HEX string to byte array
private static byte[] xeh(String in) {
return new BigInteger(in, 16).toByteArray();
}
@Setup
public void setup() throws Exception {
// Just generate a keypair and dump getEncoded() of key and cert.
byte[] x1 = xeh("3041020100301306072A8648CE3D020106082A8648CE3D03" +
"0107042730250201010420B561D1FBE150488508BBE8FF4540F09057" +
"58712F5D2D3CC80F9A15BA5D481117");
byte[] x2 = xeh("3082012D3081D5A00302010202084EE6ECC5585640A7300A" +
"06082A8648CE3D040302300C310A30080603550403130161301E170D" +
"3230313131373230343730355A170D3233303831343230343730355A" +
"300C310A300806035504031301613059301306072A8648CE3D020106" +
"082A8648CE3D030107034200041E761F511841602E272B40A021995D" +
"1BD828DDC7F71412D6A66CC0CB858C856D32C58273E494676D1D2B05" +
"B8E9B08207A122265C2AA5FCBDCE19E5E88CA7A1B6A321301F301D06" +
"03551D0E04160414173F278D77096E5C8EA182D12F147694587B5D9A" +
"300A06082A8648CE3D04030203470030440220760CEAF1FA7041CB8C" +
"1CA80AF60E4F9C9D5136D96B2AF0AAA9440F79561C44E502205D5C72" +
"886C92B95A681C4393C67AAEC8DA9FD7910FF9BF2BCB721AE71D1B6F88");
KeyFactory kf = KeyFactory.getInstance("EC");
pk = kf.generatePrivate(new PKCS8EncodedKeySpec(x1));
CertificateFactory cf = CertificateFactory.getInstance("X.509");
certs = new Certificate[]{cf.generateCertificate(new ByteArrayInputStream(x2))};
bw2048 = outweak2048();
bw50000 = outweak50000_Old();
bs50000 = outstrong50000();
bs10000 = outstrong10000_New();
bs2048 = outstrong2048();
}
// Reads in a pkcs12 keystore
private KeyStore in(byte[] b) throws Exception {
KeyStore ks = KeyStore.getInstance("pkcs12");
ks.load(new ByteArrayInputStream(b), PASS);
if (!ks.getCertificate("a").getPublicKey().getAlgorithm().equals(
ks.getKey("a", PASS).getAlgorithm())) {
throw new RuntimeException("Not same alg");
}
return ks;
}
// Generates a pkcs12 keystore with the specified algorithm/ic
private byte[] out(String cAlg, String cIc, String kAlg, String kIc,
String mAlg, String mIc) throws Exception {
System.setProperty("keystore.pkcs12.certProtectionAlgorithm", cAlg);
System.setProperty("keystore.pkcs12.certPbeIterationCount", cIc);
System.setProperty("keystore.pkcs12.keyProtectionAlgorithm", kAlg);
System.setProperty("keystore.pkcs12.keyPbeIterationCount", kIc);
System.setProperty("keystore.pkcs12.macAlgorithm", mAlg);
System.setProperty("keystore.pkcs12.macIterationCount", mIc);
KeyStore ks = KeyStore.getInstance("pkcs12");
ks.load(null, null);
ks.setKeyEntry("a", pk, PASS, certs);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ks.store(bout, PASS);
return bout.toByteArray();
}
// Benchmark methods start here:
// Reading a keystore
@Benchmark
public KeyStore inweak2048() throws Exception {
return in(bw2048);
}
@Benchmark
public KeyStore inweak50000_Old() throws Exception {
return in(bw50000);
}
@Benchmark
public KeyStore instrong50000() throws Exception {
return in(bs50000);
}
@Benchmark
public KeyStore instrong10000_New() throws Exception {
return in(bs10000);
}
@Benchmark
public KeyStore instrong2048() throws Exception {
return in(bs2048);
}
// Writing a keystore
@Benchmark
public byte[] outweak2048() throws Exception {
return out("PBEWithSHA1AndRC2_40", "2048",
"PBEWithSHA1AndDESede", "2048",
"HmacPBESHA1", "2048");
}
@Benchmark
public byte[] outweak50000_Old() throws Exception {
return out("PBEWithSHA1AndRC2_40", "50000",
"PBEWithSHA1AndDESede", "50000",
"HmacPBESHA1", "100000");
// Attention: 100000 is old default Mac ic
}
@Benchmark
public byte[] outstrong50000() throws Exception {
return out("PBEWithHmacSHA256AndAES_256", "50000",
"PBEWithHmacSHA256AndAES_256", "50000",
"HmacPBESHA256", "100000");
// Attention: 100000 is old default Mac ic
}
@Benchmark
public byte[] outstrong10000_New() throws Exception {
return out("PBEWithHmacSHA256AndAES_256", "10000",
"PBEWithHmacSHA256AndAES_256", "10000",
"HmacPBESHA256", "10000");
}
@Benchmark
public byte[] outstrong2048() throws Exception {
return out("PBEWithHmacSHA256AndAES_256", "2048",
"PBEWithHmacSHA256AndAES_256", "2048",
"HmacPBESHA256", "2048");
}
}

View file

@ -0,0 +1,78 @@
/*
* Copyright (c) 2020, 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.
*/
package org.openjdk.bench.java.security;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.security.Permissions;
import java.security.UnresolvedPermission;
import java.util.concurrent.TimeUnit;
/**
* Benchmark measuring Permissions.implies
*/
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(3)
@State(Scope.Thread)
public class PermissionsImplies {
private Permissions withPermission = new Permissions();
private Permissions withoutPermission = new Permissions();
private Permissions withUnresolvedPermission = new Permissions();
private RuntimePermission permission = new RuntimePermission("exitVM");
@Setup
public void setup() {
withPermission.add(permission);
withUnresolvedPermission.add(permission);
withUnresolvedPermission.add(new UnresolvedPermission("java.lang.FilePermission", "foo", "write", null));
}
@Benchmark
public boolean withoutPermission() {
return withoutPermission.implies(permission);
}
@Benchmark
public boolean withPermission() {
return withPermission.implies(permission);
}
@Benchmark
public boolean withUnresolvedPermission() {
return withUnresolvedPermission.implies(permission);
}
}

View file

@ -0,0 +1,130 @@
/*
* Copyright (c) 2022, 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.
*/
package org.openjdk.bench.java.security;
import java.security.*;
import java.net.*;
import java.io.*;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.bench.util.InMemoryJavaCompiler;
@State(Scope.Thread)
@OutputTimeUnit(TimeUnit.SECONDS)
@Warmup(iterations = 5, time = 2)
@Measurement(iterations = 5, time = 2)
@BenchmarkMode(Mode.Throughput)
public class ProtectionDomainBench {
@Param({"100"})
public int numberOfClasses;
@Param({"10"})
public int numberOfCodeSources;
static byte[][] compiledClasses;
static Class[] loadedClasses;
static String[] classNames;
static int index = 0;
static CodeSource[] cs;
static String B(int count) {
return "public class B" + count + " {"
+ " static int intField;"
+ " public static void compiledMethod() { "
+ " intField++;"
+ " }"
+ "}";
}
@Setup(Level.Trial)
public void setupClasses() throws Exception {
compiledClasses = new byte[numberOfClasses][];
loadedClasses = new Class[numberOfClasses];
classNames = new String[numberOfClasses];
cs = new CodeSource[numberOfCodeSources];
for (int i = 0; i < numberOfCodeSources; i++) {
@SuppressWarnings("deprecation")
URL u = new URL("file:/tmp/duke" + i);
cs[i] = new CodeSource(u, (java.security.cert.Certificate[]) null);
}
for (int i = 0; i < numberOfClasses; i++) {
classNames[i] = "B" + i;
compiledClasses[i] = InMemoryJavaCompiler.compile(classNames[i], B(i));
}
}
static class ProtectionDomainBenchLoader extends SecureClassLoader {
ProtectionDomainBenchLoader() {
super();
}
ProtectionDomainBenchLoader(ClassLoader parent) {
super(parent);
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
if (name.equals(classNames[index] /* "B" + index */)) {
assert compiledClasses[index] != null;
return defineClass(name, compiledClasses[index] , 0, (compiledClasses[index]).length, cs[index % cs.length] );
} else {
return super.findClass(name);
}
}
}
void work() throws ClassNotFoundException {
ProtectionDomainBench.ProtectionDomainBenchLoader loader1 = new
ProtectionDomainBench.ProtectionDomainBenchLoader();
for (index = 0; index < compiledClasses.length; index++) {
Class c = loader1.findClass(classNames[index]);
loadedClasses[index] = c;
}
}
@Benchmark
@Fork(value = 3)
public void noSecurityManager() throws ClassNotFoundException {
work();
}
}

View file

@ -0,0 +1,220 @@
/*
* Copyright (c) 2022, 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.
*/
package org.openjdk.bench.java.security;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.nio.ByteBuffer;
import java.security.KeyStore;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManagerFactory;
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
@State(Scope.Thread)
@Warmup(iterations = 5, time = 5)
@Measurement(iterations = 5, time = 5)
@Fork(value = 3)
public class SSLHandshake {
// one global server context
private static final SSLContext sslServerCtx = getServerContext();
// per-thread client contexts
private SSLContext sslClientCtx;
private SSLEngine clientEngine;
private ByteBuffer clientOut = ByteBuffer.allocate(5);
private ByteBuffer clientIn = ByteBuffer.allocate(1 << 15);
private SSLEngine serverEngine;
private ByteBuffer serverOut = ByteBuffer.allocate(5);
private ByteBuffer serverIn = ByteBuffer.allocate(1 << 15);
private ByteBuffer cTOs = ByteBuffer.allocateDirect(1 << 16);
private ByteBuffer sTOc = ByteBuffer.allocateDirect(1 << 16);
@Param({"true", "false"})
boolean resume;
@Param({
"TLSv1.2-secp256r1",
"TLSv1.3-x25519", "TLSv1.3-secp256r1", "TLSv1.3-secp384r1",
"TLSv1.3-X25519MLKEM768", "TLSv1.3-SecP256r1MLKEM768", "TLSv1.3-SecP384r1MLKEM1024"
})
String versionAndGroup;
private String tlsVersion;
private String namedGroup;
private static SSLContext getServerContext() {
try {
KeyStore ks = TestCertificates.getKeyStore();
KeyManagerFactory kmf = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, new char[0]);
SSLContext sslCtx = SSLContext.getInstance("TLS");
sslCtx.init(kmf.getKeyManagers(), null, null);
return sslCtx;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Setup(Level.Trial)
public void init() throws Exception {
String[] components = versionAndGroup.split("-", 2);
tlsVersion = components[0];
namedGroup = components[1];
KeyStore ts = TestCertificates.getTrustStore();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ts);
SSLContext sslCtx = SSLContext.getInstance(tlsVersion);
sslCtx.init(null, tmf.getTrustManagers(), null);
sslClientCtx = sslCtx;
}
private HandshakeStatus checkResult(SSLEngine engine, SSLEngineResult result) {
HandshakeStatus hsStatus = result.getHandshakeStatus();
if (hsStatus == HandshakeStatus.NEED_TASK) {
Runnable runnable;
while ((runnable = engine.getDelegatedTask()) != null) {
runnable.run();
}
hsStatus = engine.getHandshakeStatus();
}
return hsStatus;
}
/**
* This benchmark measures the time needed to perform a TLS handshake.
* Data is exchanged using a pair of ByteBuffers.
* The client and the server both operate on the same thread.
*/
@Benchmark
public SSLSession doHandshake() throws Exception {
createSSLEngines();
boolean isCtoS = true;
for (;;) {
HandshakeStatus result;
if (isCtoS) {
result = checkResult(clientEngine,
clientEngine.wrap(clientOut, cTOs)
);
cTOs.flip();
checkResult(serverEngine,
serverEngine.unwrap(cTOs, serverIn)
);
cTOs.compact();
if (result == HandshakeStatus.NEED_UNWRAP) {
isCtoS = false;
} else if (result == HandshakeStatus.FINISHED) {
break;
} else if (result != HandshakeStatus.NEED_WRAP) {
throw new Exception("Unexpected result "+result);
}
} else {
result = checkResult(serverEngine,
serverEngine.wrap(serverOut, sTOc)
);
sTOc.flip();
checkResult(clientEngine,
clientEngine.unwrap(sTOc, clientIn)
);
sTOc.compact();
if (result == HandshakeStatus.NEED_UNWRAP) {
isCtoS = true;
} else if (result == HandshakeStatus.FINISHED) {
break;
} else if (result != HandshakeStatus.NEED_WRAP) {
throw new Exception("Unexpected result "+result);
}
}
}
SSLSession session = clientEngine.getSession();
if (resume) {
// TLS 1.3 needs another wrap/unwrap to deliver a session ticket
serverEngine.wrap(serverOut, sTOc);
sTOc.flip();
clientEngine.unwrap(sTOc, clientIn);
sTOc.compact();
} else {
// invalidate TLS1.2 session. TLS 1.3 doesn't care
session.invalidate();
}
return session;
}
private void createSSLEngines() {
/*
* Configure the serverEngine to act as a server in the SSL/TLS
* handshake.
*/
serverEngine = sslServerCtx.createSSLEngine();
serverEngine.setUseClientMode(false);
/*
* Similar to above, but using client mode instead.
*/
clientEngine = sslClientCtx.createSSLEngine("client", 80);
clientEngine.setUseClientMode(true);
// Set the key exchange named group in client and server engines
SSLParameters clientParams = clientEngine.getSSLParameters();
clientParams.setNamedGroups(new String[]{namedGroup});
clientEngine.setSSLParameters(clientParams);
SSLParameters serverParams = serverEngine.getSSLParameters();
serverParams.setNamedGroups(new String[]{namedGroup});
serverEngine.setSSLParameters(serverParams);
}
}

View file

@ -0,0 +1,43 @@
/*
* Copyright Amazon.com Inc. 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.
*
*/
package org.openjdk.bench.java.security;
import org.openjdk.jmh.annotations.*;
import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(value = 3)
public class SecureRandomBench {
@Benchmark
public SecureRandom create() throws Exception {
return new SecureRandom();
}
}

View file

@ -0,0 +1,257 @@
/*
* Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (C) 2022, Tencent. 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.
*/
package org.openjdk.bench.java.security;
import org.openjdk.jmh.annotations.*;
import java.security.*;
import java.security.spec.*;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(jvmArgs = {"-Xms1024m", "-Xmx1024m", "-Xmn768m", "-XX:+UseParallelGC"}, value = 3)
public class Signatures {
@State(Scope.Benchmark)
public static class test01 {
@Param({"64", "512", "2048", "16384"})
private int messageLength;
@Param({"secp256r1", "secp384r1", "secp521r1"})
private String algorithm;
}
@State(Scope.Benchmark)
public static class test02 {
@Param({"64", "512", "2048", "16384"})
private int messageLength;
@Param({"Ed25519", "Ed448"})
private String algorithm;
}
@State(Scope.Benchmark)
public static class test03 {
@Param({"64", "512", "2048", "16384"})
private int messageLength;
@Param({"SHA256withDSA", "SHA384withDSA", "SHA512withDSA"})
private String algorithm;
}
@State(Scope.Benchmark)
public static class test04 {
@Param({"64", "512", "2048", "16384"})
private int messageLength;
@Param({"SHA256withRSA", "SHA384withRSA", "SHA512withRSA"})
private String algorithm;
}
@State(Scope.Benchmark)
public static class test05 {
@Param({"64", "512", "2048", "16384"})
private int messageLength;
@Param({"SHA256", "SHA384", "SHA512"})
private String algorithm;
}
@Benchmark
public byte[] ECDSA(s1 state) throws Exception {
state.signer.update(state.message);
return state.signer.sign();
}
@Benchmark
public byte[] EdDSA(s2 state) throws Exception {
state.signer.update(state.message);
return state.signer.sign();
}
@Benchmark
public byte[] DSA(s3 state) throws Exception {
state.signer.update(state.message);
return state.signer.sign();
}
@Benchmark
public byte[] RSA(s4 state) throws Exception {
state.signer.update(state.message);
return state.signer.sign();
}
@Benchmark
public byte[] RSASSAPSS(s5 state) throws Exception {
state.signer.update(state.message);
return state.signer.sign();
}
@State(Scope.Thread)
public static class s1 {
private Signature signer;
private byte[] message;
@Setup
public void setup(test01 test) throws Exception {
message = new byte[test.messageLength];
(new Random(System.nanoTime())).nextBytes(message);
String signName = switch (test.algorithm) {
case "secp256r1" -> "SHA256withECDSA";
case "secp384r1" -> "SHA384withECDSA";
case "secp521r1" -> "SHA512withECDSA";
default -> throw new RuntimeException();
};
AlgorithmParameters params =
AlgorithmParameters.getInstance("EC", "SunEC");
params.init(new ECGenParameterSpec(test.algorithm));
ECGenParameterSpec ecParams =
params.getParameterSpec(ECGenParameterSpec.class);
KeyPairGenerator kpg =
KeyPairGenerator.getInstance("EC", "SunEC");
kpg.initialize(ecParams);
KeyPair kp = kpg.generateKeyPair();
signer = Signature.getInstance(signName, "SunEC");
signer.initSign(kp.getPrivate());
}
}
@State(Scope.Thread)
public static class s2 {
private Signature signer;
private byte[] message;
@Setup
public void setup(test02 test) throws Exception {
message = new byte[test.messageLength];
(new Random(System.nanoTime())).nextBytes(message);
KeyPairGenerator kpg =
KeyPairGenerator.getInstance(test.algorithm, "SunEC");
NamedParameterSpec spec = new NamedParameterSpec(test.algorithm);
kpg.initialize(spec);
KeyPair kp = kpg.generateKeyPair();
signer = Signature.getInstance(test.algorithm, "SunEC");
signer.initSign(kp.getPrivate());
}
}
@State(Scope.Thread)
public static class s3 {
private Signature signer;
private byte[] message;
@Setup
public void setup(test03 test) throws Exception {
message = new byte[test.messageLength];
(new Random(System.nanoTime())).nextBytes(message);
int keyLength = switch (test.algorithm) {
case "SHA256withDSA" -> 2048;
case "SHA384withDSA" -> 3072;
case "SHA512withDSA" -> 3072;
default -> throw new RuntimeException();
};
KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
kpg.initialize(keyLength);
KeyPair kp = kpg.generateKeyPair();
signer = Signature.getInstance(test.algorithm);
signer.initSign(kp.getPrivate());
}
}
@State(Scope.Thread)
public static class s4 {
private Signature signer;
private byte[] message;
@Setup
public void setup(test04 test) throws Exception {
message = new byte[test.messageLength];
(new Random(System.nanoTime())).nextBytes(message);
int keyLength = switch (test.algorithm) {
case "SHA256withRSA" -> 2048;
case "SHA384withRSA" -> 3072;
case "SHA512withRSA" -> 4096;
default -> throw new RuntimeException();
};
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(keyLength);
KeyPair kp = kpg.generateKeyPair();
signer = Signature.getInstance(test.algorithm);
signer.initSign(kp.getPrivate());
}
}
@State(Scope.Thread)
public static class s5 {
private Signature signer;
private byte[] message;
@Setup
public void setup(test05 test) throws Exception {
message = new byte[test.messageLength];
(new Random(System.nanoTime())).nextBytes(message);
int keyLength = switch (test.algorithm) {
case "SHA256" -> 2048;
case "SHA384" -> 3072;
case "SHA512" -> 4096;
default -> throw new RuntimeException();
};
PSSParameterSpec spec = switch (test.algorithm) {
case "SHA256" ->
new PSSParameterSpec(
"SHA-256", "MGF1",
MGF1ParameterSpec.SHA256,
32, PSSParameterSpec.TRAILER_FIELD_BC);
case "SHA384" ->
new PSSParameterSpec(
"SHA-384", "MGF1",
MGF1ParameterSpec.SHA384,
48, PSSParameterSpec.TRAILER_FIELD_BC);
case "SHA512" ->
new PSSParameterSpec(
"SHA-512", "MGF1",
MGF1ParameterSpec.SHA512,
64, PSSParameterSpec.TRAILER_FIELD_BC);
default -> throw new RuntimeException();
};
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSASSA-PSS");
kpg.initialize(keyLength);
KeyPair kp = kpg.generateKeyPair();
signer = Signature.getInstance("RSASSA-PSS");
signer.setParameter(spec);
signer.initSign(kp.getPrivate());
}
}
}

View file

@ -0,0 +1,148 @@
/*
* Copyright (c) 2022, 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.
*/
package org.openjdk.bench.java.security;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
/**
* This class contains a 3-certificate chain for use in TLS tests.
* The method {@link #getKeyStore()} returns a keystore with a single entry
* containing one server+one intermediate CA certificate.
* Server's CN and subjectAltName are both set to "client"
*
* The method {@link #getTrustStore()} returns a keystore with a single entry
* containing the root CA certificate used for signing the intermediate CA.
*/
class TestCertificates {
// "/C=US/ST=CA/O=Test Root CA, Inc."
// basicConstraints=critical, CA:true
// subjectKeyIdentifier = hash
// authorityKeyIdentifier = keyid:always
// keyUsage = keyCertSign
private static final String ROOT_CA_CERT =
"-----BEGIN CERTIFICATE-----\n" +
"MIIB0jCCAXigAwIBAgIUE+wUdx22foJXSQzD3hpCNCqITLEwCgYIKoZIzj0EAwIw\n" +
"NzELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMRswGQYDVQQKDBJUZXN0IFJvb3Qg\n" +
"Q0EsIEluYy4wIBcNMjIwNDEyMDcxMzMzWhgPMjEyMjAzMTkwNzEzMzNaMDcxCzAJ\n" +
"BgNVBAYTAlVTMQswCQYDVQQIDAJDQTEbMBkGA1UECgwSVGVzdCBSb290IENBLCBJ\n" +
"bmMuMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEBKye/mwO0V0WLr71tf8auFEz\n" +
"EmqhaYWauaP17Fb33fRAeG8aVp9c4B0isv/VgcqSTRMG0SJjbx7ttSYwR/JNhqNg\n" +
"MF4wDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUpfGt4bjadmVzWeXAiSMp9pLU\n" +
"RMkwHwYDVR0jBBgwFoAUpfGt4bjadmVzWeXAiSMp9pLURMkwCwYDVR0PBAQDAgIE\n" +
"MAoGCCqGSM49BAMCA0gAMEUCIBF8YyD5BBuhkFNV/3rNmvvMuvWUAECJ8rrUg8kr\n" +
"J8zpAiEAzbZQsC/IZ0wVNd4lqHn6/Ih5v7vhCgkg95KCP1NhBnU=\n" +
"-----END CERTIFICATE-----";
// "/C=US/ST=CA/O=Test Intermediate CA, Inc."
// basicConstraints=critical, CA:true, pathlen:0
// subjectKeyIdentifier = hash
// authorityKeyIdentifier = keyid:always
// keyUsage = keyCertSign
private static final String CA_CERT =
"-----BEGIN CERTIFICATE-----\n" +
"MIIB3TCCAYOgAwIBAgIUQ+lTbsDcIQ1UUg0RGdpJB6JMXpcwCgYIKoZIzj0EAwIw\n" +
"NzELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMRswGQYDVQQKDBJUZXN0IFJvb3Qg\n" +
"Q0EsIEluYy4wIBcNMjIwNDEyMDcxMzM0WhgPMjEyMjAzMTkwNzEzMzRaMD8xCzAJ\n" +
"BgNVBAYTAlVTMQswCQYDVQQIDAJDQTEjMCEGA1UECgwaVGVzdCBJbnRlcm1lZGlh\n" +
"dGUgQ0EsIEluYy4wWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQ7DsKCSQkP5oT2\n" +
"Wx0gf40N+H/F75w1YmPm6dp2wiQ6JPMN/4En87Ylx0ISJkeXJLxrbLvu2xZ+aonM\n" +
"kckNh/ERo2MwYTASBgNVHRMBAf8ECDAGAQH/AgEAMB0GA1UdDgQWBBTqP6hB5Ibr\n" +
"aivot/zWSMKr8ZkCVzAfBgNVHSMEGDAWgBSl8a3huNp2ZXNZ5cCJIyn2ktREyTAL\n" +
"BgNVHQ8EBAMCAgQwCgYIKoZIzj0EAwIDSAAwRQIhAM0vCIV938aqGAEmELIA8Kc4\n" +
"X+kOc4LGE0R7sMiBAbXuAiBlbNVaskKYRHIEGHEtIWet6Ufi3w9NMrycEbBZ+v5o\n" +
"gA==\n" +
"-----END CERTIFICATE-----";
// "/C=US/ST=CA/O=Test Server/CN=client"
// subjectKeyIdentifier = hash
// authorityKeyIdentifier = keyid:always
// keyUsage = digitalSignature
// subjectAltName = DNS:client
private static final String SERVER_CERT =
"-----BEGIN CERTIFICATE-----\n" +
"MIIB5TCCAYygAwIBAgIUNWe754lZoDc6wNs9Vsev/h9TMicwCgYIKoZIzj0EAwIw\n" +
"PzELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMSMwIQYDVQQKDBpUZXN0IEludGVy\n" +
"bWVkaWF0ZSBDQSwgSW5jLjAgFw0yMjA0MTIwNzEzMzRaGA8yMTIyMDMxOTA3MTMz\n" +
"NFowQTELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMRQwEgYDVQQKDAtUZXN0IFNl\n" +
"cnZlcjEPMA0GA1UEAwwGY2xpZW50MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE\n" +
"o6zUz5QmzmfHL2xRifvaJenggck/Dlu6KC4v4rGXug69R7tWKWuRUsbSFLy29Rii\n" +
"F7V1wjFhsyGAzNyKf/KlmaNiMGAwHQYDVR0OBBYEFHz32VSnXBF4WdLDOe7e3hF9\n" +
"yDxmMB8GA1UdIwQYMBaAFOo/qEHkhutqK+i3/NZIwqvxmQJXMAsGA1UdDwQEAwIH\n" +
"gDARBgNVHREECjAIggZjbGllbnQwCgYIKoZIzj0EAwIDRwAwRAIgWsCn2LIElgVs\n" +
"VihcQznvBemWneEcmnp/Bw+lwk86KQ8CIA3loL7P/0/Ft/xXtClxJfyxEoZ/Az1n\n" +
"HTTjbe6ZnN0Y\n" +
"-----END CERTIFICATE-----";
private static final String serverkey =
//"-----BEGIN PRIVATE KEY-----\n" +
"MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgKb9cKLH++BgA9CL1\n" +
"cdCLHpD0poPJ/uAkafGXDJBR67ChRANCAASjrNTPlCbOZ8cvbFGJ+9ol6eCByT8O\n" +
"W7ooLi/isZe6Dr1Hu1Ypa5FSxtIUvLb1GKIXtXXCMWGzIYDM3Ip/8qWZ";
// + "\n-----END PRIVATE KEY-----";
private TestCertificates() {}
public static KeyStore getKeyStore() throws GeneralSecurityException, IOException {
KeyStore result = KeyStore.getInstance(KeyStore.getDefaultType());
result.load(null, null);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate serverCert = cf.generateCertificate(
new ByteArrayInputStream(
SERVER_CERT.getBytes(StandardCharsets.ISO_8859_1)));
Certificate caCert = cf.generateCertificate(
new ByteArrayInputStream(
CA_CERT.getBytes(StandardCharsets.ISO_8859_1)));
KeyFactory kf = KeyFactory.getInstance("EC");
PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(
Base64.getMimeDecoder().decode(serverkey));
Key key = kf.generatePrivate(ks);
Certificate[] chain = {serverCert, caCert};
result.setKeyEntry("server", key, new char[0], chain);
return result;
}
public static KeyStore getTrustStore() throws GeneralSecurityException, IOException {
KeyStore result = KeyStore.getInstance(KeyStore.getDefaultType());
result.load(null, null);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate rootcaCert = cf.generateCertificate(
new ByteArrayInputStream(
ROOT_CA_CERT.getBytes(StandardCharsets.ISO_8859_1)));
result.setCertificateEntry("testca", rootcaCert);
return result;
}
}