diff --git a/.clang-format b/.clang-format
index c05d06f80..ad30c81a3 100644
--- a/.clang-format
+++ b/.clang-format
@@ -1,18 +1,21 @@
---
Language: Cpp
-BasedOnStyle: Google
+BasedOnStyle: Google
AccessModifierOffset: -4
AllowShortFunctionsOnASingleLine: Empty
ColumnLimit: 100
IndentWidth: 4
ContinuationIndentWidth: 8
TypenameMacros: ['STACK_OF']
+AlignEscapedNewlines: Left
+AlignAfterOpenBracket: Align
---
Language: Java
BasedOnStyle: Google
ColumnLimit: 100
IndentWidth: 4
ContinuationIndentWidth: 8
+AlignAfterOpenBracket: Align
JavaImportGroups:
- android
- androidx
diff --git a/PREUPLOAD.cfg b/PREUPLOAD.cfg
deleted file mode 100644
index 4c8d13794..000000000
--- a/PREUPLOAD.cfg
+++ /dev/null
@@ -1,3 +0,0 @@
-[Builtin Hooks]
-commit_msg_test_field = true
-clang_format = true
diff --git a/android/lint.xml b/android/lint.xml
index 5d43d7ff6..8ad971986 100644
--- a/android/lint.xml
+++ b/android/lint.xml
@@ -28,4 +28,10 @@
+
+
+
+
+
+
diff --git a/android/src/main/java/org/conscrypt/ConscryptNetworkSecurityPolicy.java b/android/src/main/java/org/conscrypt/ConscryptNetworkSecurityPolicy.java
new file mode 100644
index 000000000..4f5f0e6ad
--- /dev/null
+++ b/android/src/main/java/org/conscrypt/ConscryptNetworkSecurityPolicy.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.conscrypt;
+
+import org.conscrypt.metrics.CertificateTransparencyVerificationReason;
+
+/**
+ * A default NetworkSecurityPolicy for unbundled Android.
+ */
+@Internal
+public class ConscryptNetworkSecurityPolicy implements NetworkSecurityPolicy {
+ public static ConscryptNetworkSecurityPolicy getDefault() {
+ return new ConscryptNetworkSecurityPolicy();
+ }
+
+ @Override
+ public boolean isCertificateTransparencyVerificationRequired(String hostname) {
+ return false;
+ }
+
+ @Override
+ public CertificateTransparencyVerificationReason getCertificateTransparencyVerificationReason(
+ String hostname) {
+ return CertificateTransparencyVerificationReason.UNKNOWN;
+ }
+
+ @Override
+ public DomainEncryptionMode getDomainEncryptionMode(String hostname) {
+ return DomainEncryptionMode.UNKNOWN;
+ }
+}
diff --git a/android/src/main/java/org/conscrypt/ConscryptStatsLog.java b/android/src/main/java/org/conscrypt/ConscryptStatsLog.java
new file mode 100644
index 000000000..19ab61631
--- /dev/null
+++ b/android/src/main/java/org/conscrypt/ConscryptStatsLog.java
@@ -0,0 +1,26 @@
+/*
+ * Copyright 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.conscrypt;
+
+/**
+ * Stub class for logging statistics events.
+ */
+public class ConscryptStatsLog {
+ public static final int TLS_HANDSHAKE_REPORTED = 0;
+
+ public static void write(int code, boolean arg1, int arg2, int arg3, int arg4) {}
+}
diff --git a/android/src/main/java/org/conscrypt/Platform.java b/android/src/main/java/org/conscrypt/Platform.java
index 65fc084ad..681842ff5 100644
--- a/android/src/main/java/org/conscrypt/Platform.java
+++ b/android/src/main/java/org/conscrypt/Platform.java
@@ -59,11 +59,13 @@
import java.util.Collection;
import java.util.Collections;
import java.util.List;
+import java.util.function.Supplier;
import javax.net.ssl.SNIHostName;
import javax.net.ssl.SNIMatcher;
import javax.net.ssl.SNIServerName;
import javax.net.ssl.SSLEngine;
+import javax.net.ssl.SSLException;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
@@ -82,13 +84,14 @@ final public class Platform {
private static boolean FILTERED_TLS_V1 = true;
private static Method m_getCurveName;
+
static {
NativeCrypto.setTlsV1DeprecationStatus(DEPRECATED_TLS_V1, ENABLED_TLS_V1);
try {
m_getCurveName = ECParameterSpec.class.getDeclaredMethod("getCurveName");
m_getCurveName.setAccessible(true);
} catch (Exception ignored) {
- //Ignored
+ // Ignored
}
}
@@ -146,7 +149,7 @@ public static void setCurveName(ECParameterSpec spec, String curveName) {
Method setCurveName = spec.getClass().getDeclaredMethod("setCurveName", String.class);
setCurveName.invoke(spec, curveName);
} catch (Exception ignored) {
- //Ignored
+ // Ignored
}
}
@@ -212,15 +215,16 @@ public static void setSocketWriteTimeout(Socket s, long timeoutMillis) throws So
return;
}
- Method m_setsockoptTimeval = instance_os.getClass().getMethod("setsockoptTimeval",
- FileDescriptor.class, int.class, int.class, c_structTimeval);
+ Method m_setsockoptTimeval =
+ instance_os.getClass().getMethod("setsockoptTimeval", FileDescriptor.class,
+ int.class, int.class, c_structTimeval);
if (m_setsockoptTimeval == null) {
Log.w(TAG, "setsockoptTimeval == null; not setting socket write timeout");
return;
}
m_setsockoptTimeval.invoke(instance_os, fd, f_SOL_SOCKET.get(null),
- f_SO_SNDTIMEO.get(null), timeval);
+ f_SO_SNDTIMEO.get(null), timeval);
} catch (Exception e) {
// We don't want to spam the logcat since this isn't a fatal error, but we want to know
// why this might be happening.
@@ -257,13 +261,14 @@ private static void setSSLParametersOnImpl(SSLParameters params, SSLParametersIm
try {
Method getNamedGroupsMethod = params.getClass().getMethod("getNamedGroups");
impl.setNamedGroups((String[]) getNamedGroupsMethod.invoke(params));
- } catch (NoSuchMethodException | IllegalArgumentException e) {
+ } catch (NoSuchMethodException | IllegalArgumentException | IllegalAccessException
+ | InvocationTargetException e) {
// Do nothing.
}
}
- public static void setSSLParameters(
- SSLParameters params, SSLParametersImpl impl, AbstractConscryptSocket socket) {
+ public static void setSSLParameters(SSLParameters params, SSLParametersImpl impl,
+ AbstractConscryptSocket socket) {
try {
setSSLParametersOnImpl(params, impl);
@@ -274,16 +279,16 @@ public static void setSSLParameters(
}
}
} catch (NoSuchMethodException ignored) {
- //Ignored
+ // Ignored
} catch (IllegalAccessException ignored) {
- //Ignored
+ // Ignored
} catch (InvocationTargetException e) {
throw new RuntimeException(e.getCause());
}
}
- public static void setSSLParameters(
- SSLParameters params, SSLParametersImpl impl, ConscryptEngine engine) {
+ public static void setSSLParameters(SSLParameters params, SSLParametersImpl impl,
+ ConscryptEngine engine) {
try {
setSSLParametersOnImpl(params, impl);
@@ -294,9 +299,9 @@ public static void setSSLParameters(
}
}
} catch (NoSuchMethodException ignored) {
- //Ignored
+ // Ignored
} catch (IllegalAccessException ignored) {
- //Ignored
+ // Ignored
} catch (InvocationTargetException e) {
throw new RuntimeException(e.getCause());
}
@@ -323,8 +328,8 @@ private static void getSSLParametersFromImpl(SSLParameters params, SSLParameters
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
Method m_setEndpointIdentificationAlgorithm =
params.getClass().getMethod("setEndpointIdentificationAlgorithm", String.class);
- m_setEndpointIdentificationAlgorithm.invoke(
- params, impl.getEndpointIdentificationAlgorithm());
+ m_setEndpointIdentificationAlgorithm.invoke(params,
+ impl.getEndpointIdentificationAlgorithm());
Method m_setUseCipherSuitesOrder =
params.getClass().getMethod("setUseCipherSuitesOrder", boolean.class);
@@ -334,13 +339,14 @@ private static void getSSLParametersFromImpl(SSLParameters params, SSLParameters
Method setNamedGroupsMethod =
params.getClass().getMethod("setNamedGroups", String[].class);
setNamedGroupsMethod.invoke(params, (Object) impl.getNamedGroups());
- } catch (NoSuchMethodException | IllegalArgumentException e) {
+ } catch (NoSuchMethodException | IllegalArgumentException | IllegalAccessException
+ | InvocationTargetException e) {
// Do nothing.
}
}
- public static void getSSLParameters(
- SSLParameters params, SSLParametersImpl impl, AbstractConscryptSocket socket) {
+ public static void getSSLParameters(SSLParameters params, SSLParametersImpl impl,
+ AbstractConscryptSocket socket) {
try {
getSSLParametersFromImpl(params, impl);
@@ -348,28 +354,28 @@ public static void getSSLParameters(
setParametersSniHostname(params, impl, socket);
}
} catch (NoSuchMethodException ignored) {
- //Ignored
+ // Ignored
} catch (IllegalAccessException ignored) {
- //Ignored
+ // Ignored
} catch (InvocationTargetException e) {
throw new RuntimeException(e.getCause());
}
}
@TargetApi(24)
- private static void setParametersSniHostname(
- SSLParameters params, SSLParametersImpl impl, AbstractConscryptSocket socket)
+ private static void setParametersSniHostname(SSLParameters params, SSLParametersImpl impl,
+ AbstractConscryptSocket socket)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
if (impl.getUseSni() && AddressUtils.isValidSniHostname(socket.getHostname())) {
Method m_setServerNames = params.getClass().getMethod("setServerNames", List.class);
m_setServerNames.invoke(params,
- Collections.singletonList(
- new SNIHostName(socket.getHostname())));
+ Collections.singletonList(
+ new SNIHostName(socket.getHostname())));
}
}
- public static void getSSLParameters(
- SSLParameters params, SSLParametersImpl impl, ConscryptEngine engine) {
+ public static void getSSLParameters(SSLParameters params, SSLParametersImpl impl,
+ ConscryptEngine engine) {
try {
getSSLParametersFromImpl(params, impl);
@@ -377,23 +383,23 @@ public static void getSSLParameters(
setParametersSniHostname(params, impl, engine);
}
} catch (NoSuchMethodException ignored) {
- //Ignored
+ // Ignored
} catch (IllegalAccessException ignored) {
- //Ignored
+ // Ignored
} catch (InvocationTargetException e) {
throw new RuntimeException(e.getCause());
}
}
@TargetApi(24)
- private static void setParametersSniHostname(
- SSLParameters params, SSLParametersImpl impl, ConscryptEngine engine)
+ private static void setParametersSniHostname(SSLParameters params, SSLParametersImpl impl,
+ ConscryptEngine engine)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
if (impl.getUseSni() && AddressUtils.isValidSniHostname(engine.getHostname())) {
Method m_setServerNames = params.getClass().getMethod("setServerNames", List.class);
m_setServerNames.invoke(params,
- Collections.singletonList(
- new SNIHostName(engine.getHostname())));
+ Collections.singletonList(
+ new SNIHostName(engine.getHostname())));
}
}
@@ -405,14 +411,14 @@ private static Class> getClass(String... klasses) {
try {
return Class.forName(klass);
} catch (Exception ignored) {
- //Ignored
+ // Ignored
}
}
return null;
}
- public static void setEndpointIdentificationAlgorithm(
- SSLParameters params, String endpointIdentificationAlgorithm) {
+ public static void setEndpointIdentificationAlgorithm(SSLParameters params,
+ String endpointIdentificationAlgorithm) {
// TODO: implement this for unbundled
}
@@ -426,21 +432,22 @@ public static String getEndpointIdentificationAlgorithm(SSLParameters params) {
* Socket, SSLEngine, or String (legacy Android).
*/
private static boolean checkTrusted(String methodName, X509TrustManager tm,
- X509Certificate[] chain, String authType, Class> argumentClass,
- Object argumentInstance) throws CertificateException {
+ X509Certificate[] chain, String authType,
+ Class> argumentClass, Object argumentInstance)
+ throws CertificateException {
// Use duck-typing to try and call the hostname-aware method if available.
try {
- Method method = tm.getClass().getMethod(
- methodName, X509Certificate[].class, String.class, argumentClass);
+ Method method = tm.getClass().getMethod(methodName, X509Certificate[].class,
+ String.class, argumentClass);
method.invoke(tm, chain, authType, argumentInstance);
return true;
} catch (NoSuchMethodException ignored) {
- //Ignored
+ // Ignored
} catch (IllegalAccessException ignored) {
- //Ignored
+ // Ignored
} catch (InvocationTargetException e) {
if (e.getCause() instanceof CertificateException) {
- throw(CertificateException) e.getCause();
+ throw (CertificateException) e.getCause();
}
throw new RuntimeException(e.getCause());
}
@@ -449,40 +456,44 @@ private static boolean checkTrusted(String methodName, X509TrustManager tm,
@SuppressLint("NewApi") // AbstractConscryptSocket defines getHandshakeSession()
public static void checkClientTrusted(X509TrustManager tm, X509Certificate[] chain,
- String authType, AbstractConscryptSocket socket) throws CertificateException {
+ String authType, AbstractConscryptSocket socket)
+ throws CertificateException {
if (!checkTrusted("checkClientTrusted", tm, chain, authType, Socket.class, socket)
- && !checkTrusted("checkClientTrusted", tm, chain, authType, String.class,
- socket.getHandshakeSession().getPeerHost())) {
+ && !checkTrusted("checkClientTrusted", tm, chain, authType, String.class,
+ socket.getHandshakeSession().getPeerHost())) {
tm.checkClientTrusted(chain, authType);
}
}
@SuppressLint("NewApi") // AbstractConscryptSocket defines getHandshakeSession()
public static void checkServerTrusted(X509TrustManager tm, X509Certificate[] chain,
- String authType, AbstractConscryptSocket socket) throws CertificateException {
+ String authType, AbstractConscryptSocket socket)
+ throws CertificateException {
if (!checkTrusted("checkServerTrusted", tm, chain, authType, Socket.class, socket)
- && !checkTrusted("checkServerTrusted", tm, chain, authType, String.class,
- socket.getHandshakeSession().getPeerHost())) {
+ && !checkTrusted("checkServerTrusted", tm, chain, authType, String.class,
+ socket.getHandshakeSession().getPeerHost())) {
tm.checkServerTrusted(chain, authType);
}
}
@SuppressLint("NewApi") // AbstractConscryptSocket defines getHandshakeSession()
public static void checkClientTrusted(X509TrustManager tm, X509Certificate[] chain,
- String authType, ConscryptEngine engine) throws CertificateException {
+ String authType, ConscryptEngine engine)
+ throws CertificateException {
if (!checkTrusted("checkClientTrusted", tm, chain, authType, SSLEngine.class, engine)
- && !checkTrusted("checkClientTrusted", tm, chain, authType, String.class,
- engine.getHandshakeSession().getPeerHost())) {
+ && !checkTrusted("checkClientTrusted", tm, chain, authType, String.class,
+ engine.getHandshakeSession().getPeerHost())) {
tm.checkClientTrusted(chain, authType);
}
}
@SuppressLint("NewApi") // AbstractConscryptSocket defines getHandshakeSession()
public static void checkServerTrusted(X509TrustManager tm, X509Certificate[] chain,
- String authType, ConscryptEngine engine) throws CertificateException {
+ String authType, ConscryptEngine engine)
+ throws CertificateException {
if (!checkTrusted("checkServerTrusted", tm, chain, authType, SSLEngine.class, engine)
- && !checkTrusted("checkServerTrusted", tm, chain, authType, String.class,
- engine.getHandshakeSession().getPeerHost())) {
+ && !checkTrusted("checkServerTrusted", tm, chain, authType, String.class,
+ engine.getHandshakeSession().getPeerHost())) {
tm.checkServerTrusted(chain, authType);
}
}
@@ -506,7 +517,8 @@ static ConscryptEngineSocket createEngineSocket(SSLParametersImpl sslParameters)
}
static ConscryptEngineSocket createEngineSocket(String hostname, int port,
- SSLParametersImpl sslParameters) throws IOException {
+ SSLParametersImpl sslParameters)
+ throws IOException {
if (Build.VERSION.SDK_INT >= 24) {
return new Java8EngineSocket(hostname, port, sslParameters);
}
@@ -514,7 +526,8 @@ static ConscryptEngineSocket createEngineSocket(String hostname, int port,
}
static ConscryptEngineSocket createEngineSocket(InetAddress address, int port,
- SSLParametersImpl sslParameters) throws IOException {
+ SSLParametersImpl sslParameters)
+ throws IOException {
if (Build.VERSION.SDK_INT >= 24) {
return new Java8EngineSocket(address, port, sslParameters);
}
@@ -522,7 +535,8 @@ static ConscryptEngineSocket createEngineSocket(InetAddress address, int port,
}
static ConscryptEngineSocket createEngineSocket(String hostname, int port,
- InetAddress clientAddress, int clientPort, SSLParametersImpl sslParameters)
+ InetAddress clientAddress, int clientPort,
+ SSLParametersImpl sslParameters)
throws IOException {
if (Build.VERSION.SDK_INT >= 24) {
return new Java8EngineSocket(hostname, port, clientAddress, clientPort, sslParameters);
@@ -531,7 +545,8 @@ static ConscryptEngineSocket createEngineSocket(String hostname, int port,
}
static ConscryptEngineSocket createEngineSocket(InetAddress address, int port,
- InetAddress clientAddress, int clientPort, SSLParametersImpl sslParameters)
+ InetAddress clientAddress, int clientPort,
+ SSLParametersImpl sslParameters)
throws IOException {
if (Build.VERSION.SDK_INT >= 24) {
return new Java8EngineSocket(address, port, clientAddress, clientPort, sslParameters);
@@ -540,7 +555,9 @@ static ConscryptEngineSocket createEngineSocket(InetAddress address, int port,
}
static ConscryptEngineSocket createEngineSocket(Socket socket, String hostname, int port,
- boolean autoClose, SSLParametersImpl sslParameters) throws IOException {
+ boolean autoClose,
+ SSLParametersImpl sslParameters)
+ throws IOException {
if (Build.VERSION.SDK_INT >= 24) {
return new Java8EngineSocket(socket, hostname, port, autoClose, sslParameters);
}
@@ -556,7 +573,8 @@ static ConscryptFileDescriptorSocket createFileDescriptorSocket(SSLParametersImp
}
static ConscryptFileDescriptorSocket createFileDescriptorSocket(String hostname, int port,
- SSLParametersImpl sslParameters) throws IOException {
+ SSLParametersImpl sslParameters)
+ throws IOException {
if (Build.VERSION.SDK_INT >= 24) {
return new Java8FileDescriptorSocket(hostname, port, sslParameters);
}
@@ -564,7 +582,8 @@ static ConscryptFileDescriptorSocket createFileDescriptorSocket(String hostname,
}
static ConscryptFileDescriptorSocket createFileDescriptorSocket(InetAddress address, int port,
- SSLParametersImpl sslParameters) throws IOException {
+ SSLParametersImpl sslParameters)
+ throws IOException {
if (Build.VERSION.SDK_INT >= 24) {
return new Java8FileDescriptorSocket(address, port, sslParameters);
}
@@ -572,29 +591,35 @@ static ConscryptFileDescriptorSocket createFileDescriptorSocket(InetAddress addr
}
static ConscryptFileDescriptorSocket createFileDescriptorSocket(String hostname, int port,
- InetAddress clientAddress, int clientPort, SSLParametersImpl sslParameters)
+ InetAddress clientAddress,
+ int clientPort,
+ SSLParametersImpl sslParameters)
throws IOException {
if (Build.VERSION.SDK_INT >= 24) {
- return new Java8FileDescriptorSocket(
- hostname, port, clientAddress, clientPort, sslParameters);
+ return new Java8FileDescriptorSocket(hostname, port, clientAddress, clientPort,
+ sslParameters);
}
- return new ConscryptFileDescriptorSocket(
- hostname, port, clientAddress, clientPort, sslParameters);
+ return new ConscryptFileDescriptorSocket(hostname, port, clientAddress, clientPort,
+ sslParameters);
}
static ConscryptFileDescriptorSocket createFileDescriptorSocket(InetAddress address, int port,
- InetAddress clientAddress, int clientPort, SSLParametersImpl sslParameters)
+ InetAddress clientAddress,
+ int clientPort,
+ SSLParametersImpl sslParameters)
throws IOException {
if (Build.VERSION.SDK_INT >= 24) {
- return new Java8FileDescriptorSocket(
- address, port, clientAddress, clientPort, sslParameters);
+ return new Java8FileDescriptorSocket(address, port, clientAddress, clientPort,
+ sslParameters);
}
- return new ConscryptFileDescriptorSocket(
- address, port, clientAddress, clientPort, sslParameters);
+ return new ConscryptFileDescriptorSocket(address, port, clientAddress, clientPort,
+ sslParameters);
}
static ConscryptFileDescriptorSocket createFileDescriptorSocket(Socket socket, String hostname,
- int port, boolean autoClose, SSLParametersImpl sslParameters) throws IOException {
+ int port, boolean autoClose,
+ SSLParametersImpl sslParameters)
+ throws IOException {
if (Build.VERSION.SDK_INT >= 24) {
return new Java8FileDescriptorSocket(socket, hostname, port, autoClose, sslParameters);
}
@@ -639,8 +664,8 @@ public static GCMParameters fromGCMParameterSpec(AlgorithmParameterSpec params)
} catch (IllegalAccessException e) {
throw new RuntimeException("GCMParameterSpec lacks expected methods", e);
} catch (InvocationTargetException e) {
- throw new RuntimeException(
- "Could not fetch GCM parameters", e.getTargetException());
+ throw new RuntimeException("Could not fetch GCM parameters",
+ e.getTargetException());
}
}
return null;
@@ -685,7 +710,7 @@ public static AlgorithmParameterSpec toGCMParameterSpec(int tagLenInBits, byte[]
Constructor> constructor = gcmSpecClass.getConstructor(int.class, byte[].class);
return (AlgorithmParameterSpec) constructor.newInstance(tagLenInBits, iv);
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException
- | IllegalArgumentException e) {
+ | IllegalArgumentException e) {
logStackTraceSnippet("Can't find GCMParameterSpec class", e);
} catch (InvocationTargetException e) {
logStackTraceSnippet("Can't find GCMParameterSpec class", e.getCause());
@@ -741,13 +766,13 @@ public static String oidToAlgorithmName(String oid) {
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof RuntimeException) {
- throw(RuntimeException) cause;
+ throw (RuntimeException) cause;
} else if (cause instanceof Error) {
- throw(Error) cause;
+ throw (Error) cause;
}
throw new RuntimeException(e);
} catch (Exception ignored) {
- //Ignored
+ // Ignored
}
// Newer OpenJDK style
@@ -763,13 +788,13 @@ public static String oidToAlgorithmName(String oid) {
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof RuntimeException) {
- throw(RuntimeException) cause;
+ throw (RuntimeException) cause;
} else if (cause instanceof Error) {
- throw(Error) cause;
+ throw (Error) cause;
}
throw new RuntimeException(e);
} catch (Exception ignored) {
- //Ignored
+ // Ignored
}
return oid;
@@ -808,9 +833,9 @@ public static String getOriginalHostNameFromInetAddress(InetAddress addr) {
} catch (ClassNotFoundException ignore) {
// passthrough and return addr.getHostAddress()
} catch (IllegalAccessException ignore) {
- //Ignored
+ // Ignored
} catch (NoSuchMethodException ignore) {
- //Ignored
+ // Ignored
}
}
return addr.getHostAddress();
@@ -828,7 +853,7 @@ public static String getHostStringFromInetSocketAddress(InetSocketAddress addr)
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (Exception ignored) {
- //Ignored
+ // Ignored
}
}
return null;
@@ -839,59 +864,8 @@ static boolean supportsX509ExtendedTrustManager() {
return Build.VERSION.SDK_INT > 23;
}
- /**
- * Check if SCT verification is required for a given hostname.
- *
- * SCT Verification is enabled using {@code Security} properties.
- * The "conscrypt.ct.enable" property must be true, as well as a per domain property.
- * The reverse notation of the domain name, prefixed with "conscrypt.ct.enforce."
- * is used as the property name.
- * Basic globbing is also supported.
- *
- * For example, for the domain foo.bar.com, the following properties will be
- * looked up, in order of precedence.
- * - conscrypt.ct.enforce.com.bar.foo
- * - conscrypt.ct.enforce.com.bar.*
- * - conscrypt.ct.enforce.com.*
- * - conscrypt.ct.enforce.*
- */
- public static boolean isCTVerificationRequired(String hostname) {
- if (hostname == null) {
- return false;
- }
- // TODO: Use the platform version on platforms that support it
-
- String property = Security.getProperty("conscrypt.ct.enable");
- if (property == null || !Boolean.parseBoolean(property)) {
- return false;
- }
-
- List parts = Arrays.asList(hostname.split("\\."));
- Collections.reverse(parts);
-
- boolean enable = false;
- String propertyName = "conscrypt.ct.enforce";
- // The loop keeps going on even once we've found a match
- // This allows for finer grained settings on subdomains
- for (String part : parts) {
- property = Security.getProperty(propertyName + ".*");
- if (property != null) {
- enable = Boolean.parseBoolean(property);
- }
-
- propertyName = propertyName + "." + part;
- }
-
- property = Security.getProperty(propertyName);
- if (property != null) {
- enable = Boolean.parseBoolean(property);
- }
- return enable;
- }
-
- public static CertificateTransparencyVerificationReason reasonCTVerificationRequired(
- String hostname) {
- return CertificateTransparencyVerificationReason.UNKNOWN;
+ static SSLException wrapInvalidEchDataException(SSLException e) {
+ return e;
}
static boolean supportsConscryptCertStore() {
@@ -920,7 +894,8 @@ static CertBlocklist newDefaultBlocklist() {
return null;
}
- static CertificateTransparency newDefaultCertificateTransparency() {
+ static CertificateTransparency newDefaultCertificateTransparency(
+ Supplier policySupplier) {
return null;
}
@@ -932,8 +907,8 @@ static boolean serverNamePermitted(SSLParametersImpl parameters, String serverNa
}
@TargetApi(24)
- private static boolean serverNamePermittedInternal(
- SSLParametersImpl parameters, String serverName) {
+ private static boolean serverNamePermittedInternal(SSLParametersImpl parameters,
+ String serverName) {
Collection sniMatchers = parameters.getSNIMatchers();
if (sniMatchers == null || sniMatchers.isEmpty()) {
return true;
diff --git a/common/src/jni/main/cpp/conscrypt/jniutil.cc b/common/src/jni/main/cpp/conscrypt/jniutil.cc
index 96385df2a..ae24377e5 100644
--- a/common/src/jni/main/cpp/conscrypt/jniutil.cc
+++ b/common/src/jni/main/cpp/conscrypt/jniutil.cc
@@ -14,17 +14,17 @@
* limitations under the License.
*/
-#include
-
#include
+#include
#include
-#include
#include
+#include
+
namespace conscrypt {
namespace jniutil {
-JavaVM *gJavaVM;
+JavaVM* gJavaVM;
jclass cryptoUpcallsClass;
jclass openSslInputStreamClass;
jclass nativeRefClass;
@@ -84,10 +84,10 @@ void init(JavaVM* vm, JNIEnv* env) {
bufferClass = findClass(env, "java/nio/Buffer");
fileDescriptorClass = findClass(env, "java/io/FileDescriptor");
- cryptoUpcallsClass = getGlobalRefToClass(
- env, TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/CryptoUpcalls");
- nativeRefClass = getGlobalRefToClass(
- env, TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef");
+ cryptoUpcallsClass =
+ getGlobalRefToClass(env, TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/CryptoUpcalls");
+ nativeRefClass =
+ getGlobalRefToClass(env, TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef");
nativeRefHpkeCtxClass = getGlobalRefToClass(
env, TO_STRING(JNI_JARJAR_PREFIX) "org/conscrypt/NativeRef$EVP_HPKE_CTX");
openSslInputStreamClass = getGlobalRefToClass(
@@ -106,46 +106,43 @@ void init(JavaVM* vm, JNIEnv* env) {
inputStream_readMethod = getMethodRef(env, inputStreamClass, "read", "([B)I");
integer_valueOfMethod =
env->GetStaticMethodID(integerClass, "valueOf", "(I)Ljava/lang/Integer;");
- openSslInputStream_readLineMethod =
- getMethodRef(env, openSslInputStreamClass, "gets", "([B)I");
+ openSslInputStream_readLineMethod = getMethodRef(env, openSslInputStreamClass, "gets", "([B)I");
outputStream_writeMethod = getMethodRef(env, outputStreamClass, "write", "([B)V");
outputStream_flushMethod = getMethodRef(env, outputStreamClass, "flush", "()V");
buffer_positionMethod = getMethodRef(env, bufferClass, "position", "()I");
buffer_limitMethod = getMethodRef(env, bufferClass, "limit", "()I");
buffer_isDirectMethod = getMethodRef(env, bufferClass, "isDirect", "()Z");
- sslHandshakeCallbacks_verifyCertificateChain =
- getMethodRef(env, sslHandshakeCallbacksClass, "verifyCertificateChain", "([[BLjava/lang/String;)V");
+ sslHandshakeCallbacks_verifyCertificateChain = getMethodRef(
+ env, sslHandshakeCallbacksClass, "verifyCertificateChain", "([[BLjava/lang/String;)V");
sslHandshakeCallbacks_onSSLStateChange =
- getMethodRef(env, sslHandshakeCallbacksClass, "onSSLStateChange", "(II)V");
- sslHandshakeCallbacks_clientCertificateRequested =
- getMethodRef(env, sslHandshakeCallbacksClass, "clientCertificateRequested", "([B[I[[B)V");
+ getMethodRef(env, sslHandshakeCallbacksClass, "onSSLStateChange", "(II)V");
+ sslHandshakeCallbacks_clientCertificateRequested = getMethodRef(
+ env, sslHandshakeCallbacksClass, "clientCertificateRequested", "([B[I[[B)V");
sslHandshakeCallbacks_serverCertificateRequested =
- getMethodRef(env, sslHandshakeCallbacksClass, "serverCertificateRequested", "()V");
- sslHandshakeCallbacks_clientPSKKeyRequested =
- getMethodRef(env, sslHandshakeCallbacksClass, "clientPSKKeyRequested", "(Ljava/lang/String;[B[B)I");
+ getMethodRef(env, sslHandshakeCallbacksClass, "serverCertificateRequested", "()V");
+ sslHandshakeCallbacks_clientPSKKeyRequested = getMethodRef(
+ env, sslHandshakeCallbacksClass, "clientPSKKeyRequested", "(Ljava/lang/String;[B[B)I");
sslHandshakeCallbacks_serverPSKKeyRequested =
- getMethodRef(env, sslHandshakeCallbacksClass, "serverPSKKeyRequested", "(Ljava/lang/String;Ljava/lang/String;[B)I");
+ getMethodRef(env, sslHandshakeCallbacksClass, "serverPSKKeyRequested",
+ "(Ljava/lang/String;Ljava/lang/String;[B)I");
sslHandshakeCallbacks_onNewSessionEstablished =
- getMethodRef(env, sslHandshakeCallbacksClass, "onNewSessionEstablished", "(J)V");
+ getMethodRef(env, sslHandshakeCallbacksClass, "onNewSessionEstablished", "(J)V");
sslHandshakeCallbacks_serverSessionRequested =
- getMethodRef(env, sslHandshakeCallbacksClass, "serverSessionRequested", "([B)J");
+ getMethodRef(env, sslHandshakeCallbacksClass, "serverSessionRequested", "([B)J");
sslHandshakeCallbacks_selectApplicationProtocol =
- getMethodRef(env, sslHandshakeCallbacksClass, "selectApplicationProtocol", "([B)I");
- cryptoUpcallsClass_rawSignMethod = env->GetStaticMethodID(cryptoUpcallsClass,
- "ecSignDigestWithPrivateKey",
- "(Ljava/security/PrivateKey;[B)[B");
+ getMethodRef(env, sslHandshakeCallbacksClass, "selectApplicationProtocol", "([B)I");
+ cryptoUpcallsClass_rawSignMethod = env->GetStaticMethodID(
+ cryptoUpcallsClass, "ecSignDigestWithPrivateKey", "(Ljava/security/PrivateKey;[B)[B");
if (cryptoUpcallsClass_rawSignMethod == nullptr) {
env->FatalError("Could not find ecSignDigestWithPrivateKey");
}
- cryptoUpcallsClass_rsaSignMethod = env->GetStaticMethodID(cryptoUpcallsClass,
- "rsaSignDigestWithPrivateKey",
- "(Ljava/security/PrivateKey;I[B)[B");
+ cryptoUpcallsClass_rsaSignMethod = env->GetStaticMethodID(
+ cryptoUpcallsClass, "rsaSignDigestWithPrivateKey", "(Ljava/security/PrivateKey;I[B)[B");
if (cryptoUpcallsClass_rsaSignMethod == nullptr) {
env->FatalError("Could not find rsaSignDigestWithPrivateKey");
}
- cryptoUpcallsClass_rsaDecryptMethod = env->GetStaticMethodID(cryptoUpcallsClass,
- "rsaDecryptWithPrivateKey",
- "(Ljava/security/PrivateKey;I[B)[B");
+ cryptoUpcallsClass_rsaDecryptMethod = env->GetStaticMethodID(
+ cryptoUpcallsClass, "rsaDecryptWithPrivateKey", "(Ljava/security/PrivateKey;I[B)[B");
if (cryptoUpcallsClass_rsaDecryptMethod == nullptr) {
env->FatalError("Could not find rsaDecryptWithPrivateKey");
}
@@ -257,14 +254,13 @@ int throwInvalidKeyException(JNIEnv* env, const char* message) {
int throwIllegalArgumentException(JNIEnv* env, const char* message) {
JNI_TRACE("throwIllegalArgumentException %s", message);
- return conscrypt::jniutil::throwException(
- env, "java/lang/IllegalArgumentException", message);
+ return conscrypt::jniutil::throwException(env, "java/lang/IllegalArgumentException", message);
}
int throwIllegalBlockSizeException(JNIEnv* env, const char* message) {
JNI_TRACE("throwIllegalBlockSizeException %s", message);
- return conscrypt::jniutil::throwException(
- env, "javax/crypto/IllegalBlockSizeException", message);
+ return conscrypt::jniutil::throwException(env, "javax/crypto/IllegalBlockSizeException",
+ message);
}
int throwIllegalStateException(JNIEnv* env, const char* message) {
@@ -274,14 +270,13 @@ int throwIllegalStateException(JNIEnv* env, const char* message) {
int throwShortBufferException(JNIEnv* env, const char* message) {
JNI_TRACE("throwShortBufferException %s", message);
- return conscrypt::jniutil::throwException(
- env, "javax/crypto/ShortBufferException", message);
+ return conscrypt::jniutil::throwException(env, "javax/crypto/ShortBufferException", message);
}
int throwNoSuchAlgorithmException(JNIEnv* env, const char* message) {
JNI_TRACE("throwUnknownAlgorithmException %s", message);
- return conscrypt::jniutil::throwException(
- env, "java/security/NoSuchAlgorithmException", message);
+ return conscrypt::jniutil::throwException(env, "java/security/NoSuchAlgorithmException",
+ message);
}
int throwIOException(JNIEnv* env, const char* message) {
@@ -291,8 +286,8 @@ int throwIOException(JNIEnv* env, const char* message) {
int throwCertificateException(JNIEnv* env, const char* message) {
JNI_TRACE("throwCertificateException %s", message);
- return conscrypt::jniutil::throwException(
- env, "java/security/cert/CertificateException", message);
+ return conscrypt::jniutil::throwException(env, "java/security/cert/CertificateException",
+ message);
}
int throwParsingException(JNIEnv* env, const char* message) {
@@ -333,9 +328,9 @@ int throwForCipherError(JNIEnv* env, int reason, const char* message,
case CIPHER_R_WRONG_FINAL_BLOCK_LENGTH:
return throwIllegalBlockSizeException(env, message);
break;
- // TODO(davidben): Remove these ifdefs after
- // https://boringssl-review.googlesource.com/c/boringssl/+/35565 has
- // rolled out to relevant BoringSSL copies.
+ // TODO(davidben): Remove these ifdefs after
+ // https://boringssl-review.googlesource.com/c/boringssl/+/35565 has
+ // rolled out to relevant BoringSSL copies.
#if defined(CIPHER_R_BAD_KEY_LENGTH)
case CIPHER_R_BAD_KEY_LENGTH:
#endif
@@ -503,8 +498,7 @@ int throwSocketTimeoutException(JNIEnv* env, const char* message) {
int throwSSLHandshakeExceptionStr(JNIEnv* env, const char* message) {
JNI_TRACE("throwSSLExceptionStr %s", message);
- return conscrypt::jniutil::throwException(
- env, "javax/net/ssl/SSLHandshakeException", message);
+ return conscrypt::jniutil::throwException(env, "javax/net/ssl/SSLHandshakeException", message);
}
int throwSSLExceptionStr(JNIEnv* env, const char* message) {
@@ -514,8 +508,7 @@ int throwSSLExceptionStr(JNIEnv* env, const char* message) {
int throwSSLProtocolExceptionStr(JNIEnv* env, const char* message) {
JNI_TRACE("throwSSLProtocolExceptionStr %s", message);
- return conscrypt::jniutil::throwException(
- env, "javax/net/ssl/SSLProtocolException", message);
+ return conscrypt::jniutil::throwException(env, "javax/net/ssl/SSLProtocolException", message);
}
int throwSSLExceptionWithSslErrors(JNIEnv* env, SSL* ssl, int sslErrorCode, const char* message,
diff --git a/common/src/jni/main/cpp/conscrypt/native_crypto.cc b/common/src/jni/main/cpp/conscrypt/native_crypto.cc
index b99815873..7ede18d2b 100644
--- a/common/src/jni/main/cpp/conscrypt/native_crypto.cc
+++ b/common/src/jni/main/cpp/conscrypt/native_crypto.cc
@@ -58,6 +58,8 @@
#include
#include
+#include "jni.h"
+
using conscrypt::AppData;
using conscrypt::BioInputStream;
using conscrypt::BioOutputStream;
@@ -216,7 +218,7 @@ static bool arrayToBignum(JNIEnv* env, jbyteArray source, BIGNUM** dest) {
}
static bssl::UniquePtr arrayToBignum(JNIEnv* env, jbyteArray source) {
- BIGNUM *bn = nullptr;
+ BIGNUM* bn = nullptr;
if (!arrayToBignum(env, source, &bn)) {
return nullptr;
}
@@ -501,7 +503,7 @@ static long bio_stream_ctrl(BIO* b, int cmd, long, void*) {
}
}
-static const BIO_METHOD *stream_bio_method() {
+static const BIO_METHOD* stream_bio_method() {
static const BIO_METHOD* stream_method = []() -> const BIO_METHOD* {
BIO_METHOD* method = BIO_meth_new(0, nullptr);
if (!method || !BIO_meth_set_write(method, bio_stream_write) ||
@@ -543,8 +545,7 @@ static jbyteArray ecSignDigestWithPrivateKey(JNIEnv* env, jobject privateKey, co
return reinterpret_cast(env->CallStaticObjectMethod(
conscrypt::jniutil::cryptoUpcallsClass,
- conscrypt::jniutil::cryptoUpcallsClass_rawSignMethod,
- privateKey, messageArray.get()));
+ conscrypt::jniutil::cryptoUpcallsClass_rawSignMethod, privateKey, messageArray.get()));
}
static jbyteArray rsaSignDigestWithPrivateKey(JNIEnv* env, jobject privateKey, jint padding,
@@ -571,10 +572,9 @@ static jbyteArray rsaSignDigestWithPrivateKey(JNIEnv* env, jobject privateKey, j
}
return reinterpret_cast(
- env->CallStaticObjectMethod(
- conscrypt::jniutil::cryptoUpcallsClass,
- conscrypt::jniutil::cryptoUpcallsClass_rsaSignMethod,
- privateKey, padding, messageArray.get()));
+ env->CallStaticObjectMethod(conscrypt::jniutil::cryptoUpcallsClass,
+ conscrypt::jniutil::cryptoUpcallsClass_rsaSignMethod,
+ privateKey, padding, messageArray.get()));
}
// rsaDecryptWithPrivateKey uses privateKey to decrypt |ciphertext_len| bytes
@@ -605,10 +605,9 @@ static jbyteArray rsaDecryptWithPrivateKey(JNIEnv* env, jobject privateKey, jint
}
return reinterpret_cast(
- env->CallStaticObjectMethod(
- conscrypt::jniutil::cryptoUpcallsClass,
- conscrypt::jniutil::cryptoUpcallsClass_rsaDecryptMethod,
- privateKey, padding, ciphertextArray.get()));
+ env->CallStaticObjectMethod(conscrypt::jniutil::cryptoUpcallsClass,
+ conscrypt::jniutil::cryptoUpcallsClass_rsaDecryptMethod,
+ privateKey, padding, ciphertextArray.get()));
}
// *********************************************
@@ -639,22 +638,14 @@ struct KeyExData {
// ExDataDup is called when one of the RSA or EC_KEY objects is duplicated. We
// don't support this and it should never happen.
-int ExDataDup(CRYPTO_EX_DATA* /* to */,
- const CRYPTO_EX_DATA* /* from */,
- void** /* from_d */,
- int /* index */,
- long /* argl */ /* NOLINT(runtime/int) */,
- void* /* argp */) {
- return 0;
+int ExDataDup(CRYPTO_EX_DATA* /* to */, const CRYPTO_EX_DATA* /* from */, void** /* from_d */,
+ int /* index */, long /* argl */ /* NOLINT(runtime/int) */, void* /* argp */) {
+ return 0;
}
// ExDataFree is called when one of the RSA or EC_KEY objects is freed.
-void ExDataFree(void* /* parent */,
- void* ptr,
- CRYPTO_EX_DATA* /* ad */,
- int /* index */,
- long /* argl */ /* NOLINT(runtime/int) */,
- void* /* argp */) {
+void ExDataFree(void* /* parent */, void* ptr, CRYPTO_EX_DATA* /* ad */, int /* index */,
+ long /* argl */ /* NOLINT(runtime/int) */, void* /* argp */) {
// Ensure the global JNI reference created with this wrapper is
// properly destroyed with it.
KeyExData* ex_data = reinterpret_cast(ptr);
@@ -787,8 +778,8 @@ int EcdsaMethodSign(const uint8_t* digest, size_t digest_len, uint8_t* sig, unsi
// Sign message with it through JNI.
ScopedLocalRef signature(
- env, ecSignDigestWithPrivateKey(env, private_key,
- reinterpret_cast(digest), digest_len));
+ env, ecSignDigestWithPrivateKey(env, private_key, reinterpret_cast(digest),
+ digest_len));
if (signature.get() == nullptr) {
CONSCRYPT_LOG_ERROR("Could not sign message in EcdsaMethodDoSign!");
return 0;
@@ -1584,8 +1575,8 @@ static jbyteArray NativeCrypto_EVP_PKEY_get_private_seed(JNIEnv* env, jclass, jo
return seedArray.release();
}
-static jbyteArray NativeCrypto_EVP_raw_X25519_private_key(
- JNIEnv* env, jclass cls, jbyteArray keyJavaBytes) {
+static jbyteArray NativeCrypto_EVP_raw_X25519_private_key(JNIEnv* env, jclass cls,
+ jbyteArray keyJavaBytes) {
CHECK_ERROR_QUEUE_ON_RETURN;
JNI_TRACE("NativeCrypto_EVP_raw_X25519_private_key(%p)", keyJavaBytes);
@@ -1614,8 +1605,8 @@ static jbyteArray NativeCrypto_EVP_raw_X25519_private_key(
return nullptr;
}
- if (EVP_PKEY_get_raw_private_key(
- pkey.get(), reinterpret_cast(bytes.get()), &key_length) == 0) {
+ if (EVP_PKEY_get_raw_private_key(pkey.get(), reinterpret_cast(bytes.get()),
+ &key_length) == 0) {
conscrypt::jniutil::throwExceptionFromBoringSSLError(env, "EVP_PKEY_get_raw_private_key");
return nullptr;
}
@@ -1885,8 +1876,8 @@ static jint RSA_crypt_operation(RSACryptOperation operation, const char* caller,
operation(static_cast(flen), reinterpret_cast(from.get()),
reinterpret_cast(to.get()), rsa.get(), padding);
if (resultSize == -1) {
- conscrypt::jniutil::throwExceptionFromBoringSSLError(env, caller,
- conscrypt::jniutil::throwBadPaddingException);
+ conscrypt::jniutil::throwExceptionFromBoringSSLError(
+ env, caller, conscrypt::jniutil::throwBadPaddingException);
JNI_TRACE("%s => threw error", caller);
return -1;
}
@@ -2052,8 +2043,9 @@ static jobjectArray NativeCrypto_get_RSA_private_params(JNIEnv* env, jclass, job
}
static void NativeCrypto_chacha20_encrypt_decrypt(JNIEnv* env, jclass, jbyteArray inBytes,
- jint inOffset, jbyteArray outBytes, jint outOffset, jint length, jbyteArray keyBytes,
- jbyteArray nonceBytes, jint blockCounter) {
+ jint inOffset, jbyteArray outBytes,
+ jint outOffset, jint length, jbyteArray keyBytes,
+ jbyteArray nonceBytes, jint blockCounter) {
CHECK_ERROR_QUEUE_ON_RETURN;
JNI_TRACE("chacha20_encrypt_decrypt");
ScopedByteArrayRO in(env, inBytes);
@@ -2077,13 +2069,10 @@ static void NativeCrypto_chacha20_encrypt_decrypt(JNIEnv* env, jclass, jbyteArra
return;
}
- CRYPTO_chacha_20(
- reinterpret_cast(out.get()) + outOffset,
- reinterpret_cast(in.get()) + inOffset,
- length,
- reinterpret_cast(key.get()),
- reinterpret_cast(nonce.get()),
- blockCounter);
+ CRYPTO_chacha_20(reinterpret_cast(out.get()) + outOffset,
+ reinterpret_cast(in.get()) + inOffset, length,
+ reinterpret_cast(key.get()),
+ reinterpret_cast(nonce.get()), blockCounter);
}
static jlong NativeCrypto_EC_GROUP_new_by_curve_name(JNIEnv* env, jclass, jstring curveNameJava) {
@@ -2170,7 +2159,8 @@ static jlong NativeCrypto_EC_GROUP_new_arbitrary(JNIEnv* env, jclass, jbyteArray
return 0;
}
- if (!EC_POINT_set_affine_coordinates_GFp(group.get(), generator.get(), x.get(), y.get(), ctx.get())) {
+ if (!EC_POINT_set_affine_coordinates_GFp(group.get(), generator.get(), x.get(), y.get(),
+ ctx.get())) {
JNI_TRACE("EC_POINT_set_affine_coordinates_GFp => error");
conscrypt::jniutil::throwExceptionFromBoringSSLError(env,
"EC_POINT_set_affine_coordinates_GFp");
@@ -2705,16 +2695,16 @@ static jint NativeCrypto_ECDH_compute_key(JNIEnv* env, jclass, jbyteArray outArr
bssl::UniquePtr pubkey(EVP_PKEY_get1_EC_KEY(pubPkey));
if (pubkey.get() == nullptr) {
JNI_TRACE("ECDH_compute_key(%p) => can't get public key", pubPkey);
- conscrypt::jniutil::throwExceptionFromBoringSSLError(env, "EVP_PKEY_get1_EC_KEY public",
- conscrypt::jniutil::throwInvalidKeyException);
+ conscrypt::jniutil::throwExceptionFromBoringSSLError(
+ env, "EVP_PKEY_get1_EC_KEY public", conscrypt::jniutil::throwInvalidKeyException);
return -1;
}
const EC_POINT* pubkeyPoint = EC_KEY_get0_public_key(pubkey.get());
if (pubkeyPoint == nullptr) {
JNI_TRACE("ECDH_compute_key(%p) => can't get public key point", pubPkey);
- conscrypt::jniutil::throwExceptionFromBoringSSLError(env, "EVP_PKEY_get1_EC_KEY public",
- conscrypt::jniutil::throwInvalidKeyException);
+ conscrypt::jniutil::throwExceptionFromBoringSSLError(
+ env, "EVP_PKEY_get1_EC_KEY public", conscrypt::jniutil::throwInvalidKeyException);
return -1;
}
@@ -2726,8 +2716,8 @@ static jint NativeCrypto_ECDH_compute_key(JNIEnv* env, jclass, jbyteArray outArr
bssl::UniquePtr privkey(EVP_PKEY_get1_EC_KEY(privPkey));
if (privkey.get() == nullptr) {
- conscrypt::jniutil::throwExceptionFromBoringSSLError(env, "EVP_PKEY_get1_EC_KEY private",
- conscrypt::jniutil::throwInvalidKeyException);
+ conscrypt::jniutil::throwExceptionFromBoringSSLError(
+ env, "EVP_PKEY_get1_EC_KEY private", conscrypt::jniutil::throwInvalidKeyException);
return -1;
}
@@ -2736,8 +2726,8 @@ static jint NativeCrypto_ECDH_compute_key(JNIEnv* env, jclass, jbyteArray outArr
privkey.get(), nullptr /* No KDF */);
if (outputLength == -1) {
JNI_TRACE("ECDH_compute_key(%p) => outputLength = -1", pubPkey);
- conscrypt::jniutil::throwExceptionFromBoringSSLError(env, "ECDH_compute_key",
- conscrypt::jniutil::throwInvalidKeyException);
+ conscrypt::jniutil::throwExceptionFromBoringSSLError(
+ env, "ECDH_compute_key", conscrypt::jniutil::throwInvalidKeyException);
return -1;
}
@@ -3105,13 +3095,14 @@ static jint NativeCrypto_SLHDSA_SHA2_128S_verify(JNIEnv* env, jclass, jbyteArray
}
static jboolean NativeCrypto_X25519(JNIEnv* env, jclass, jbyteArray outArray,
- jbyteArray privkeyArray, jbyteArray pubkeyArray) {
+ jbyteArray privkeyArray, jbyteArray pubkeyArray) {
CHECK_ERROR_QUEUE_ON_RETURN;
JNI_TRACE("X25519(%p, %p, %p)", outArray, privkeyArray, pubkeyArray);
ScopedByteArrayRW out(env, outArray);
if (out.get() == nullptr) {
- JNI_TRACE("X25519(%p, %p, %p) can't get output buffer", outArray, privkeyArray, pubkeyArray);
+ JNI_TRACE("X25519(%p, %p, %p) can't get output buffer", outArray, privkeyArray,
+ pubkeyArray);
return JNI_FALSE;
}
@@ -3131,8 +3122,8 @@ static jboolean NativeCrypto_X25519(JNIEnv* env, jclass, jbyteArray outArray,
reinterpret_cast(privkey.get()),
reinterpret_cast(pubkey.get())) != 1) {
JNI_TRACE("X25519(%p) => failure", outArray);
- conscrypt::jniutil::throwExceptionFromBoringSSLError(env, "X25519",
- conscrypt::jniutil::throwInvalidKeyException);
+ conscrypt::jniutil::throwExceptionFromBoringSSLError(
+ env, "X25519", conscrypt::jniutil::throwInvalidKeyException);
return JNI_FALSE;
}
@@ -3140,28 +3131,34 @@ static jboolean NativeCrypto_X25519(JNIEnv* env, jclass, jbyteArray outArray,
return JNI_TRUE;
}
-static void NativeCrypto_X25519_keypair(JNIEnv* env, jclass, jbyteArray outPublicArray, jbyteArray outPrivateArray) {
+static void NativeCrypto_X25519_keypair(JNIEnv* env, jclass, jbyteArray outPublicArray,
+ jbyteArray outPrivateArray) {
CHECK_ERROR_QUEUE_ON_RETURN;
JNI_TRACE("X25519_keypair(%p, %p)", outPublicArray, outPrivateArray);
ScopedByteArrayRW outPublic(env, outPublicArray);
if (outPublic.get() == nullptr) {
- JNI_TRACE("X25519_keypair(%p, %p) can't get output public key buffer", outPublicArray, outPrivateArray);
+ JNI_TRACE("X25519_keypair(%p, %p) can't get output public key buffer", outPublicArray,
+ outPrivateArray);
return;
}
ScopedByteArrayRW outPrivate(env, outPrivateArray);
if (outPrivate.get() == nullptr) {
- JNI_TRACE("X25519_keypair(%p, %p) can't get output private key buffer", outPublicArray, outPrivateArray);
+ JNI_TRACE("X25519_keypair(%p, %p) can't get output private key buffer", outPublicArray,
+ outPrivateArray);
return;
}
- if (outPublic.size() != X25519_PUBLIC_VALUE_LEN || outPrivate.size() != X25519_PRIVATE_KEY_LEN) {
- conscrypt::jniutil::throwException(env, "java/lang/IllegalArgumentException", "Output key array length != 32");
+ if (outPublic.size() != X25519_PUBLIC_VALUE_LEN ||
+ outPrivate.size() != X25519_PRIVATE_KEY_LEN) {
+ conscrypt::jniutil::throwException(env, "java/lang/IllegalArgumentException",
+ "Output key array length != 32");
return;
}
- X25519_keypair(reinterpret_cast(outPublic.get()), reinterpret_cast(outPrivate.get()));
+ X25519_keypair(reinterpret_cast(outPublic.get()),
+ reinterpret_cast(outPrivate.get()));
JNI_TRACE("X25519_keypair(%p, %p) => success", outPublicArray, outPrivateArray);
}
@@ -3605,14 +3602,14 @@ static void NativeCrypto_EVP_DigestSignUpdate(JNIEnv* env, jclass, jobject evpMd
jint inLength) {
CHECK_ERROR_QUEUE_ON_RETURN;
evpUpdate(env, evpMdCtxRef, inJavaBytes, inOffset, inLength, "EVP_DigestSignUpdate",
- EVP_DigestSignUpdate);
+ EVP_DigestSignUpdate);
}
static void NativeCrypto_EVP_DigestSignUpdateDirect(JNIEnv* env, jclass, jobject evpMdCtxRef,
- jlong inPtr, jint inLength) {
+ jlong inPtr, jint inLength) {
CHECK_ERROR_QUEUE_ON_RETURN;
evpUpdate(env, evpMdCtxRef, inPtr, inLength, "EVP_DigestSignUpdateDirect",
- EVP_DigestSignUpdate);
+ EVP_DigestSignUpdate);
}
static void NativeCrypto_EVP_DigestVerifyUpdate(JNIEnv* env, jclass, jobject evpMdCtxRef,
@@ -4261,8 +4258,8 @@ static jint NativeCrypto_EVP_CipherFinal_ex(JNIEnv* env, jclass, jobject ctxRef,
int outl;
if (!EVP_CipherFinal_ex(ctx, out + outOffset, &outl)) {
- conscrypt::jniutil::throwExceptionFromBoringSSLError(env, "EVP_CipherFinal_ex",
- conscrypt::jniutil::throwBadPaddingException);
+ conscrypt::jniutil::throwExceptionFromBoringSSLError(
+ env, "EVP_CipherFinal_ex", conscrypt::jniutil::throwBadPaddingException);
JNI_TRACE("ctx=%p EVP_CipherFinal_ex => threw error", ctx);
return 0;
}
@@ -4458,9 +4455,10 @@ typedef int (*evp_aead_ctx_op_func)(const EVP_AEAD_CTX* ctx, uint8_t* out, size_
size_t ad_len);
static jint evp_aead_ctx_op_common(JNIEnv* env, jlong evpAeadRef, jbyteArray keyArray, jint tagLen,
- uint8_t* outBuf, jbyteArray nonceArray,
- const uint8_t* inBuf, jbyteArray aadArray,
- evp_aead_ctx_op_func realFunc, jobject inBuffer, jobject outBuffer, jint outRange, jint inRange) {
+ uint8_t* outBuf, jbyteArray nonceArray, const uint8_t* inBuf,
+ jbyteArray aadArray, evp_aead_ctx_op_func realFunc,
+ jobject inBuffer, jobject outBuffer, jint outRange,
+ jint inRange) {
const EVP_AEAD* evpAead = reinterpret_cast(evpAeadRef);
ScopedByteArrayRO keyBytes(env, keyArray);
@@ -4491,26 +4489,22 @@ static jint evp_aead_ctx_op_common(JNIEnv* env, jlong evpAeadRef, jbyteArray key
static_cast(tagLen), nullptr)) {
conscrypt::jniutil::throwExceptionFromBoringSSLError(env,
"failure initializing AEAD context");
- JNI_TRACE(
- "evp_aead_ctx_op(%p, %p, %d, %p, %p, %p, %p) => fail EVP_AEAD_CTX_init",
- evpAead, keyArray, tagLen, outBuffer, nonceArray, inBuffer,
- aadArray);
+ JNI_TRACE("evp_aead_ctx_op(%p, %p, %d, %p, %p, %p, %p) => fail EVP_AEAD_CTX_init", evpAead,
+ keyArray, tagLen, outBuffer, nonceArray, inBuffer, aadArray);
return 0;
}
const uint8_t* nonceTmp = reinterpret_cast(nonceBytes.get());
size_t actualOutLength;
- if (!realFunc(aeadCtx.get(), outBuf, &actualOutLength, outRange,
- nonceTmp, nonceBytes.size(), inBuf, static_cast(inRange),
- aad_chars, aad_chars_size)) {
+ if (!realFunc(aeadCtx.get(), outBuf, &actualOutLength, outRange, nonceTmp, nonceBytes.size(),
+ inBuf, static_cast(inRange), aad_chars, aad_chars_size)) {
conscrypt::jniutil::throwExceptionFromBoringSSLError(env, "evp_aead_ctx_op");
return 0;
}
- JNI_TRACE("evp_aead_ctx_op(%p, %p, %d, %p, %p, %p, %p) => success outlength=%zd",
- evpAead, keyArray, tagLen, outBuffer, nonceArray, inBuffer,
- aadArray, actualOutLength);
+ JNI_TRACE("evp_aead_ctx_op(%p, %p, %d, %p, %p, %p, %p) => success outlength=%zd", evpAead,
+ keyArray, tagLen, outBuffer, nonceArray, inBuffer, aadArray, actualOutLength);
return static_cast(actualOutLength);
}
@@ -4522,7 +4516,6 @@ static jint evp_aead_ctx_op(JNIEnv* env, jlong evpAeadRef, jbyteArray keyArray,
JNI_TRACE("evp_aead_ctx_op(%p, %p, %d, %p, %d, %p, %p, %d, %d, %p)", evpAead, keyArray, tagLen,
outArray, outOffset, nonceArray, inArray, inOffset, inLength, aadArray);
-
ScopedByteArrayRW outBytes(env, outArray);
if (outBytes.get() == nullptr) {
return 0;
@@ -4554,18 +4547,17 @@ static jint evp_aead_ctx_op(JNIEnv* env, jlong evpAeadRef, jbyteArray keyArray,
uint8_t* outTmp = reinterpret_cast(outBytes.get());
const uint8_t* inTmp = reinterpret_cast(inBytes.get());
- return evp_aead_ctx_op_common(env, evpAeadRef, keyArray, tagLen, outTmp + outOffset, nonceArray, inTmp + inOffset,
- aadArray, realFunc, inArray, outArray, outBytes.size() - outOffset, inLength);
+ return evp_aead_ctx_op_common(env, evpAeadRef, keyArray, tagLen, outTmp + outOffset, nonceArray,
+ inTmp + inOffset, aadArray, realFunc, inArray, outArray,
+ outBytes.size() - outOffset, inLength);
}
static jint evp_aead_ctx_op_buf(JNIEnv* env, jlong evpAeadRef, jbyteArray keyArray, jint tagLen,
- jobject outBuffer, jbyteArray nonceArray,
- jobject inBuffer, jbyteArray aadArray,
- evp_aead_ctx_op_func realFunc) {
-
+ jobject outBuffer, jbyteArray nonceArray, jobject inBuffer,
+ jbyteArray aadArray, evp_aead_ctx_op_func realFunc) {
const EVP_AEAD* evpAead = reinterpret_cast(evpAeadRef);
- JNI_TRACE("evp_aead_ctx_op(%p, %p, %d, %p, %p, %p, %p)", evpAead, keyArray, tagLen,
- outBuffer, nonceArray, inBuffer, aadArray);
+ JNI_TRACE("evp_aead_ctx_op(%p, %p, %d, %p, %p, %p, %p)", evpAead, keyArray, tagLen, outBuffer,
+ nonceArray, inBuffer, aadArray);
if (!conscrypt::jniutil::isDirectByteBufferInstance(env, inBuffer)) {
conscrypt::jniutil::throwException(env, "java/lang/IllegalArgumentException",
@@ -4584,19 +4576,19 @@ static jint evp_aead_ctx_op_buf(JNIEnv* env, jlong evpAeadRef, jbyteArray keyArr
jint in_position;
inBuf = (uint8_t*)(env->GetDirectBufferAddress(inBuffer));
- // limit is the index of the first element that should not be read or written
- in_limit = env->CallIntMethod(inBuffer,conscrypt::jniutil::buffer_limitMethod);
+ // limit is the index of the first element that should not be read or written
+ in_limit = env->CallIntMethod(inBuffer, conscrypt::jniutil::buffer_limitMethod);
// position is the index of the next element to be read or written
- in_position = env->CallIntMethod(inBuffer,conscrypt::jniutil::buffer_positionMethod);
+ in_position = env->CallIntMethod(inBuffer, conscrypt::jniutil::buffer_positionMethod);
uint8_t* outBuf;
jint out_limit;
jint out_position;
outBuf = (uint8_t*)(env->GetDirectBufferAddress(outBuffer));
// limit is the index of the first element that should not be read or written
- out_limit = env->CallIntMethod(outBuffer,conscrypt::jniutil::buffer_limitMethod);
+ out_limit = env->CallIntMethod(outBuffer, conscrypt::jniutil::buffer_limitMethod);
// position is the index of the next element to be read or written
- out_position = env->CallIntMethod(outBuffer,conscrypt::jniutil::buffer_positionMethod);
+ out_position = env->CallIntMethod(outBuffer, conscrypt::jniutil::buffer_positionMethod);
// Shifting over of ByteBuffer address to start at true position
inBuf += in_position;
@@ -4606,9 +4598,9 @@ static jint evp_aead_ctx_op_buf(JNIEnv* env, jlong evpAeadRef, jbyteArray keyArr
uint8_t* outBufEnd = outBuf + out_limit - out_position;
uint8_t* inBufEnd = inBuf + inSize;
std::unique_ptr inCopy;
- if (outBufEnd >= inBuf && inBufEnd >= outBuf) { // We have an overlap
- inCopy.reset((new(std::nothrow) uint8_t[inSize]));
- if (inCopy.get() == nullptr) {
+ if (outBufEnd >= inBuf && inBufEnd >= outBuf) { // We have an overlap
+ inCopy.reset((new (std::nothrow) uint8_t[inSize]));
+ if (inCopy.get() == nullptr) {
conscrypt::jniutil::throwOutOfMemory(env, "Unable to allocate new buffer for overlap");
return 0;
}
@@ -4616,8 +4608,9 @@ static jint evp_aead_ctx_op_buf(JNIEnv* env, jlong evpAeadRef, jbyteArray keyArr
inBuf = inCopy.get();
}
- return evp_aead_ctx_op_common(env, evpAeadRef, keyArray, tagLen, outBuf, nonceArray, inBuf, aadArray, realFunc,
- inBuffer, outBuffer, out_limit-out_position, in_limit-in_position);
+ return evp_aead_ctx_op_common(env, evpAeadRef, keyArray, tagLen, outBuf, nonceArray, inBuf,
+ aadArray, realFunc, inBuffer, outBuffer, out_limit - out_position,
+ in_limit - in_position);
}
static jint NativeCrypto_EVP_AEAD_CTX_seal(JNIEnv* env, jclass, jlong evpAeadRef,
@@ -4641,19 +4634,21 @@ static jint NativeCrypto_EVP_AEAD_CTX_open(JNIEnv* env, jclass, jlong evpAeadRef
}
static jint NativeCrypto_EVP_AEAD_CTX_seal_buf(JNIEnv* env, jclass, jlong evpAeadRef,
- jbyteArray keyArray, jint tagLen, jobject outBuffer,
- jbyteArray nonceArray, jobject inBuffer, jbyteArray aadArray) {
+ jbyteArray keyArray, jint tagLen, jobject outBuffer,
+ jbyteArray nonceArray, jobject inBuffer,
+ jbyteArray aadArray) {
CHECK_ERROR_QUEUE_ON_RETURN;
- return evp_aead_ctx_op_buf(env, evpAeadRef, keyArray, tagLen, outBuffer, nonceArray,
- inBuffer, aadArray, EVP_AEAD_CTX_seal);
+ return evp_aead_ctx_op_buf(env, evpAeadRef, keyArray, tagLen, outBuffer, nonceArray, inBuffer,
+ aadArray, EVP_AEAD_CTX_seal);
}
static jint NativeCrypto_EVP_AEAD_CTX_open_buf(JNIEnv* env, jclass, jlong evpAeadRef,
- jbyteArray keyArray, jint tagLen, jobject outBuffer,
- jbyteArray nonceArray, jobject inBuffer, jbyteArray aadArray) {
+ jbyteArray keyArray, jint tagLen, jobject outBuffer,
+ jbyteArray nonceArray, jobject inBuffer,
+ jbyteArray aadArray) {
CHECK_ERROR_QUEUE_ON_RETURN;
- return evp_aead_ctx_op_buf(env, evpAeadRef, keyArray, tagLen, outBuffer, nonceArray,
- inBuffer, aadArray, EVP_AEAD_CTX_open);
+ return evp_aead_ctx_op_buf(env, evpAeadRef, keyArray, tagLen, outBuffer, nonceArray, inBuffer,
+ aadArray, EVP_AEAD_CTX_open);
}
static jbyteArray NativeCrypto_EVP_HPKE_CTX_export(JNIEnv* env, jclass, jobject hpkeCtxRef,
@@ -4689,7 +4684,8 @@ static jbyteArray NativeCrypto_EVP_HPKE_CTX_export(JNIEnv* env, jclass, jobject
return {};
}
- ScopedLocalRef exportedArray(env, env->NewByteArray(static_cast(exportedLen)));
+ ScopedLocalRef exportedArray(env,
+ env->NewByteArray(static_cast(exportedLen)));
if (exportedArray.get() == nullptr) {
return {};
}
@@ -4760,7 +4756,8 @@ static jbyteArray NativeCrypto_EVP_HPKE_CTX_open(JNIEnv* env, jclass, jobject re
}
plaintext.resize(plaintextLen);
- ScopedLocalRef plaintextArray(env, env->NewByteArray(static_cast(plaintextLen)));
+ ScopedLocalRef plaintextArray(env,
+ env->NewByteArray(static_cast(plaintextLen)));
if (plaintextArray.get() == nullptr) {
return {};
}
@@ -4816,7 +4813,8 @@ static jbyteArray NativeCrypto_EVP_HPKE_CTX_seal(JNIEnv* env, jclass, jobject se
return {};
}
- ScopedLocalRef ciphertextArray(env, env->NewByteArray(static_cast(encryptedLen)));
+ ScopedLocalRef ciphertextArray(env,
+ env->NewByteArray(static_cast(encryptedLen)));
if (ciphertextArray.get() == nullptr) {
return {};
}
@@ -4865,12 +4863,9 @@ const EVP_HPKE_KEM* getHpkeKem(JNIEnv* env, jint kemValue) {
}
}
-static jobject NativeCrypto_EVP_HPKE_CTX_setup_base_mode_recipient(JNIEnv* env, jclass,
- jint kemValue,jint kdfValue,
- jint aeadValue,
- jbyteArray privateKeyArray,
- jbyteArray encArray,
- jbyteArray infoArray) {
+static jobject NativeCrypto_EVP_HPKE_CTX_setup_base_mode_recipient(
+ JNIEnv* env, jclass, jint kemValue, jint kdfValue, jint aeadValue,
+ jbyteArray privateKeyArray, jbyteArray encArray, jbyteArray infoArray) {
CHECK_ERROR_QUEUE_ON_RETURN;
JNI_TRACE("EVP_HPKE_CTX_setup_recipient(%d, %d, %d, %p, %p, %p)", kemValue, kdfValue, aeadValue,
privateKeyArray, encArray, infoArray);
@@ -4935,14 +4930,14 @@ static jobject NativeCrypto_EVP_HPKE_CTX_setup_base_mode_recipient(JNIEnv* env,
}
ScopedLocalRef ctxObject(
- env, env->NewObject(conscrypt::jniutil::nativeRefHpkeCtxClass,
- conscrypt::jniutil::nativeRefHpkeCtxClass_constructor,
- reinterpret_cast(ctx.release())));
+ env, env->NewObject(conscrypt::jniutil::nativeRefHpkeCtxClass,
+ conscrypt::jniutil::nativeRefHpkeCtxClass_constructor,
+ reinterpret_cast(ctx.release())));
return ctxObject.release();
}
static jobjectArray NativeCrypto_EVP_HPKE_CTX_setup_base_mode_sender(JNIEnv* env, jclass,
- jint kemValue,jint kdfValue,
+ jint kemValue, jint kdfValue,
jint aeadValue,
jbyteArray publicKeyArray,
jbyteArray infoArray) {
@@ -4986,22 +4981,24 @@ static jobjectArray NativeCrypto_EVP_HPKE_CTX_setup_base_mode_sender(JNIEnv* env
bssl::UniquePtr ctx(EVP_HPKE_CTX_new());
- if (!EVP_HPKE_CTX_setup_sender(/* ctx= */ ctx.get(),
- /* out_enc= */ encapsulatedSharedSecret,
- /* out_enc_len= */ &encapsulatedSharedSecretLen,
- /* max_enc= */ EVP_HPKE_MAX_ENC_LENGTH,
- /* kem= */ kem,
- /* kdf= */ kdf,
- /* aead= */ aead,
- /* peer_public_key= */ reinterpret_cast(peer_public_key.get()),
- /* peer_public_key_len= */ peer_public_key.size(),
- /* info= */ info,
- /* info_len= */ infoLen)) {
+ if (!EVP_HPKE_CTX_setup_sender(
+ /* ctx= */ ctx.get(),
+ /* out_enc= */ encapsulatedSharedSecret,
+ /* out_enc_len= */ &encapsulatedSharedSecretLen,
+ /* max_enc= */ EVP_HPKE_MAX_ENC_LENGTH,
+ /* kem= */ kem,
+ /* kdf= */ kdf,
+ /* aead= */ aead,
+ /* peer_public_key= */ reinterpret_cast(peer_public_key.get()),
+ /* peer_public_key_len= */ peer_public_key.size(),
+ /* info= */ info,
+ /* info_len= */ infoLen)) {
conscrypt::jniutil::throwExceptionFromBoringSSLError(env, "EVP_HPKE_CTX_setup_sender");
return {};
}
- ScopedLocalRef encArray(env, env->NewByteArray(static_cast(encapsulatedSharedSecretLen)));
+ ScopedLocalRef encArray(
+ env, env->NewByteArray(static_cast(encapsulatedSharedSecretLen)));
if (encArray.get() == nullptr) {
return {};
}
@@ -5009,15 +5006,16 @@ static jobjectArray NativeCrypto_EVP_HPKE_CTX_setup_base_mode_sender(JNIEnv* env
if (encBytes.get() == nullptr) {
return {};
}
- memcpy(encBytes.get(), reinterpret_cast(encapsulatedSharedSecret), encapsulatedSharedSecretLen);
+ memcpy(encBytes.get(), reinterpret_cast(encapsulatedSharedSecret),
+ encapsulatedSharedSecretLen);
ScopedLocalRef result(
env, env->NewObjectArray(2, conscrypt::jniutil::objectClass, nullptr));
ScopedLocalRef ctxObject(
- env, env->NewObject(conscrypt::jniutil::nativeRefHpkeCtxClass,
- conscrypt::jniutil::nativeRefHpkeCtxClass_constructor,
- reinterpret_cast(ctx.release())));
+ env, env->NewObject(conscrypt::jniutil::nativeRefHpkeCtxClass,
+ conscrypt::jniutil::nativeRefHpkeCtxClass_constructor,
+ reinterpret_cast(ctx.release())));
env->SetObjectArrayElement(result.get(), 0, ctxObject.release());
env->SetObjectArrayElement(result.get(), 1, encArray.release());
@@ -5071,25 +5069,26 @@ static jobjectArray NativeCrypto_EVP_HPKE_CTX_setup_base_mode_sender_with_seed_f
bssl::UniquePtr ctx(EVP_HPKE_CTX_new());
if (!EVP_HPKE_CTX_setup_sender_with_seed_for_testing(
- /* ctx= */ ctx.get(),
- /* out_enc= */ encapsulatedSharedSecret,
- /* out_enc_len= */ &encapsulatedSharedSecretLen,
- /* max_enc= */ EVP_HPKE_MAX_ENC_LENGTH,
- /* kem= */ kem,
- /* kdf= */ kdf,
- /* aead= */ aead,
- /* peer_public_key= */ reinterpret_cast(peer_public_key.get()),
- /* peer_public_key_len= */ peer_public_key.size(),
- /* info= */ info,
- /* info_len= */ infoLen,
- /* seed= */ reinterpret_cast(seed.get()),
- /* seed_len= */ seed.size())) {
+ /* ctx= */ ctx.get(),
+ /* out_enc= */ encapsulatedSharedSecret,
+ /* out_enc_len= */ &encapsulatedSharedSecretLen,
+ /* max_enc= */ EVP_HPKE_MAX_ENC_LENGTH,
+ /* kem= */ kem,
+ /* kdf= */ kdf,
+ /* aead= */ aead,
+ /* peer_public_key= */ reinterpret_cast(peer_public_key.get()),
+ /* peer_public_key_len= */ peer_public_key.size(),
+ /* info= */ info,
+ /* info_len= */ infoLen,
+ /* seed= */ reinterpret_cast(seed.get()),
+ /* seed_len= */ seed.size())) {
conscrypt::jniutil::throwExceptionFromBoringSSLError(
env, "EVP_HPKE_CTX_setup_sender_with_seed_for_testing");
return {};
}
- ScopedLocalRef encArray(env, env->NewByteArray(static_cast(encapsulatedSharedSecretLen)));
+ ScopedLocalRef encArray(
+ env, env->NewByteArray(static_cast(encapsulatedSharedSecretLen)));
if (encArray.get() == nullptr) {
return {};
}
@@ -5097,15 +5096,16 @@ static jobjectArray NativeCrypto_EVP_HPKE_CTX_setup_base_mode_sender_with_seed_f
if (encBytes.get() == nullptr) {
return {};
}
- memcpy(encBytes.get(), reinterpret_cast(encapsulatedSharedSecret), encapsulatedSharedSecretLen);
+ memcpy(encBytes.get(), reinterpret_cast(encapsulatedSharedSecret),
+ encapsulatedSharedSecretLen);
ScopedLocalRef result(
env, env->NewObjectArray(2, conscrypt::jniutil::objectClass, nullptr));
ScopedLocalRef ctxObject(
- env, env->NewObject(conscrypt::jniutil::nativeRefHpkeCtxClass,
- conscrypt::jniutil::nativeRefHpkeCtxClass_constructor,
- reinterpret_cast(ctx.release())));
+ env, env->NewObject(conscrypt::jniutil::nativeRefHpkeCtxClass,
+ conscrypt::jniutil::nativeRefHpkeCtxClass_constructor,
+ reinterpret_cast(ctx.release())));
env->SetObjectArrayElement(result.get(), 0, ctxObject.release());
env->SetObjectArrayElement(result.get(), 1, encArray.release());
@@ -5150,21 +5150,21 @@ static void NativeCrypto_CMAC_Init(JNIEnv* env, jclass, jobject cmacCtxRef, jbyt
const uint8_t* keyPtr = reinterpret_cast(keyBytes.get());
- const EVP_CIPHER *cipher;
- switch(keyBytes.size()) {
- case 16:
- cipher = EVP_aes_128_cbc();
- break;
- case 24:
- cipher = EVP_aes_192_cbc();
- break;
- case 32:
- cipher = EVP_aes_256_cbc();
- break;
- default:
- conscrypt::jniutil::throwException(env, "java/lang/IllegalArgumentException",
- "CMAC_Init: Unsupported key length");
- return;
+ const EVP_CIPHER* cipher;
+ switch (keyBytes.size()) {
+ case 16:
+ cipher = EVP_aes_128_cbc();
+ break;
+ case 24:
+ cipher = EVP_aes_192_cbc();
+ break;
+ case 32:
+ cipher = EVP_aes_256_cbc();
+ break;
+ default:
+ conscrypt::jniutil::throwException(env, "java/lang/IllegalArgumentException",
+ "CMAC_Init: Unsupported key length");
+ return;
}
if (!CMAC_Init(cmacCtx, keyPtr, keyBytes.size(), cipher, nullptr)) {
@@ -5468,7 +5468,7 @@ static jlong NativeCrypto_create_BIO_InputStream(JNIEnv* env, jclass, jobject st
return 0;
}
- const BIO_METHOD *method = stream_bio_method();
+ const BIO_METHOD* method = stream_bio_method();
if (!method) {
return 0;
}
@@ -5492,7 +5492,7 @@ static jlong NativeCrypto_create_BIO_OutputStream(JNIEnv* env, jclass, jobject s
return 0;
}
- const BIO_METHOD *method = stream_bio_method();
+ const BIO_METHOD* method = stream_bio_method();
if (!method) {
return 0;
}
@@ -5569,7 +5569,7 @@ static jobject GENERAL_NAME_to_jobject(JNIEnv* env, GENERAL_NAME* gen) {
// Converting ASCII to UTF-16 is the identity function.
jchars.push_back(data[i]);
}
- JNI_TRACE("GENERAL_NAME_to_jobject(%p)=> Email/DNS/URI \"%.*s\"", gen, (int) len, data);
+ JNI_TRACE("GENERAL_NAME_to_jobject(%p)=> Email/DNS/URI \"%.*s\"", gen, (int)len, data);
return env->NewString(jchars.data(), jchars.size());
}
case GEN_DIRNAME:
@@ -5647,7 +5647,8 @@ static jobjectArray NativeCrypto_get_X509_GENERAL_NAME_stack(JNIEnv* env, jclass
// TODO(https://github.com/google/conscrypt/issues/916): Handle errors, remove
// |ERR_clear_error|, and throw CertificateParsingException.
if (gn_stack == nullptr) {
- JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => null (no extension or error)", x509, type);
+ JNI_TRACE("get_X509_GENERAL_NAME_stack(%p, %d) => null (no extension or error)", x509,
+ type);
ERR_clear_error();
return nullptr;
}
@@ -6582,12 +6583,9 @@ static void NativeCrypto_ASN1_TIME_to_Calendar(JNIEnv* env, jclass, jlong asn1Ti
int year, mon, mday, hour, min, sec;
const char* data = reinterpret_cast(ASN1_STRING_get0_data(gen.get()));
- if (!decimal_to_integer(data, 4, &year) ||
- !decimal_to_integer(data + 4, 2, &mon) ||
- !decimal_to_integer(data + 6, 2, &mday) ||
- !decimal_to_integer(data + 8, 2, &hour) ||
- !decimal_to_integer(data + 10, 2, &min) ||
- !decimal_to_integer(data + 12, 2, &sec)) {
+ if (!decimal_to_integer(data, 4, &year) || !decimal_to_integer(data + 4, 2, &mon) ||
+ !decimal_to_integer(data + 6, 2, &mday) || !decimal_to_integer(data + 8, 2, &hour) ||
+ !decimal_to_integer(data + 10, 2, &min) || !decimal_to_integer(data + 12, 2, &sec)) {
conscrypt::jniutil::throwParsingException(env, "Invalid date format");
return;
}
@@ -7175,8 +7173,8 @@ static jlongArray NativeCrypto_d2i_PKCS7_bio(JNIEnv* env, jclass, jlong bioRef,
uint8_t* data;
size_t len;
if (!BIO_read_asn1(bio, &data, &len, 256 * 1024 * 1024 /* max length, 256MB for sanity */)) {
- conscrypt::jniutil::throwExceptionFromBoringSSLError(env, "Error reading PKCS#7 data",
- conscrypt::jniutil::throwParsingException);
+ conscrypt::jniutil::throwExceptionFromBoringSSLError(
+ env, "Error reading PKCS#7 data", conscrypt::jniutil::throwParsingException);
JNI_TRACE("d2i_PKCS7_bio(%p, %d) => error reading BIO", bio, which);
return nullptr;
}
@@ -7188,8 +7186,8 @@ static jlongArray NativeCrypto_d2i_PKCS7_bio(JNIEnv* env, jclass, jlong bioRef,
if (which == PKCS7_CERTS) {
bssl::UniquePtr outCerts(sk_X509_new_null());
if (!PKCS7_get_certificates(outCerts.get(), &cbs)) {
- conscrypt::jniutil::throwExceptionFromBoringSSLError(env,
- "PKCS7_get_certificates", conscrypt::jniutil::throwParsingException);
+ conscrypt::jniutil::throwExceptionFromBoringSSLError(
+ env, "PKCS7_get_certificates", conscrypt::jniutil::throwParsingException);
JNI_TRACE("d2i_PKCS7_bio(%p, %d) => error reading certs", bio, which);
return nullptr;
}
@@ -7198,8 +7196,8 @@ static jlongArray NativeCrypto_d2i_PKCS7_bio(JNIEnv* env, jclass, jlong bioRef,
} else if (which == PKCS7_CRLS) {
bssl::UniquePtr outCRLs(sk_X509_CRL_new_null());
if (!PKCS7_get_CRLs(outCRLs.get(), &cbs)) {
- conscrypt::jniutil::throwExceptionFromBoringSSLError(env, "PKCS7_get_CRLs",
- conscrypt::jniutil::throwParsingException);
+ conscrypt::jniutil::throwExceptionFromBoringSSLError(
+ env, "PKCS7_get_CRLs", conscrypt::jniutil::throwParsingException);
JNI_TRACE("d2i_PKCS7_bio(%p, %d) => error reading CRLs", bio, which);
return nullptr;
}
@@ -7224,8 +7222,8 @@ static jlongArray NativeCrypto_ASN1_seq_unpack_X509_bio(JNIEnv* env, jclass, jlo
uint8_t* data;
size_t len;
if (!BIO_read_asn1(bio, &data, &len, 256 * 1024 * 1024 /* max length, 256MB for sanity */)) {
- conscrypt::jniutil::throwExceptionFromBoringSSLError(env, "Error reading X.509 data",
- conscrypt::jniutil::throwParsingException);
+ conscrypt::jniutil::throwExceptionFromBoringSSLError(
+ env, "Error reading X.509 data", conscrypt::jniutil::throwParsingException);
JNI_TRACE("ASN1_seq_unpack_X509_bio(%p) => error reading BIO", bio);
return nullptr;
}
@@ -7875,8 +7873,9 @@ static int sslSelect(JNIEnv* env, int type, jobject fdObject, AppData* appData,
break;
}
- if (WSAEventSelect(fd.get(), events[1], (type == SSL_ERROR_WANT_READ ? FD_READ : FD_WRITE) |
- FD_CLOSE) == SOCKET_ERROR) {
+ if (WSAEventSelect(fd.get(), events[1],
+ (type == SSL_ERROR_WANT_READ ? FD_READ : FD_WRITE) | FD_CLOSE) ==
+ SOCKET_ERROR) {
JNI_TRACE("sslSelect failure in WSAEventSelect: %d", WSAGetLastError());
break;
}
@@ -8101,7 +8100,7 @@ static void info_callback(const SSL* ssl, int type, int value) {
JNI_TRACE("ssl=%p info_callback calling onSSLStateChange", ssl);
env->CallVoidMethod(sslHandshakeCallbacks,
- conscrypt::jniutil::sslHandshakeCallbacks_onSSLStateChange, type, value);
+ conscrypt::jniutil::sslHandshakeCallbacks_onSSLStateChange, type, value);
if (env->ExceptionCheck()) {
JNI_TRACE("ssl=%p info_callback exception", ssl);
@@ -8422,8 +8421,7 @@ static SSL_SESSION* server_session_requested_callback(SSL* ssl, const uint8_t* i
return ssl_session_ptr;
}
-static jint NativeCrypto_EVP_has_aes_hardware(JNIEnv* env, jclass) {
- CHECK_ERROR_QUEUE_ON_RETURN;
+static jint NativeCrypto_EVP_has_aes_hardware(CRITICAL_JNI_PARAMS) {
int ret = 0;
ret = EVP_has_aes_hardware();
JNI_TRACE("EVP_has_aes_hardware => %d", ret);
@@ -9113,8 +9111,8 @@ static jbyteArray NativeCrypto_SSL_export_keying_material(JNIEnv* env, jclass, j
int ret;
if (context == nullptr) {
ret = SSL_export_keying_material(ssl, out.get(), num_bytes,
- reinterpret_cast(labelBytes.get()), labelBytes.size(),
- nullptr, 0, 0);
+ reinterpret_cast(labelBytes.get()),
+ labelBytes.size(), nullptr, 0, 0);
} else {
ScopedByteArrayRO contextBytes(env, context);
if (contextBytes.get() == nullptr) {
@@ -9128,8 +9126,8 @@ static jbyteArray NativeCrypto_SSL_export_keying_material(JNIEnv* env, jclass, j
contextBytes.size(), 1);
}
if (!ret) {
- conscrypt::jniutil::throwExceptionFromBoringSSLError(env, "SSL_export_keying_material",
- conscrypt::jniutil::throwSSLExceptionStr);
+ conscrypt::jniutil::throwExceptionFromBoringSSLError(
+ env, "SSL_export_keying_material", conscrypt::jniutil::throwSSLExceptionStr);
JNI_TRACE("ssl=%p NativeCrypto_SSL_export_keying_material => exception", ssl);
return nullptr;
}
@@ -9491,8 +9489,7 @@ static jstring NativeCrypto_SSL_get_servername(JNIEnv* env, jclass, jlong ssl_ad
* which should take precedence.
*/
static int selectApplicationProtocol(SSL* ssl, unsigned char** out, unsigned char* outLength,
- const unsigned char* primary,
- const unsigned int primaryLength,
+ const unsigned char* primary, const unsigned int primaryLength,
const unsigned char* secondary,
const unsigned int secondaryLength) {
JNI_TRACE("primary=%p, length=%d", primary, primaryLength);
@@ -9518,9 +9515,8 @@ static int selectApplicationProtocol(SSL* ssl, unsigned char** out, unsigned cha
* Calls out to an application-provided selector to choose the ALPN protocol.
*/
static int selectApplicationProtocol(SSL* ssl, JNIEnv* env, jobject sslHandshakeCallbacks,
- unsigned char** out,
- unsigned char* outLen, const unsigned char* in,
- const unsigned int inLen) {
+ unsigned char** out, unsigned char* outLen,
+ const unsigned char* in, const unsigned int inLen) {
// Copy the input array.
ScopedLocalRef protocols(env, env->NewByteArray(static_cast(inLen)));
if (protocols.get() == nullptr) {
@@ -9580,10 +9576,10 @@ static int alpn_select_callback(SSL* ssl, const unsigned char** out, unsigned ch
const_cast(out), outLen, in, inLen);
}
- return selectApplicationProtocol(ssl, const_cast(out), outLen,
- reinterpret_cast(appData->applicationProtocolsData),
- static_cast(appData->applicationProtocolsLength),
- in, inLen);
+ return selectApplicationProtocol(
+ ssl, const_cast(out), outLen,
+ reinterpret_cast(appData->applicationProtocolsData),
+ static_cast(appData->applicationProtocolsLength), in, inLen);
}
static jbyteArray NativeCrypto_getApplicationProtocol(JNIEnv* env, jclass, jlong ssl_address,
@@ -10065,7 +10061,9 @@ static int sslRead(JNIEnv* env, SSL* ssl, jobject fdObject, jobject shc, char* b
}
// Everything else is basically an error.
- default: { return THROW_SSLEXCEPTION; }
+ default: {
+ return THROW_SSLEXCEPTION;
+ }
}
}
@@ -10342,7 +10340,9 @@ static int sslWrite(JNIEnv* env, SSL* ssl, jobject fdObject, jobject shc, const
}
// Everything else is basically an error.
- default: { return THROW_SSLEXCEPTION; }
+ default: {
+ return THROW_SSLEXCEPTION;
+ }
}
}
JNI_TRACE("ssl=%p sslWrite => count=%d", ssl, count);
@@ -10715,9 +10715,8 @@ static jlong NativeCrypto_SSL_get_timeout(JNIEnv* env, jclass, jlong ssl_address
return result;
}
-static jint NativeCrypto_SSL_get_signature_algorithm_key_type(JNIEnv* env, jclass,
- jint signatureAlg) {
- CHECK_ERROR_QUEUE_ON_RETURN;
+static jint NativeCrypto_SSL_get_signature_algorithm_key_type(
+ CRITICAL_JNI_PARAMS_COMMA jint signatureAlg) {
return SSL_get_signature_algorithm_key_type(signatureAlg);
}
@@ -11190,7 +11189,7 @@ static jint NativeCrypto_SSL_get_error(JNIEnv* env, jclass, jlong ssl_address,
return SSL_get_error(ssl, ret);
}
-static void NativeCrypto_SSL_clear_error(JNIEnv*, jclass) {
+static void NativeCrypto_SSL_clear_error(CRITICAL_JNI_PARAMS) {
ERR_clear_error();
}
@@ -11733,8 +11732,9 @@ static jboolean NativeCrypto_usesBoringSsl_FIPS_mode() {
* Scrypt support
*/
-static jbyteArray NativeCrypto_Scrypt_generate_key(JNIEnv* env, jclass, jbyteArray password, jbyteArray salt,
- jint n, jint r, jint p, jint key_len) {
+static jbyteArray NativeCrypto_Scrypt_generate_key(JNIEnv* env, jclass, jbyteArray password,
+ jbyteArray salt, jint n, jint r, jint p,
+ jint key_len) {
CHECK_ERROR_QUEUE_ON_RETURN;
JNI_TRACE("Scrypt_generate_key(%p, %p, %d, %d, %d, %d)", password, salt, n, r, p, key_len);
@@ -11761,10 +11761,10 @@ static jbyteArray NativeCrypto_Scrypt_generate_key(JNIEnv* env, jclass, jbyteArr
ScopedByteArrayRO password_bytes(env, password);
ScopedByteArrayRO salt_bytes(env, salt);
- int result = EVP_PBE_scrypt(reinterpret_cast(password_bytes.get()), password_bytes.size(),
- reinterpret_cast(salt_bytes.get()), salt_bytes.size(),
- n, r, p, memory_limit,
- reinterpret_cast(out_key.get()), key_len);
+ int result = EVP_PBE_scrypt(
+ reinterpret_cast(password_bytes.get()), password_bytes.size(),
+ reinterpret_cast(salt_bytes.get()), salt_bytes.size(), n, r, p,
+ memory_limit, reinterpret_cast(out_key.get()), key_len);
if (result <= 0) {
conscrypt::jniutil::throwExceptionFromBoringSSLError(env, "Scrypt_generate_key");
@@ -12217,12 +12217,10 @@ static jboolean NativeCrypto_SSL_CTX_ech_enable_server(JNIEnv* env, jclass, jlon
// TESTING METHODS END
-#define CONSCRYPT_NATIVE_METHOD(functionName, signature) \
- { \
- /* NOLINTNEXTLINE */ \
- (char*)#functionName, (char*)(signature), \
- reinterpret_cast(NativeCrypto_##functionName) \
- }
+#define CONSCRYPT_NATIVE_METHOD(functionName, signature) \
+ {/* NOLINTNEXTLINE */ \
+ (char*)#functionName, (char*)(signature), \
+ reinterpret_cast(NativeCrypto_##functionName)}
#define FILE_DESCRIPTOR "Ljava/io/FileDescriptor;"
#define SSL_CALLBACKS \
diff --git a/common/src/jni/main/include/conscrypt/jniutil.h b/common/src/jni/main/include/conscrypt/jniutil.h
index 7ae567dbc..de69107f5 100644
--- a/common/src/jni/main/include/conscrypt/jniutil.h
+++ b/common/src/jni/main/include/conscrypt/jniutil.h
@@ -17,16 +17,23 @@
#ifndef CONSCRYPT_JNIUTIL_H_
#define CONSCRYPT_JNIUTIL_H_
-#include
-#include
-
#include
#include
+#include
#include
+#include
namespace conscrypt {
namespace jniutil {
+#ifdef __ANDROID__
+#define CRITICAL_JNI_PARAMS
+#define CRITICAL_JNI_PARAMS_COMMA
+#else
+#define CRITICAL_JNI_PARAMS JNIEnv*, jclass
+#define CRITICAL_JNI_PARAMS_COMMA JNIEnv*, jclass,
+#endif
+
extern JavaVM* gJavaVM;
extern jclass cryptoUpcallsClass;
extern jclass openSslInputStreamClass;
@@ -308,7 +315,7 @@ extern int throwSSLExceptionWithSslErrors(JNIEnv* env, SSL* ssl, int sslErrorCod
* ensure that the error queue is empty whenever the function exits.
*/
class ErrorQueueChecker {
- public:
+public:
explicit ErrorQueueChecker(JNIEnv* env) : env(env) {}
~ErrorQueueChecker() {
if (ERR_peek_error() != 0) {
@@ -326,7 +333,7 @@ class ErrorQueueChecker {
}
}
- private:
+private:
JNIEnv* env;
};
diff --git a/common/src/main/java/org/conscrypt/AbstractConscryptEngine.java b/common/src/main/java/org/conscrypt/AbstractConscryptEngine.java
index 0f1354a93..6bbd260da 100644
--- a/common/src/main/java/org/conscrypt/AbstractConscryptEngine.java
+++ b/common/src/main/java/org/conscrypt/AbstractConscryptEngine.java
@@ -18,6 +18,7 @@
import java.nio.ByteBuffer;
import java.security.PrivateKey;
+
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLException;
@@ -111,21 +112,21 @@ public final SSLSession getHandshakeSession() {
@Override
public abstract SSLEngineResult unwrap(final ByteBuffer src, final ByteBuffer[] dsts,
- final int offset, final int length) throws SSLException;
+ final int offset, final int length) throws SSLException;
abstract SSLEngineResult unwrap(final ByteBuffer[] srcs, final ByteBuffer[] dsts)
throws SSLException;
abstract SSLEngineResult unwrap(final ByteBuffer[] srcs, int srcsOffset, final int srcsLength,
- final ByteBuffer[] dsts, final int dstsOffset, final int dstsLength)
- throws SSLException;
+ final ByteBuffer[] dsts, final int dstsOffset,
+ final int dstsLength) throws SSLException;
@Override
public abstract SSLEngineResult wrap(ByteBuffer src, ByteBuffer dst) throws SSLException;
@Override
- public abstract SSLEngineResult wrap(
- ByteBuffer[] srcs, int srcsOffset, int srcsLength, ByteBuffer dst) throws SSLException;
+ public abstract SSLEngineResult wrap(ByteBuffer[] srcs, int srcsOffset, int srcsLength,
+ ByteBuffer dst) throws SSLException;
/**
* This method enables session ticket support.
@@ -134,6 +135,13 @@ public abstract SSLEngineResult wrap(
*/
abstract void setUseSessionTickets(boolean useSessionTickets);
+ /**
+ * This method sets the ECH config data to be used in the TLS handshake.
+ *
+ * @param echConfigList the ECH config data to be used in the TLS handshake
+ */
+ abstract void setEchConfigList(byte[] echConfigList);
+
/**
* Sets the list of ALPN protocols.
*
diff --git a/common/src/main/java/org/conscrypt/AbstractConscryptSocket.java b/common/src/main/java/org/conscrypt/AbstractConscryptSocket.java
index d9848681d..e77e37562 100644
--- a/common/src/main/java/org/conscrypt/AbstractConscryptSocket.java
+++ b/common/src/main/java/org/conscrypt/AbstractConscryptSocket.java
@@ -32,6 +32,7 @@
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.List;
+
import javax.net.ssl.HandshakeCompletedEvent;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.SSLException;
@@ -118,7 +119,7 @@ int getPort() {
}
AbstractConscryptSocket(InetAddress address, int port, InetAddress clientAddress,
- int clientPort) throws IOException {
+ int clientPort) throws IOException {
super(address, port, clientAddress, clientPort);
this.socket = this;
this.peerHostname = null;
@@ -626,6 +627,13 @@ private boolean isDelegating() {
*/
abstract void setUseSessionTickets(boolean useSessionTickets);
+ /**
+ * This method sets the ECH config data to be used in the TLS handshake.
+ *
+ * @param echConfigList the ECH config data to be used in the TLS handshake
+ */
+ abstract void setEchConfigList(byte[] echConfigList);
+
/**
* Enables/disables TLS Channel ID for this server socket.
*
@@ -668,8 +676,7 @@ private boolean isDelegating() {
*
* @deprecated use {@link #getApplicationProtocol()} instead.
*/
- @Deprecated
- abstract byte[] getAlpnSelectedProtocol();
+ @Deprecated abstract byte[] getAlpnSelectedProtocol();
/**
* Sets the list of ALPN protocols. This method internally converts the protocols to their
@@ -678,8 +685,7 @@ private boolean isDelegating() {
* @param alpnProtocols the list of ALPN protocols
* @deprecated use {@link #setApplicationProtocols(String[])} instead.
*/
- @Deprecated
- abstract void setAlpnProtocols(String[] alpnProtocols);
+ @Deprecated abstract void setAlpnProtocols(String[] alpnProtocols);
/**
* Alternate version of {@link #setAlpnProtocols(String[])} that directly sets the list of
@@ -689,8 +695,7 @@ private boolean isDelegating() {
* @param alpnProtocols the encoded form of the ALPN protocol list
* @deprecated Use {@link #setApplicationProtocols(String[])} instead.
*/
- @Deprecated
- abstract void setAlpnProtocols(byte[] alpnProtocols);
+ @Deprecated abstract void setAlpnProtocols(byte[] alpnProtocols);
/**
* Sets the list of ALPN protocols.
diff --git a/common/src/main/java/org/conscrypt/ArrayUtils.java b/common/src/main/java/org/conscrypt/ArrayUtils.java
index 113be7893..5563c5c08 100644
--- a/common/src/main/java/org/conscrypt/ArrayUtils.java
+++ b/common/src/main/java/org/conscrypt/ArrayUtils.java
@@ -29,17 +29,18 @@ private ArrayUtils() {}
* Checks that the range described by {@code offset} and {@code count}
* doesn't exceed {@code arrayLength}.
*/
- static void checkOffsetAndCount(int arrayLength, int offset, int count) {
+
+ public static void checkOffsetAndCount(int arrayLength, int offset, int count) {
if ((offset | count) < 0 || offset > arrayLength || arrayLength - offset < count) {
throw new ArrayIndexOutOfBoundsException("length=" + arrayLength + "; regionStart="
- + offset + "; regionLength=" + count);
+ + offset + "; regionLength=" + count);
}
}
@SafeVarargs
@SuppressWarnings("varargs")
public static T[] concatValues(T[] a1, T... values) {
- return concat (a1, values);
+ return concat(a1, values);
}
public static T[] concat(T[] a1, T[] a2) {
diff --git a/common/src/main/java/org/conscrypt/BufferUtils.java b/common/src/main/java/org/conscrypt/BufferUtils.java
index eb0806b4c..73b115048 100644
--- a/common/src/main/java/org/conscrypt/BufferUtils.java
+++ b/common/src/main/java/org/conscrypt/BufferUtils.java
@@ -16,18 +16,24 @@
package org.conscrypt;
-import static java.lang.Math.min;
import static org.conscrypt.Preconditions.checkArgument;
+import static java.lang.Math.min;
+
import java.nio.ByteBuffer;
-final class BufferUtils {
+/**
+ * Utility methods for dealing with arrays of ByteBuffers.
+ *
+ * @hide This class is not part of the Android public SDK API
+ */
+public final class BufferUtils {
private BufferUtils() {}
/**
* Throws {@link IllegalArgumentException} if any of the buffers in the array are null.
*/
- static void checkNotNull(ByteBuffer[] buffers) {
+ public static void checkNotNull(ByteBuffer[] buffers) {
for (ByteBuffer buffer : buffers) {
if (buffer == null) {
throw new IllegalArgumentException("Null buffer in array");
@@ -38,7 +44,7 @@ static void checkNotNull(ByteBuffer[] buffers) {
/**
* Returns the total number of bytes remaining in the buffer array.
*/
- static long remaining(ByteBuffer[] buffers) {
+ public static long remaining(ByteBuffer[] buffers) {
long size = 0;
for (ByteBuffer buffer : buffers) {
size += buffer.remaining();
@@ -51,7 +57,7 @@ static long remaining(ByteBuffer[] buffers) {
*
* @throws IllegalArgumentException if there are fewer than {@code toConsume} bytes remaining
*/
- static void consume(ByteBuffer[] sourceBuffers, int toConsume) {
+ public static void consume(ByteBuffer[] sourceBuffers, int toConsume) {
for (ByteBuffer sourceBuffer : sourceBuffers) {
int amount = min(sourceBuffer.remaining(), toConsume);
if (amount > 0) {
@@ -71,7 +77,7 @@ static void consume(ByteBuffer[] sourceBuffers, int toConsume) {
* Looks for a buffer in the buffer array which EITHER is larger than {@code minSize} AND
* has no preceding non-empty buffers OR is the only non-empty buffer in the array.
*/
- static ByteBuffer getBufferLargerThan(ByteBuffer[] buffers, int minSize) {
+ public static ByteBuffer getBufferLargerThan(ByteBuffer[] buffers, int minSize) {
int length = buffers.length;
for (int i = 0; i < length; i++) {
ByteBuffer buffer = buffers[i];
@@ -99,11 +105,12 @@ static ByteBuffer getBufferLargerThan(ByteBuffer[] buffers, int minSize) {
* {@code consume()} method.
*
*/
- static ByteBuffer copyNoConsume(ByteBuffer[] buffers, ByteBuffer destination, int maxAmount) {
- checkArgument(destination.remaining() >= maxAmount, "Destination buffer too small");
- int needed = maxAmount;
+ public static ByteBuffer copyNoConsume(ByteBuffer[] buffers, ByteBuffer destination,
+ int maxAmount) {
+ checkArgument(destination.remaining() >= maxAmount, "Destination buffer too small");
+ int needed = maxAmount;
for (ByteBuffer buffer : buffers) {
- int remaining = buffer.remaining();
+ int remaining = buffer.remaining();
if (remaining > 0) {
// If this buffer can fit completely then copy it all, otherwise temporarily
// adjust its limit to fill so as to the output buffer completely
diff --git a/common/src/main/java/org/conscrypt/CertBlocklist.java b/common/src/main/java/org/conscrypt/CertBlocklist.java
index 024947b89..056718f02 100644
--- a/common/src/main/java/org/conscrypt/CertBlocklist.java
+++ b/common/src/main/java/org/conscrypt/CertBlocklist.java
@@ -16,14 +16,16 @@
package org.conscrypt;
+import org.conscrypt.Internal;
+
import java.math.BigInteger;
import java.security.PublicKey;
/**
* A set of certificates that are blacklisted from trust.
*/
+@Internal
public interface CertBlocklist {
-
/**
* Returns whether the given public key is in the blacklist.
*/
diff --git a/common/src/main/java/org/conscrypt/CertBlocklistEntry.java b/common/src/main/java/org/conscrypt/CertBlocklistEntry.java
new file mode 100644
index 000000000..950d568d5
--- /dev/null
+++ b/common/src/main/java/org/conscrypt/CertBlocklistEntry.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.conscrypt;
+
+import org.conscrypt.Internal;
+
+/**
+ * An entry in the blocklist, for the purpose of reporting.
+ */
+@Internal
+public interface CertBlocklistEntry {
+ enum Origin { SHA1_TEST, SHA1_BUILT_IN, SHA1_FILE, SHA256_TEST, SHA256_BUILT_IN, SHA256_FILE }
+
+ /**
+ * Returns the origin of this entry.
+ */
+ Origin getOrigin();
+
+ /**
+ * Returns the index of this entry in its blocklist.
+ */
+ int getIndex();
+}
diff --git a/common/src/main/java/org/conscrypt/Conscrypt.java b/common/src/main/java/org/conscrypt/Conscrypt.java
index 90c8d6c1e..819469d27 100644
--- a/common/src/main/java/org/conscrypt/Conscrypt.java
+++ b/common/src/main/java/org/conscrypt/Conscrypt.java
@@ -225,8 +225,8 @@ public ProviderBuilder isTlsV1Enabled(boolean enabledTlsV1) {
}
public Provider build() {
- return new OpenSSLProvider(
- name, provideTrustManager, defaultTlsProtocol, deprecatedTlsV1, enabledTlsV1);
+ return new OpenSSLProvider(name, provideTrustManager, defaultTlsProtocol,
+ deprecatedTlsV1, enabledTlsV1);
}
}
@@ -271,8 +271,8 @@ public static SSLContextSpi newPreferredSSLContextSpi() {
public static void setClientSessionCache(SSLContext context, SSLClientSessionCache cache) {
SSLSessionContext clientContext = context.getClientSessionContext();
if (!(clientContext instanceof ClientSessionContext)) {
- throw new IllegalArgumentException(
- "Not a conscrypt client context: " + clientContext.getClass().getName());
+ throw new IllegalArgumentException("Not a conscrypt client context: "
+ + clientContext.getClass().getName());
}
((ClientSessionContext) clientContext).setPersistentCache(cache);
}
@@ -283,8 +283,8 @@ public static void setClientSessionCache(SSLContext context, SSLClientSessionCac
public static void setServerSessionCache(SSLContext context, SSLServerSessionCache cache) {
SSLSessionContext serverContext = context.getServerSessionContext();
if (!(serverContext instanceof ServerSessionContext)) {
- throw new IllegalArgumentException(
- "Not a conscrypt client context: " + serverContext.getClass().getName());
+ throw new IllegalArgumentException("Not a conscrypt client context: "
+ + serverContext.getClass().getName());
}
((ServerSessionContext) serverContext).setPersistentCache(cache);
}
@@ -299,8 +299,8 @@ public static boolean isConscrypt(SSLSocketFactory factory) {
private static OpenSSLSocketFactoryImpl toConscrypt(SSLSocketFactory factory) {
if (!isConscrypt(factory)) {
- throw new IllegalArgumentException(
- "Not a conscrypt socket factory: " + factory.getClass().getName());
+ throw new IllegalArgumentException("Not a conscrypt socket factory: "
+ + factory.getClass().getName());
}
return (OpenSSLSocketFactoryImpl) factory;
}
@@ -332,8 +332,8 @@ public static boolean isConscrypt(SSLServerSocketFactory factory) {
private static OpenSSLServerSocketFactoryImpl toConscrypt(SSLServerSocketFactory factory) {
if (!isConscrypt(factory)) {
- throw new IllegalArgumentException(
- "Not a conscrypt server socket factory: " + factory.getClass().getName());
+ throw new IllegalArgumentException("Not a conscrypt server socket factory: "
+ + factory.getClass().getName());
}
return (OpenSSLServerSocketFactoryImpl) factory;
}
@@ -355,8 +355,8 @@ public static boolean isConscrypt(SSLSocket socket) {
private static AbstractConscryptSocket toConscrypt(SSLSocket socket) {
if (!isConscrypt(socket)) {
- throw new IllegalArgumentException(
- "Not a conscrypt socket: " + socket.getClass().getName());
+ throw new IllegalArgumentException("Not a conscrypt socket: "
+ + socket.getClass().getName());
}
return (AbstractConscryptSocket) socket;
}
@@ -400,6 +400,16 @@ public static void setUseSessionTickets(SSLSocket socket, boolean useSessionTick
toConscrypt(socket).setUseSessionTickets(useSessionTickets);
}
+ /**
+ * This method sets the ECH config data to be used in the TLS handshake.
+ *
+ * @param socket the socket
+ * @param echConfigList the ECH config data to be used in the TLS handshake
+ */
+ public static void setEchConfigList(SSLSocket socket, byte[] echConfigList) {
+ toConscrypt(socket).setEchConfigList(echConfigList);
+ }
+
/**
* Enables/disables TLS Channel ID for the given server-side socket.
*
@@ -458,8 +468,8 @@ public static String getApplicationProtocol(SSLSocket socket) {
return toConscrypt(socket).getApplicationProtocol();
}
if (!socket.getClass().getName().contains("conscrypt")) {
- throw new IllegalArgumentException(
- "Not a conscrypt socket: " + socket.getClass().getName());
+ throw new IllegalArgumentException("Not a conscrypt socket: "
+ + socket.getClass().getName());
}
return invokeConscryptMethod(socket, "getApplicationProtocol");
}
@@ -471,8 +481,8 @@ public static String getApplicationProtocol(SSLSocket socket) {
* @param socket the socket
* @param selector the ALPN protocol selector
*/
- public static void setApplicationProtocolSelector(
- SSLSocket socket, ApplicationProtocolSelector selector) {
+ public static void setApplicationProtocolSelector(SSLSocket socket,
+ ApplicationProtocolSelector selector) {
toConscrypt(socket).setApplicationProtocolSelector(selector);
}
@@ -522,8 +532,8 @@ public static byte[] getTlsUnique(SSLSocket socket) {
* completed or the connection has been closed.
* @throws SSLException if the value could not be exported.
*/
- public static byte[] exportKeyingMaterial(
- SSLSocket socket, String label, byte[] context, int length) throws SSLException {
+ public static byte[] exportKeyingMaterial(SSLSocket socket, String label, byte[] context,
+ int length) throws SSLException {
return toConscrypt(socket).exportKeyingMaterial(label, context, length);
}
@@ -536,8 +546,8 @@ public static boolean isConscrypt(SSLEngine engine) {
private static AbstractConscryptEngine toConscrypt(SSLEngine engine) {
if (!isConscrypt(engine)) {
- throw new IllegalArgumentException(
- "Not a conscrypt engine: " + engine.getClass().getName());
+ throw new IllegalArgumentException("Not a conscrypt engine: "
+ + engine.getClass().getName());
}
return (AbstractConscryptEngine) engine;
}
@@ -664,7 +674,7 @@ public static void setChannelIdPrivateKey(SSLEngine engine, PrivateKey privateKe
* @throws SSLException thrown if an SSL error occurred
*/
public static SSLEngineResult unwrap(SSLEngine engine, final ByteBuffer[] srcs,
- final ByteBuffer[] dsts) throws SSLException {
+ final ByteBuffer[] dsts) throws SSLException {
return toConscrypt(engine).unwrap(srcs, dsts);
}
@@ -682,10 +692,11 @@ public static SSLEngineResult unwrap(SSLEngine engine, final ByteBuffer[] srcs,
* @throws SSLException thrown if an SSL error occurred
*/
public static SSLEngineResult unwrap(SSLEngine engine, final ByteBuffer[] srcs, int srcsOffset,
- final int srcsLength, final ByteBuffer[] dsts, final int dstsOffset,
- final int dstsLength) throws SSLException {
- return toConscrypt(engine).unwrap(
- srcs, srcsOffset, srcsLength, dsts, dstsOffset, dstsLength);
+ final int srcsLength, final ByteBuffer[] dsts,
+ final int dstsOffset, final int dstsLength)
+ throws SSLException {
+ return toConscrypt(engine).unwrap(srcs, srcsOffset, srcsLength, dsts, dstsOffset,
+ dstsLength);
}
/**
@@ -698,6 +709,16 @@ public static void setUseSessionTickets(SSLEngine engine, boolean useSessionTick
toConscrypt(engine).setUseSessionTickets(useSessionTickets);
}
+ /**
+ * This method sets the ECH config data to be used in the TLS handshake.
+ *
+ * @param engine the engine
+ * @param echConfigList the ECH config data to be used in the TLS handshake
+ */
+ public static void setEchConfigList(SSLEngine engine, byte[] echConfigList) {
+ toConscrypt(engine).setEchConfigList(echConfigList);
+ }
+
/**
* Sets the application-layer protocols (ALPN) in prioritization order.
*
@@ -729,8 +750,8 @@ public static String[] getApplicationProtocols(SSLEngine engine) {
* @param engine the engine
* @param selector the ALPN protocol selector
*/
- public static void setApplicationProtocolSelector(
- SSLEngine engine, ApplicationProtocolSelector selector) {
+ public static void setApplicationProtocolSelector(SSLEngine engine,
+ ApplicationProtocolSelector selector) {
toConscrypt(engine).setApplicationProtocolSelector(selector);
}
@@ -746,8 +767,8 @@ public static String getApplicationProtocol(SSLEngine engine) {
return toConscrypt(engine).getApplicationProtocol();
}
if (!engine.getClass().getName().contains("conscrypt")) {
- throw new IllegalArgumentException(
- "Not a conscrypt engine: " + engine.getClass().getName());
+ throw new IllegalArgumentException("Not a conscrypt engine: "
+ + engine.getClass().getName());
}
return invokeConscryptMethod(engine, "getApplicationProtocol");
}
@@ -774,8 +795,8 @@ public static byte[] getTlsUnique(SSLEngine engine) {
* completed or the connection has been closed.
* @throws SSLException if the value could not be exported.
*/
- public static byte[] exportKeyingMaterial(
- SSLEngine engine, String label, byte[] context, int length) throws SSLException {
+ public static byte[] exportKeyingMaterial(SSLEngine engine, String label, byte[] context,
+ int length) throws SSLException {
return toConscrypt(engine).exportKeyingMaterial(label, context, length);
}
@@ -789,8 +810,8 @@ public static boolean isConscrypt(TrustManager trustManager) {
private static TrustManagerImpl toConscrypt(TrustManager trustManager) {
if (!isConscrypt(trustManager)) {
- throw new IllegalArgumentException(
- "Not a Conscrypt trust manager: " + trustManager.getClass().getName());
+ throw new IllegalArgumentException("Not a Conscrypt trust manager: "
+ + trustManager.getClass().getName());
}
return (TrustManagerImpl) trustManager;
}
@@ -824,8 +845,8 @@ public synchronized static ConscryptHostnameVerifier getDefaultHostnameVerifier(
* @throws IllegalArgumentException if the provided trust manager is not a Conscrypt trust
* manager per {@link #isConscrypt(TrustManager)}
*/
- public static void setHostnameVerifier(
- TrustManager trustManager, ConscryptHostnameVerifier verifier) {
+ public static void setHostnameVerifier(TrustManager trustManager,
+ ConscryptHostnameVerifier verifier) {
toConscrypt(trustManager).setHostnameVerifier(verifier);
}
@@ -847,8 +868,8 @@ public static ConscryptHostnameVerifier getHostnameVerifier(TrustManager trustMa
public static ConscryptHostnameVerifier wrapHostnameVerifier(final HostnameVerifier verifier) {
return new ConscryptHostnameVerifier() {
@Override
- public boolean verify(
- X509Certificate[] certificates, String hostname, SSLSession session) {
+ public boolean verify(X509Certificate[] certificates, String hostname,
+ SSLSession session) {
return verifier.verify(hostname, session);
}
};
diff --git a/common/src/main/java/org/conscrypt/ConscryptFileDescriptorSocket.java b/common/src/main/java/org/conscrypt/ConscryptFileDescriptorSocket.java
index c457a1636..85e36f187 100644
--- a/common/src/main/java/org/conscrypt/ConscryptFileDescriptorSocket.java
+++ b/common/src/main/java/org/conscrypt/ConscryptFileDescriptorSocket.java
@@ -62,8 +62,7 @@
*
*/
class ConscryptFileDescriptorSocket extends OpenSSLSocketImpl
- implements NativeCrypto.SSLHandshakeCallbacks,
- SSLParametersImpl.PSKCallbacks,
+ implements NativeCrypto.SSLHandshakeCallbacks, SSLParametersImpl.PSKCallbacks,
SSLParametersImpl.AliasChooser {
private static final boolean DBG_STATE = false;
@@ -111,12 +110,12 @@ class ConscryptFileDescriptorSocket extends OpenSSLSocketImpl
* The session object exposed externally from this class.
*/
private final SSLSession externalSession =
- Platform.wrapSSLSession(new ExternalSession(new ExternalSession.Provider() {
- @Override
- public ConscryptSession provideSession() {
- return ConscryptFileDescriptorSocket.this.provideSession();
- }
- }));
+ Platform.wrapSSLSession(new ExternalSession(new ExternalSession.Provider() {
+ @Override
+ public ConscryptSession provideSession() {
+ return ConscryptFileDescriptorSocket.this.provideSession();
+ }
+ }));
private int writeTimeoutMilliseconds = 0;
private int handshakeTimeoutMilliseconds = -1; // -1 = same as timeout; 0 = infinite
@@ -148,7 +147,8 @@ public ConscryptSession provideSession() {
}
ConscryptFileDescriptorSocket(String hostname, int port, InetAddress clientAddress,
- int clientPort, SSLParametersImpl sslParameters) throws IOException {
+ int clientPort, SSLParametersImpl sslParameters)
+ throws IOException {
super(hostname, port, clientAddress, clientPort);
this.sslParameters = sslParameters;
this.ssl = newSsl(sslParameters, this);
@@ -156,7 +156,8 @@ public ConscryptSession provideSession() {
}
ConscryptFileDescriptorSocket(InetAddress address, int port, InetAddress clientAddress,
- int clientPort, SSLParametersImpl sslParameters) throws IOException {
+ int clientPort, SSLParametersImpl sslParameters)
+ throws IOException {
super(address, port, clientAddress, clientPort);
this.sslParameters = sslParameters;
this.ssl = newSsl(sslParameters, this);
@@ -164,7 +165,7 @@ public ConscryptSession provideSession() {
}
ConscryptFileDescriptorSocket(Socket socket, String hostname, int port, boolean autoClose,
- SSLParametersImpl sslParameters) throws IOException {
+ SSLParametersImpl sslParameters) throws IOException {
super(socket, hostname, port, autoClose);
this.sslParameters = sslParameters;
this.ssl = newSsl(sslParameters, this);
@@ -172,7 +173,7 @@ public ConscryptSession provideSession() {
}
private static NativeSsl newSsl(SSLParametersImpl sslParameters,
- ConscryptFileDescriptorSocket engine) throws SSLException {
+ ConscryptFileDescriptorSocket engine) throws SSLException {
return NativeSsl.newInstance(sslParameters, engine, engine, engine);
}
@@ -306,7 +307,7 @@ public final void startHandshake() throws IOException {
@Override
@SuppressWarnings("unused") // used by NativeCrypto.SSLHandshakeCallbacks / client_cert_cb
public final void clientCertificateRequested(byte[] keyTypeBytes, int[] signatureAlgs,
- byte[][] asn1DerEncodedPrincipals)
+ byte[][] asn1DerEncodedPrincipals)
throws CertificateEncodingException, SSLException {
ssl.chooseClientCertificate(keyTypeBytes, signatureAlgs, asn1DerEncodedPrincipals);
}
@@ -476,9 +477,8 @@ private void waitForHandshake() throws IOException {
startHandshake();
synchronized (ssl) {
- while (state != STATE_READY &&
- state != STATE_READY_HANDSHAKE_CUT_THROUGH &&
- state != STATE_CLOSED) {
+ while (state != STATE_READY && state != STATE_READY_HANDSHAKE_CUT_THROUGH
+ && state != STATE_CLOSED) {
try {
ssl.wait();
} catch (InterruptedException e) {
@@ -506,8 +506,7 @@ private class SSLInputStream extends InputStream {
*/
private final Object readLock = new Object();
- SSLInputStream() {
- }
+ SSLInputStream() {}
/**
* Reads one byte. If there is no data in the underlying buffer,
@@ -546,8 +545,8 @@ public int read(byte[] buf, int offset, int byteCount) throws IOException {
}
}
- int ret = ssl.read(
- Platform.getFileDescriptor(socket), buf, offset, byteCount, getSoTimeout());
+ int ret = ssl.read(Platform.getFileDescriptor(socket), buf, offset, byteCount,
+ getSoTimeout());
if (ret == -1) {
synchronized (ssl) {
if (state == STATE_CLOSED) {
@@ -590,8 +589,7 @@ private class SSLOutputStream extends OutputStream {
*/
private final Object writeLock = new Object();
- SSLOutputStream() {
- }
+ SSLOutputStream() {}
/**
* Method acts as described in spec for superclass.
@@ -629,7 +627,7 @@ public void write(byte[] buf, int offset, int byteCount) throws IOException {
}
ssl.write(Platform.getFileDescriptor(socket), buf, offset, byteCount,
- writeTimeoutMilliseconds);
+ writeTimeoutMilliseconds);
synchronized (ssl) {
if (state == STATE_CLOSED) {
@@ -687,16 +685,16 @@ private ConscryptSession provideSession() {
// After handshake has started, provide active session otherwise a null session,
// for code which needs to read session attributes without triggering the handshake.
private ConscryptSession provideAfterHandshakeSession() {
- return (state < STATE_HANDSHAKE_STARTED)
- ? SSLNullSession.getNullSession()
- : provideSession();
+ return (state < STATE_HANDSHAKE_STARTED) ? SSLNullSession.getNullSession()
+ : provideSession();
}
// If handshake is in progress, provide active session otherwise a null session.
private ConscryptSession provideHandshakeSession() {
synchronized (ssl) {
- return state >= STATE_HANDSHAKE_STARTED && state < STATE_READY ? activeSession
- : SSLNullSession.getNullSession();
+ return state >= STATE_HANDSHAKE_STARTED && state < STATE_READY
+ ? activeSession
+ : SSLNullSession.getNullSession();
}
}
@@ -775,6 +773,11 @@ public final void setUseSessionTickets(boolean useSessionTickets) {
sslParameters.setUseSessionTickets(useSessionTickets);
}
+ @Override
+ public final void setEchConfigList(byte[] echConfigList) {
+ sslParameters.setEchConfigList(echConfigList);
+ }
+
/**
* This method enables Server Name Indication. If the hostname is not a valid SNI hostname,
* the SNI extension will be omitted from the handshake.
@@ -805,7 +808,7 @@ public final void setChannelIdEnabled(boolean enabled) {
if (state != STATE_NEW) {
throw new IllegalStateException(
"Could not enable/disable Channel ID after the initial handshake has"
- + " begun.");
+ + " begun.");
}
}
sslParameters.channelIdEnabled = enabled;
@@ -858,7 +861,7 @@ public final void setChannelIdPrivateKey(PrivateKey privateKey) {
if (state != STATE_NEW) {
throw new IllegalStateException(
"Could not change Channel ID private key after the initial handshake has"
- + " begun.");
+ + " begun.");
}
}
@@ -1133,7 +1136,8 @@ public final String getApplicationProtocol() {
public final String getHandshakeApplicationProtocol() {
synchronized (ssl) {
return state >= STATE_HANDSHAKE_STARTED && state < STATE_READY
- ? getApplicationProtocol() : null;
+ ? getApplicationProtocol()
+ : null;
}
}
@@ -1164,7 +1168,8 @@ public final String chooseClientPSKIdentity(PSKKeyManager keyManager, String ide
@Override
@SuppressWarnings("deprecation") // PSKKeyManager is deprecated, but in our own package
- public final SecretKey getPSKKey(PSKKeyManager keyManager, String identityHint, String identity) {
+ public final SecretKey getPSKKey(PSKKeyManager keyManager, String identityHint,
+ String identity) {
return keyManager.getKey(identityHint, identity, this);
}
@@ -1202,8 +1207,8 @@ private void transitionTo(int newState) {
if (handshakeStartedMillis != 0) {
StatsLog statsLog = Platform.getStatsLog();
if (statsLog != null) {
- statsLog.countTlsHandshake(true, activeSession.getProtocol(),
- activeSession.getCipherSuite(),
+ statsLog.countTlsHandshake(
+ true, activeSession.getProtocol(), activeSession.getCipherSuite(),
Platform.getMillisSinceBoot() - handshakeStartedMillis);
}
handshakeStartedMillis = 0;
@@ -1215,7 +1220,8 @@ private void transitionTo(int newState) {
// Handshake was in progress so must have failed.
StatsLog statsLog = Platform.getStatsLog();
if (statsLog != null) {
- statsLog.countTlsHandshake(false, "TLS_PROTO_FAILED", "TLS_CIPHER_FAILED",
+ statsLog.countTlsHandshake(
+ false, "TLS_PROTO_FAILED", "TLS_CIPHER_FAILED",
Platform.getMillisSinceBoot() - handshakeStartedMillis);
}
handshakeStartedMillis = 0;
diff --git a/common/src/main/java/org/conscrypt/ConscryptX509TrustManager.java b/common/src/main/java/org/conscrypt/ConscryptX509TrustManager.java
new file mode 100644
index 000000000..f3586d6f9
--- /dev/null
+++ b/common/src/main/java/org/conscrypt/ConscryptX509TrustManager.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.conscrypt;
+
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.List;
+
+/**
+ * Interface for TrustManager methods implemented in Conscrypt but not part of
+ * the standard X509TrustManager or X509ExtendedTrustManager.
+ *
+ * These methods can be called by the Android framework. Extend
+ * X509TrustManagerExtensions if these need to be visible to apps.
+ */
+@Internal
+public interface ConscryptX509TrustManager {
+ /**
+ * Verifies the given certificate chain.
+ *
+ *
See {@link X509TrustManager#checkServerTrusted(X509Certificate[], String)} for a
+ * description of the chain and authType parameters. The final parameter, host, should be the
+ * hostname of the server.
+ *
+ * @throws CertificateException if the chain does not verify correctly.
+ * @return the properly ordered chain used for verification as a list of X509Certificates.
+ */
+ public List checkServerTrusted(X509Certificate[] chain, String authType,
+ String hostname) throws CertificateException;
+
+ /**
+ * Verifies the given certificate chain.
+ *
+ *
See {@link X509TrustManager#checkServerTrusted(X509Certificate[], String)} for a
+ * description of the chain and authType parameters. The final parameter, host, should be the
+ * hostname of the server.
+ *
+ *
ocspData and tlsSctData may be provided to verify any Signed Certificate Timestamp (SCT)
+ * attached to the connection. These are ASN.1 octet strings (SignedCertificateTimestampList) as
+ * described in RFC 6962, Section 3.3. Note that SCTs embedded in the certificate chain will
+ * automatically be processed.
+ *
+ * @throws CertificateException if the chain does not verify correctly.
+ * @return the properly ordered chain used for verification as a list of X509Certificates.
+ */
+ public List checkServerTrusted(X509Certificate[] chain, byte[] ocspData,
+ byte[] tlsSctData, String authType,
+ String hostname) throws CertificateException;
+}
diff --git a/common/src/main/java/org/conscrypt/DomainEncryptionMode.java b/common/src/main/java/org/conscrypt/DomainEncryptionMode.java
new file mode 100644
index 000000000..ab878a468
--- /dev/null
+++ b/common/src/main/java/org/conscrypt/DomainEncryptionMode.java
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.conscrypt;
+
+@Internal enum DomainEncryptionMode { UNKNOWN, DISABLED, OPPORTUNISTIC, ENABLED, REQUIRED }
diff --git a/common/src/main/java/org/conscrypt/EchOptions.java b/common/src/main/java/org/conscrypt/EchOptions.java
new file mode 100644
index 000000000..3715a4819
--- /dev/null
+++ b/common/src/main/java/org/conscrypt/EchOptions.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.conscrypt;
+
+@Internal
+class EchOptions {
+ private final byte[] configList;
+ private final boolean enableGrease;
+
+ EchOptions(byte[] configList, boolean enableGrease) {
+ this.configList = configList;
+ this.enableGrease = enableGrease;
+ }
+
+ byte[] getConfigList() {
+ return configList;
+ }
+
+ boolean isGreaseEnabled() {
+ return enableGrease;
+ }
+}
diff --git a/common/src/main/java/org/conscrypt/HpkeImpl.java b/common/src/main/java/org/conscrypt/HpkeImpl.java
index ac50d1804..ff5b863be 100644
--- a/common/src/main/java/org/conscrypt/HpkeImpl.java
+++ b/common/src/main/java/org/conscrypt/HpkeImpl.java
@@ -50,7 +50,7 @@ public HpkeImpl(HpkeSuite hpkeSuite) {
@Override
public void engineInitSender(PublicKey recipientKey, byte[] info, PrivateKey senderKey,
- byte[] psk, byte[] psk_id) throws InvalidKeyException {
+ byte[] psk, byte[] psk_id) throws InvalidKeyException {
checkNotInitialised();
checkArgumentsForBaseModeOnly(senderKey, psk, psk_id);
if (recipientKey == null) {
@@ -65,8 +65,8 @@ public void engineInitSender(PublicKey recipientKey, byte[] info, PrivateKey sen
@Override
public void engineInitSenderForTesting(PublicKey recipientKey, byte[] info,
- PrivateKey senderKey, byte[] psk, byte[] psk_id, byte[] sKe)
- throws InvalidKeyException {
+ PrivateKey senderKey, byte[] psk, byte[] psk_id,
+ byte[] sKe) throws InvalidKeyException {
checkNotInitialised();
Objects.requireNonNull(sKe);
checkArgumentsForBaseModeOnly(senderKey, psk, psk_id);
@@ -85,7 +85,8 @@ public void engineInitSenderForTesting(PublicKey recipientKey, byte[] info,
@Override
public void engineInitRecipient(byte[] encapsulated, PrivateKey recipientKey, byte[] info,
- PublicKey senderKey, byte[] psk, byte[] psk_id) throws InvalidKeyException {
+ PublicKey senderKey, byte[] psk, byte[] psk_id)
+ throws InvalidKeyException {
checkNotInitialised();
checkArgumentsForBaseModeOnly(senderKey, psk, psk_id);
Preconditions.checkNotNull(encapsulated, "null encapsulated data");
@@ -125,8 +126,8 @@ public byte[] engineExport(int length, byte[] exporterContext) {
checkInitialised();
long maxLength = hpkeSuite.getKdf().maxExportLength();
if (length < 0 || length > maxLength) {
- throw new IllegalArgumentException(
- "Export length must be between 0 and " + maxLength + ", but was " + length);
+ throw new IllegalArgumentException("Export length must be between 0 and " + maxLength
+ + ", but was " + length);
}
return NativeCrypto.EVP_HPKE_CTX_export(ctx, exporterContext, length);
}
@@ -182,8 +183,8 @@ private HpkeX25519Impl(HpkeSuite hpkeSuite) {
@Override
byte[] getRecipientPublicKeyBytes(PublicKey recipientKey) throws InvalidKeyException {
if (!(recipientKey instanceof OpenSSLX25519PublicKey)) {
- throw new InvalidKeyException(
- "Unsupported recipient key class: " + recipientKey.getClass());
+ throw new InvalidKeyException("Unsupported recipient key class: "
+ + recipientKey.getClass());
}
return ((OpenSSLX25519PublicKey) recipientKey).getU();
}
@@ -191,8 +192,8 @@ byte[] getRecipientPublicKeyBytes(PublicKey recipientKey) throws InvalidKeyExcep
@Override
byte[] getPrivateRecipientKeyBytes(PrivateKey recipientKey) throws InvalidKeyException {
if (!(recipientKey instanceof OpenSSLX25519PrivateKey)) {
- throw new InvalidKeyException(
- "Unsupported recipient private key class: " + recipientKey.getClass());
+ throw new InvalidKeyException("Unsupported recipient private key class: "
+ + recipientKey.getClass());
}
return ((OpenSSLX25519PrivateKey) recipientKey).getU();
}
@@ -215,13 +216,11 @@ public X25519_AES_256() {
/** Implementation of X25519/HKDF_SHA256/CHACHA20_POLY1305. */
public static class X25519_CHACHA20 extends HpkeX25519Impl {
public X25519_CHACHA20() {
- super(new HpkeSuite(
- KEM_DHKEM_X25519_HKDF_SHA256, KDF_HKDF_SHA256, AEAD_CHACHA20POLY1305));
+ super(new HpkeSuite(KEM_DHKEM_X25519_HKDF_SHA256, KDF_HKDF_SHA256,
+ AEAD_CHACHA20POLY1305));
}
}
- private static final OpenSslXwingKeyFactory xwingKeyFactory = new OpenSslXwingKeyFactory();
-
private static class HpkeXwingImpl extends HpkeImpl {
HpkeXwingImpl(HpkeSuite hpkeSuite) {
super(hpkeSuite);
@@ -229,20 +228,20 @@ private static class HpkeXwingImpl extends HpkeImpl {
@Override
byte[] getRecipientPublicKeyBytes(PublicKey publicKey) throws InvalidKeyException {
- Key translatedKey = xwingKeyFactory.engineTranslateKey(publicKey);
- if (!(translatedKey instanceof OpenSslXwingPublicKey)) {
- throw new IllegalStateException("Unexpected public key class");
+ if (!(publicKey instanceof OpenSslXwingPublicKey)) {
+ throw new InvalidKeyException("Unsupported recipient key class: "
+ + publicKey.getClass());
}
- return ((OpenSslXwingPublicKey) translatedKey).getRaw();
+ return ((OpenSslXwingPublicKey) publicKey).getRaw();
}
@Override
byte[] getPrivateRecipientKeyBytes(PrivateKey recipientKey) throws InvalidKeyException {
- Key translatedKey = xwingKeyFactory.engineTranslateKey(recipientKey);
- if (!(translatedKey instanceof OpenSslXwingPrivateKey)) {
- throw new IllegalStateException("Unexpected private key class");
+ if (!(recipientKey instanceof OpenSslXwingPrivateKey)) {
+ throw new InvalidKeyException("Unsupported recipient private key class: "
+ + recipientKey.getClass());
}
- return ((OpenSslXwingPrivateKey) translatedKey).getRaw();
+ return ((OpenSslXwingPrivateKey) recipientKey).getRaw();
}
}
diff --git a/common/src/main/java/org/conscrypt/Java8EngineWrapper.java b/common/src/main/java/org/conscrypt/Java8EngineWrapper.java
index 5cf135d4f..c6a0b7d38 100644
--- a/common/src/main/java/org/conscrypt/Java8EngineWrapper.java
+++ b/common/src/main/java/org/conscrypt/Java8EngineWrapper.java
@@ -22,6 +22,7 @@
import java.security.PrivateKey;
import java.util.List;
import java.util.function.BiFunction;
+
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
@@ -254,7 +255,7 @@ SSLEngineResult unwrap(ByteBuffer[] srcs, ByteBuffer[] dsts) throws SSLException
@Override
SSLEngineResult unwrap(ByteBuffer[] srcs, int srcsOffset, int srcsLength, ByteBuffer[] dsts,
- int dstsOffset, int dstsLength) throws SSLException {
+ int dstsOffset, int dstsLength) throws SSLException {
return delegate.unwrap(srcs, srcsOffset, srcsLength, dsts, dstsOffset, dstsLength);
}
@@ -274,6 +275,11 @@ void setUseSessionTickets(boolean useSessionTickets) {
delegate.setUseSessionTickets(useSessionTickets);
}
+ @Override
+ void setEchConfigList(byte[] echConfigList) {
+ delegate.setEchConfigList(echConfigList);
+ }
+
@Override
void setApplicationProtocols(String[] protocols) {
delegate.setApplicationProtocols(protocols);
diff --git a/common/src/main/java/org/conscrypt/NativeCrypto.java b/common/src/main/java/org/conscrypt/NativeCrypto.java
index 9269ba708..d4fe34101 100644
--- a/common/src/main/java/org/conscrypt/NativeCrypto.java
+++ b/common/src/main/java/org/conscrypt/NativeCrypto.java
@@ -18,6 +18,8 @@
import org.conscrypt.OpenSSLX509CertificateFactory.ParsingException;
+// android-add: import dalvik.annotation.optimization.CriticalNative;
+// android-add: import dalvik.annotation.optimization.FastNative;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.OutputStream;
@@ -61,6 +63,7 @@
public final class NativeCrypto {
// --- OpenSSL library initialization --------------------------------------
private static final UnsatisfiedLinkError loadError;
+
static {
UnsatisfiedLinkError error = null;
try {
@@ -75,8 +78,8 @@ public final class NativeCrypto {
}
/**
- * Checks to see whether or not the native library was successfully loaded. If not, throws
- * the {@link UnsatisfiedLinkError} that was encountered while attempting to load the library.
+ * Checks to see whether or not the native library was successfully loaded. If not, throws the
+ * {@link UnsatisfiedLinkError} that was encountered while attempting to load the library.
*/
static void checkAvailability() {
if (loadError != null) {
@@ -86,23 +89,32 @@ static void checkAvailability() {
// --- DSA/RSA public/private key handling functions -----------------------
+ // android-add: @FastNative
static native long EVP_PKEY_new_RSA(byte[] n, byte[] e, byte[] d, byte[] p, byte[] q,
- byte[] dmp1, byte[] dmq1, byte[] iqmp);
+ byte[] dmp1, byte[] dmq1, byte[] iqmp);
+ // android-add: @FastNative
static native int EVP_PKEY_type(NativeRef.EVP_PKEY pkey);
+ // android-add: @FastNative
static native String EVP_PKEY_print_public(NativeRef.EVP_PKEY pkeyRef);
+ // android-add: @FastNative
static native String EVP_PKEY_print_params(NativeRef.EVP_PKEY pkeyRef);
+ // android-add: @FastNative
static native void EVP_PKEY_free(long pkey);
+ // android-add: @FastNative
static native int EVP_PKEY_cmp(NativeRef.EVP_PKEY pkey1, NativeRef.EVP_PKEY pkey2);
+ // android-add: @FastNative
static native byte[] EVP_marshal_private_key(NativeRef.EVP_PKEY pkey);
+ // android-add: @FastNative
static native long EVP_parse_private_key(byte[] data) throws ParsingException;
+ // android-add: @FastNative
static native byte[] EVP_marshal_public_key(NativeRef.EVP_PKEY pkey);
static native long EVP_PKEY_from_private_key_info(byte[] data, int[] algs)
@@ -123,43 +135,58 @@ static native long EVP_PKEY_from_subject_public_key_info(byte[] data, int[] algs
static native byte[] EVP_PKEY_get_private_seed(NativeRef.EVP_PKEY pkey);
+ // android-add: @FastNative
static native byte[] EVP_raw_X25519_private_key(byte[] data)
throws ParsingException, InvalidKeyException;
+ // android-add: @FastNative
static native long EVP_parse_public_key(byte[] data) throws ParsingException;
+ // android-add: @FastNative
static native long PEM_read_bio_PUBKEY(long bioCtx);
+ // android-add: @FastNative
static native long PEM_read_bio_PrivateKey(long bioCtx);
+ // android-add: @FastNative
static native long getRSAPrivateKeyWrapper(PrivateKey key, byte[] modulus);
+ // android-add: @FastNative
static native long getECPrivateKeyWrapper(PrivateKey key, NativeRef.EC_GROUP ecGroupRef);
static native long RSA_generate_key_ex(int modulusBits, byte[] publicExponent);
+ // android-add: @FastNative
static native int RSA_size(NativeRef.EVP_PKEY pkey);
- static native int RSA_private_encrypt(
- int flen, byte[] from, byte[] to, NativeRef.EVP_PKEY pkey, int padding);
+ // android-add: @FastNative
+ static native int RSA_private_encrypt(int flen, byte[] from, byte[] to, NativeRef.EVP_PKEY pkey,
+ int padding);
+ // android-add: @FastNative
static native int RSA_public_decrypt(int flen, byte[] from, byte[] to, NativeRef.EVP_PKEY pkey,
- int padding) throws BadPaddingException, SignatureException;
+ int padding)
+ throws BadPaddingException, SignatureException;
- static native int RSA_public_encrypt(
- int flen, byte[] from, byte[] to, NativeRef.EVP_PKEY pkey, int padding);
+ // android-add: @FastNative
+ static native int RSA_public_encrypt(int flen, byte[] from, byte[] to, NativeRef.EVP_PKEY pkey,
+ int padding);
+ // android-add: @FastNative
static native int RSA_private_decrypt(int flen, byte[] from, byte[] to, NativeRef.EVP_PKEY pkey,
- int padding) throws BadPaddingException, SignatureException;
+ int padding)
+ throws BadPaddingException, SignatureException;
/*
* Returns array of {n, e}
*/
+ // android-add: @FastNative
static native byte[][] get_RSA_public_params(NativeRef.EVP_PKEY rsa);
/*
* Returns array of {n, e, d, p, q, dmp1, dmq1, iqmp}
*/
+ // android-add: @FastNative
static native byte[][] get_RSA_private_params(NativeRef.EVP_PKEY rsa);
// --- ChaCha20 -----------------------
@@ -167,88 +194,122 @@ static native int RSA_private_decrypt(int flen, byte[] from, byte[] to, NativeRe
/*
* Returns the encrypted or decrypted version of the data.
*/
+ // android-add: @FastNative
static native void chacha20_encrypt_decrypt(byte[] in, int inOffset, byte[] out, int outOffset,
- int length, byte[] key, byte[] nonce, int blockCounter);
+ int length, byte[] key, byte[] nonce,
+ int blockCounter);
// --- EC functions --------------------------
- static native long EVP_PKEY_new_EC_KEY(
- NativeRef.EC_GROUP groupRef, NativeRef.EC_POINT pubkeyRef, byte[] privkey);
+ // android-add: @FastNative
+ static native long EVP_PKEY_new_EC_KEY(NativeRef.EC_GROUP groupRef,
+ NativeRef.EC_POINT pubkeyRef, byte[] privkey);
+ // android-add: @FastNative
static native long EC_GROUP_new_by_curve_name(String curveName);
- static native long EC_GROUP_new_arbitrary(
- byte[] p, byte[] a, byte[] b, byte[] x, byte[] y, byte[] order, int cofactor);
+ // android-add: @FastNative
+ static native long EC_GROUP_new_arbitrary(byte[] p, byte[] a, byte[] b, byte[] x, byte[] y,
+ byte[] order, int cofactor);
+ // android-add: @FastNative
static native String EC_GROUP_get_curve_name(NativeRef.EC_GROUP groupRef);
+ // android-add: @FastNative
static native byte[][] EC_GROUP_get_curve(NativeRef.EC_GROUP groupRef);
+ // android-add: @FastNative
static native void EC_GROUP_clear_free(long groupRef);
+ // android-add: @FastNative
static native long EC_GROUP_get_generator(NativeRef.EC_GROUP groupRef);
+ // android-add: @FastNative
static native byte[] EC_GROUP_get_order(NativeRef.EC_GROUP groupRef);
+ // android-add: @FastNative
static native int EC_GROUP_get_degree(NativeRef.EC_GROUP groupRef);
+ // android-add: @FastNative
static native byte[] EC_GROUP_get_cofactor(NativeRef.EC_GROUP groupRef);
+ // android-add: @FastNative
static native long EC_POINT_new(NativeRef.EC_GROUP groupRef);
+ // android-add: @FastNative
static native void EC_POINT_clear_free(long pointRef);
- static native byte[][] EC_POINT_get_affine_coordinates(
- NativeRef.EC_GROUP groupRef, NativeRef.EC_POINT pointRef);
+ // android-add: @FastNative
+ static native byte[][] EC_POINT_get_affine_coordinates(NativeRef.EC_GROUP groupRef,
+ NativeRef.EC_POINT pointRef);
- static native void EC_POINT_set_affine_coordinates(
- NativeRef.EC_GROUP groupRef, NativeRef.EC_POINT pointRef, byte[] x, byte[] y);
+ // android-add: @FastNative
+ static native void EC_POINT_set_affine_coordinates(NativeRef.EC_GROUP groupRef,
+ NativeRef.EC_POINT pointRef, byte[] x,
+ byte[] y);
static native long EC_KEY_generate_key(NativeRef.EC_GROUP groupRef);
+ // android-add: @FastNative
static native long EC_KEY_get1_group(NativeRef.EVP_PKEY pkeyRef);
+ // android-add: @FastNative
static native byte[] EC_KEY_get_private_key(NativeRef.EVP_PKEY keyRef);
+ // android-add: @FastNative
static native long EC_KEY_get_public_key(NativeRef.EVP_PKEY keyRef);
+ // android-add: @FastNative
static native byte[] EC_KEY_marshal_curve_name(NativeRef.EC_GROUP groupRef) throws IOException;
+ // android-add: @FastNative
static native long EC_KEY_parse_curve_name(byte[] encoded) throws IOException;
+ // android-add: @FastNative
static native int ECDH_compute_key(byte[] out, int outOffset, NativeRef.EVP_PKEY publicKeyRef,
- NativeRef.EVP_PKEY privateKeyRef) throws InvalidKeyException, IndexOutOfBoundsException;
+ NativeRef.EVP_PKEY privateKeyRef)
+ throws InvalidKeyException, IndexOutOfBoundsException;
+ // android-add: @FastNative
static native int ECDSA_size(NativeRef.EVP_PKEY pkey);
+ // android-add: @FastNative
static native int ECDSA_sign(byte[] data, int dataLen, byte[] sig, NativeRef.EVP_PKEY pkey);
+ // android-add: @FastNative
static native int ECDSA_verify(byte[] data, int dataLen, byte[] sig, NativeRef.EVP_PKEY pkey);
// --- MLDSA65 --------------------------------------------------------------
+ // android-add: @FastNative
static native byte[] MLDSA65_public_key_from_seed(byte[] privateKeySeed);
// --- MLDSA87 --------------------------------------------------------------
+ // android-add: @FastNative
static native byte[] MLDSA87_public_key_from_seed(byte[] privateKeySeed);
// --- SLHDSA_SHA2_128S --------------------------------------------------------------
static native void SLHDSA_SHA2_128S_generate_key(byte[] outPublicKey, byte[] outPrivateKey);
+ // android-add: @FastNative
static native byte[] SLHDSA_SHA2_128S_sign(byte[] data, int dataLen, byte[] privateKey);
- static native int SLHDSA_SHA2_128S_verify(
- byte[] data, int dataLen, byte[] sig, byte[] publicKey);
+ // android-add: @FastNative
+ static native int SLHDSA_SHA2_128S_verify(byte[] data, int dataLen, byte[] sig,
+ byte[] publicKey);
// --- Curve25519 --------------
+ // android-add: @FastNative
static native boolean X25519(byte[] out, byte[] privateKey, byte[] publicKey)
throws InvalidKeyException;
+ // android-add: @FastNative
static native void X25519_keypair(byte[] outPublicKey, byte[] outPrivateKey);
+ // android-add: @FastNative
static native void ED25519_keypair(byte[] outPublicKey, byte[] outPrivateKey);
// --- X-Wing --------------
@@ -258,224 +319,311 @@ static native boolean X25519(byte[] out, byte[] privateKey, byte[] publicKey)
// --- Message digest functions --------------
// These return const references
+ // android-add: @FastNative
static native long EVP_get_digestbyname(String name);
+ // android-add: @FastNative
static native int EVP_MD_size(long evp_md_const);
// --- Message digest context functions --------------
+ // android-add: @FastNative
static native long EVP_MD_CTX_create();
+ // android-add: @FastNative
static native void EVP_MD_CTX_cleanup(NativeRef.EVP_MD_CTX ctx);
+ // android-add: @FastNative
static native void EVP_MD_CTX_destroy(long ctx);
- static native int EVP_MD_CTX_copy_ex(
- NativeRef.EVP_MD_CTX dst_ctx, NativeRef.EVP_MD_CTX src_ctx);
+ // android-add: @FastNative
+ static native int EVP_MD_CTX_copy_ex(NativeRef.EVP_MD_CTX dst_ctx,
+ NativeRef.EVP_MD_CTX src_ctx);
// --- Digest handling functions -------------------------------------------
+ // android-add: @FastNative
static native int EVP_DigestInit_ex(NativeRef.EVP_MD_CTX ctx, long evp_md);
- static native void EVP_DigestUpdate(
- NativeRef.EVP_MD_CTX ctx, byte[] buffer, int offset, int length);
+ // android-add: @FastNative
+ static native void EVP_DigestUpdate(NativeRef.EVP_MD_CTX ctx, byte[] buffer, int offset,
+ int length);
+ // android-add: @FastNative
static native void EVP_DigestUpdateDirect(NativeRef.EVP_MD_CTX ctx, long ptr, int length);
+ // android-add: @FastNative
static native int EVP_DigestFinal_ex(NativeRef.EVP_MD_CTX ctx, byte[] hash, int offset);
// --- Signature handling functions ----------------------------------------
- static native long EVP_DigestSignInit(
- NativeRef.EVP_MD_CTX ctx, long evpMdRef, NativeRef.EVP_PKEY key);
+ // android-add: @FastNative
+ static native long EVP_DigestSignInit(NativeRef.EVP_MD_CTX ctx, long evpMdRef,
+ NativeRef.EVP_PKEY key);
- static native long EVP_DigestVerifyInit(
- NativeRef.EVP_MD_CTX ctx, long evpMdRef, NativeRef.EVP_PKEY key);
+ // android-add: @FastNative
+ static native long EVP_DigestVerifyInit(NativeRef.EVP_MD_CTX ctx, long evpMdRef,
+ NativeRef.EVP_PKEY key);
- static native void EVP_DigestSignUpdate(
- NativeRef.EVP_MD_CTX ctx, byte[] buffer, int offset, int length);
+ // android-add: @FastNative
+ static native void EVP_DigestSignUpdate(NativeRef.EVP_MD_CTX ctx, byte[] buffer, int offset,
+ int length);
+ // android-add: @FastNative
static native void EVP_DigestSignUpdateDirect(NativeRef.EVP_MD_CTX ctx, long ptr, int length);
- static native void EVP_DigestVerifyUpdate(
- NativeRef.EVP_MD_CTX ctx, byte[] buffer, int offset, int length);
+ // android-add: @FastNative
+ static native void EVP_DigestVerifyUpdate(NativeRef.EVP_MD_CTX ctx, byte[] buffer, int offset,
+ int length);
+ // android-add: @FastNative
static native void EVP_DigestVerifyUpdateDirect(NativeRef.EVP_MD_CTX ctx, long ptr, int length);
+ // android-add: @FastNative
static native byte[] EVP_DigestSignFinal(NativeRef.EVP_MD_CTX ctx);
+ // android-add: @FastNative
static native boolean EVP_DigestVerifyFinal(NativeRef.EVP_MD_CTX ctx, byte[] signature,
- int offset, int length) throws IndexOutOfBoundsException;
+ int offset, int length)
+ throws IndexOutOfBoundsException;
- static native byte[] EVP_DigestSign(
- NativeRef.EVP_MD_CTX ctx, byte[] buffer, int offset, int length);
+ // android-add: @FastNative
+ static native byte[] EVP_DigestSign(NativeRef.EVP_MD_CTX ctx, byte[] buffer, int offset,
+ int length);
+ // android-add: @FastNative
static native boolean EVP_DigestVerify(NativeRef.EVP_MD_CTX ctx, byte[] sigBuffer,
- int sigOffset, int sigLen, byte[] dataBuffer, int dataOffset, int dataLen);
+ int sigOffset, int sigLen, byte[] dataBuffer,
+ int dataOffset, int dataLen);
+ // android-add: @FastNative
static native long EVP_PKEY_encrypt_init(NativeRef.EVP_PKEY pkey) throws InvalidKeyException;
+ // android-add: @FastNative
static native int EVP_PKEY_encrypt(NativeRef.EVP_PKEY_CTX ctx, byte[] out, int outOffset,
- byte[] input, int inOffset, int inLength)
+ byte[] input, int inOffset, int inLength)
throws IndexOutOfBoundsException, BadPaddingException;
+ // android-add: @FastNative
static native long EVP_PKEY_decrypt_init(NativeRef.EVP_PKEY pkey) throws InvalidKeyException;
+ // android-add: @FastNative
static native int EVP_PKEY_decrypt(NativeRef.EVP_PKEY_CTX ctx, byte[] out, int outOffset,
- byte[] input, int inOffset, int inLength)
+ byte[] input, int inOffset, int inLength)
throws IndexOutOfBoundsException, BadPaddingException;
+ // android-add: @FastNative
static native void EVP_PKEY_CTX_free(long pkeyCtx);
+ // android-add: @FastNative
static native void EVP_PKEY_CTX_set_rsa_padding(long ctx, int pad)
throws InvalidAlgorithmParameterException;
+ // android-add: @FastNative
static native void EVP_PKEY_CTX_set_rsa_pss_saltlen(long ctx, int len)
throws InvalidAlgorithmParameterException;
+ // android-add: @FastNative
static native void EVP_PKEY_CTX_set_rsa_mgf1_md(long ctx, long evpMdRef)
throws InvalidAlgorithmParameterException;
+ // android-add: @FastNative
static native void EVP_PKEY_CTX_set_rsa_oaep_md(long ctx, long evpMdRef)
throws InvalidAlgorithmParameterException;
+ // android-add: @FastNative
static native void EVP_PKEY_CTX_set_rsa_oaep_label(long ctx, byte[] label)
throws InvalidAlgorithmParameterException;
// --- Block ciphers -------------------------------------------------------
// These return const references
+ // android-add: @FastNative
static native long EVP_get_cipherbyname(String string);
+ // android-add: @FastNative
static native void EVP_CipherInit_ex(NativeRef.EVP_CIPHER_CTX ctx, long evpCipher, byte[] key,
- byte[] iv, boolean encrypting);
+ byte[] iv, boolean encrypting);
+ // android-add: @FastNative
static native int EVP_CipherUpdate(NativeRef.EVP_CIPHER_CTX ctx, byte[] out, int outOffset,
- byte[] in, int inOffset, int inLength) throws IndexOutOfBoundsException;
+ byte[] in, int inOffset, int inLength)
+ throws IndexOutOfBoundsException;
+ // android-add: @FastNative
static native int EVP_CipherFinal_ex(NativeRef.EVP_CIPHER_CTX ctx, byte[] out, int outOffset)
throws BadPaddingException, IllegalBlockSizeException;
+ // android-add: @FastNative
static native int EVP_CIPHER_iv_length(long evpCipher);
+ // android-add: @FastNative
static native long EVP_CIPHER_CTX_new();
+ // android-add: @FastNative
static native int EVP_CIPHER_CTX_block_size(NativeRef.EVP_CIPHER_CTX ctx);
+ // android-add: @FastNative
static native int get_EVP_CIPHER_CTX_buf_len(NativeRef.EVP_CIPHER_CTX ctx);
+ // android-add: @FastNative
static native boolean get_EVP_CIPHER_CTX_final_used(NativeRef.EVP_CIPHER_CTX ctx);
- static native void EVP_CIPHER_CTX_set_padding(
- NativeRef.EVP_CIPHER_CTX ctx, boolean enablePadding);
+ // android-add: @FastNative
+ static native void EVP_CIPHER_CTX_set_padding(NativeRef.EVP_CIPHER_CTX ctx,
+ boolean enablePadding);
+ // android-add: @FastNative
static native void EVP_CIPHER_CTX_set_key_length(NativeRef.EVP_CIPHER_CTX ctx, int keyBitSize);
+ // android-add: @FastNative
static native void EVP_CIPHER_CTX_free(long ctx);
// --- AEAD ----------------------------------------------------------------
+ // android-add: @FastNative
static native long EVP_aead_aes_128_gcm();
+ // android-add: @FastNative
static native long EVP_aead_aes_256_gcm();
+ // android-add: @FastNative
static native long EVP_aead_chacha20_poly1305();
+ // android-add: @FastNative
static native long EVP_aead_aes_128_gcm_siv();
+ // android-add: @FastNative
static native long EVP_aead_aes_256_gcm_siv();
+ // android-add: @FastNative
static native int EVP_AEAD_max_overhead(long evpAead);
+ // android-add: @FastNative
static native int EVP_AEAD_nonce_length(long evpAead);
+ // android-add: @FastNative
static native int EVP_AEAD_CTX_seal(long evpAead, byte[] key, int tagLengthInBytes, byte[] out,
- int outOffset, byte[] nonce, byte[] in, int inOffset, int inLength, byte[] ad)
+ int outOffset, byte[] nonce, byte[] in, int inOffset,
+ int inLength, byte[] ad)
throws ShortBufferException, BadPaddingException;
+ // android-add: @FastNative
static native int EVP_AEAD_CTX_seal_buf(long evpAead, byte[] key, int tagLengthInBytes,
- ByteBuffer out, byte[] nonce, ByteBuffer input, byte[] ad)
+ ByteBuffer out, byte[] nonce, ByteBuffer input,
+ byte[] ad)
throws ShortBufferException, BadPaddingException;
+ // android-add: @FastNative
static native int EVP_AEAD_CTX_open(long evpAead, byte[] key, int tagLengthInBytes, byte[] out,
- int outOffset, byte[] nonce, byte[] in, int inOffset, int inLength, byte[] ad)
+ int outOffset, byte[] nonce, byte[] in, int inOffset,
+ int inLength, byte[] ad)
throws ShortBufferException, BadPaddingException;
+ // android-add: @FastNative
static native int EVP_AEAD_CTX_open_buf(long evpAead, byte[] key, int tagLengthInBytes,
- ByteBuffer out, byte[] nonce, ByteBuffer input, byte[] ad)
+ ByteBuffer out, byte[] nonce, ByteBuffer input,
+ byte[] ad)
throws ShortBufferException, BadPaddingException;
// --- CMAC functions ------------------------------------------------------
+ // android-add: @FastNative
static native long CMAC_CTX_new();
+ // android-add: @FastNative
static native void CMAC_CTX_free(long ctx);
+ // android-add: @FastNative
static native void CMAC_Init(NativeRef.CMAC_CTX ctx, byte[] key);
+ // android-add: @FastNative
static native void CMAC_Update(NativeRef.CMAC_CTX ctx, byte[] in, int inOffset, int inLength);
+ // android-add: @FastNative
static native void CMAC_UpdateDirect(NativeRef.CMAC_CTX ctx, long inPtr, int inLength);
+ // android-add: @FastNative
static native byte[] CMAC_Final(NativeRef.CMAC_CTX ctx);
+ // android-add: @FastNative
static native void CMAC_Reset(NativeRef.CMAC_CTX ctx);
// --- HMAC functions ------------------------------------------------------
+ // android-add: @FastNative
static native long HMAC_CTX_new();
+ // android-add: @FastNative
static native void HMAC_CTX_free(long ctx);
+ // android-add: @FastNative
static native void HMAC_Init_ex(NativeRef.HMAC_CTX ctx, byte[] key, long evp_md);
+ // android-add: @FastNative
static native void HMAC_Update(NativeRef.HMAC_CTX ctx, byte[] in, int inOffset, int inLength);
+ // android-add: @FastNative
static native void HMAC_UpdateDirect(NativeRef.HMAC_CTX ctx, long inPtr, int inLength);
+ // android-add: @FastNative
static native byte[] HMAC_Final(NativeRef.HMAC_CTX ctx);
+ // android-add: @FastNative
static native void HMAC_Reset(NativeRef.HMAC_CTX ctx);
// --- HPKE functions ------------------------------------------------------
- static native byte[] EVP_HPKE_CTX_export(
- NativeRef.EVP_HPKE_CTX ctx, byte[] exporterCtx, int length);
+ // android-add: @FastNative
+ static native byte[] EVP_HPKE_CTX_export(NativeRef.EVP_HPKE_CTX ctx, byte[] exporterCtx,
+ int length);
static native void EVP_HPKE_CTX_free(long ctx);
- static native byte[] EVP_HPKE_CTX_open(
- NativeRef.EVP_HPKE_CTX ctx, byte[] ciphertext, byte[] aad) throws BadPaddingException;
+ // android-add: @FastNative
+ static native byte[] EVP_HPKE_CTX_open(NativeRef.EVP_HPKE_CTX ctx, byte[] ciphertext,
+ byte[] aad) throws BadPaddingException;
- static native byte[] EVP_HPKE_CTX_seal(
- NativeRef.EVP_HPKE_CTX ctx, byte[] plaintext, byte[] aad);
+ // android-add: @FastNative
+ static native byte[] EVP_HPKE_CTX_seal(NativeRef.EVP_HPKE_CTX ctx, byte[] plaintext,
+ byte[] aad);
- static native Object EVP_HPKE_CTX_setup_base_mode_recipient(
- int kem, int kdf, int aead, byte[] privateKey, byte[] enc, byte[] info);
+ // android-add: @FastNative
+ static native Object EVP_HPKE_CTX_setup_base_mode_recipient(int kem, int kdf, int aead,
+ byte[] privateKey, byte[] enc,
+ byte[] info);
- static Object EVP_HPKE_CTX_setup_base_mode_recipient(
- HpkeSuite suite, byte[] privateKey, byte[] enc, byte[] info) {
- return EVP_HPKE_CTX_setup_base_mode_recipient(suite.getKem().getId(),
- suite.getKdf().getId(), suite.getAead().getId(), privateKey, enc, info);
+ static Object EVP_HPKE_CTX_setup_base_mode_recipient(HpkeSuite suite, byte[] privateKey,
+ byte[] enc, byte[] info) {
+ return EVP_HPKE_CTX_setup_base_mode_recipient(
+ suite.getKem().getId(), suite.getKdf().getId(), suite.getAead().getId(), privateKey,
+ enc, info);
}
- static native Object[] EVP_HPKE_CTX_setup_base_mode_sender(
- int kem, int kdf, int aead, byte[] publicKey, byte[] info);
+ // android-add: @FastNative
+ static native Object[] EVP_HPKE_CTX_setup_base_mode_sender(int kem, int kdf, int aead,
+ byte[] publicKey, byte[] info);
- static Object[] EVP_HPKE_CTX_setup_base_mode_sender(
- HpkeSuite suite, byte[] publicKey, byte[] info) {
+ static Object[] EVP_HPKE_CTX_setup_base_mode_sender(HpkeSuite suite, byte[] publicKey,
+ byte[] info) {
return EVP_HPKE_CTX_setup_base_mode_sender(suite.getKem().getId(), suite.getKdf().getId(),
- suite.getAead().getId(), publicKey, info);
+ suite.getAead().getId(), publicKey, info);
}
+
+ // android-add: @FastNative
static native Object[] EVP_HPKE_CTX_setup_base_mode_sender_with_seed_for_testing(
int kem, int kdf, int aead, byte[] publicKey, byte[] info, byte[] seed);
- static Object[] EVP_HPKE_CTX_setup_base_mode_sender_with_seed_for_testing(
- HpkeSuite suite, byte[] publicKey, byte[] info, byte[] seed) {
- return EVP_HPKE_CTX_setup_base_mode_sender_with_seed_for_testing(suite.getKem().getId(),
- suite.getKdf().getId(), suite.getAead().getId(), publicKey, info, seed);
+ static Object[] EVP_HPKE_CTX_setup_base_mode_sender_with_seed_for_testing(HpkeSuite suite,
+ byte[] publicKey,
+ byte[] info,
+ byte[] seed) {
+ return EVP_HPKE_CTX_setup_base_mode_sender_with_seed_for_testing(
+ suite.getKem().getId(), suite.getKdf().getId(), suite.getAead().getId(), publicKey,
+ info, seed);
}
// --- RAND ----------------------------------------------------------------
+ // android-add: @FastNative
static native void RAND_bytes(byte[] output);
// --- X509_NAME -----------------------------------------------------------
@@ -487,6 +635,7 @@ static int X509_NAME_hash(X500Principal principal) {
public static int X509_NAME_hash_old(X500Principal principal) {
return X509_NAME_hash(principal, "MD5");
}
+
private static int X509_NAME_hash(X500Principal principal, String algorithm) {
try {
byte[] digest = MessageDigest.getInstance(algorithm).digest(principal.getEncoded());
@@ -503,102 +652,130 @@ private static int X509_NAME_hash(X500Principal principal, String algorithm) {
/** Used to request get_X509_GENERAL_NAME_stack get the "altname" field. */
static final int GN_STACK_SUBJECT_ALT_NAME = 1;
- /**
- * Used to request get_X509_GENERAL_NAME_stack get the issuerAlternativeName
- * extension.
- */
+ /** Used to request get_X509_GENERAL_NAME_stack get the issuerAlternativeName extension. */
static final int GN_STACK_ISSUER_ALT_NAME = 2;
- /**
- * Used to request only non-critical types in get_X509*_ext_oids.
- */
+ /** Used to request only non-critical types in get_X509*_ext_oids. */
static final int EXTENSION_TYPE_NON_CRITICAL = 0;
- /**
- * Used to request only critical types in get_X509*_ext_oids.
- */
+ /** Used to request only critical types in get_X509*_ext_oids. */
static final int EXTENSION_TYPE_CRITICAL = 1;
+ // android-add: @FastNative
static native long d2i_X509_bio(long bioCtx);
+ // android-add: @FastNative
static native long d2i_X509(byte[] encoded) throws ParsingException;
+ // android-add: @FastNative
static native long PEM_read_bio_X509(long bioCtx);
+ // android-add: @FastNative
static native byte[] i2d_X509(long x509ctx, OpenSSLX509Certificate holder);
/** Takes an X509 context not an X509_PUBKEY context. */
+ // android-add: @FastNative
static native byte[] i2d_X509_PUBKEY(long x509ctx, OpenSSLX509Certificate holder);
+ // android-add: @FastNative
static native byte[] ASN1_seq_pack_X509(long[] x509CertRefs);
+ // android-add: @FastNative
static native long[] ASN1_seq_unpack_X509_bio(long bioRef) throws ParsingException;
static native void X509_free(long x509ctx, OpenSSLX509Certificate holder);
+ // android-add: @FastNative
static native int X509_cmp(long x509ctx1, OpenSSLX509Certificate holder, long x509ctx2,
- OpenSSLX509Certificate holder2);
+ OpenSSLX509Certificate holder2);
- static native void X509_print_ex(
- long bioCtx, long x509ctx, OpenSSLX509Certificate holder, long nmflag, long certflag);
+ // android-add: @FastNative
+ static native void X509_print_ex(long bioCtx, long x509ctx, OpenSSLX509Certificate holder,
+ long nmflag, long certflag);
+ // android-add: @FastNative
static native byte[] X509_get_issuer_name(long x509ctx, OpenSSLX509Certificate holder);
+ // android-add: @FastNative
static native byte[] X509_get_subject_name(long x509ctx, OpenSSLX509Certificate holder);
+ // android-add: @FastNative
static native String get_X509_sig_alg_oid(long x509ctx, OpenSSLX509Certificate holder);
+ // android-add: @FastNative
static native byte[] get_X509_sig_alg_parameter(long x509ctx, OpenSSLX509Certificate holder);
+ // android-add: @FastNative
static native boolean[] get_X509_issuerUID(long x509ctx, OpenSSLX509Certificate holder);
+ // android-add: @FastNative
static native boolean[] get_X509_subjectUID(long x509ctx, OpenSSLX509Certificate holder);
+ // android-add: @FastNative
static native long X509_get_pubkey(long x509ctx, OpenSSLX509Certificate holder)
throws NoSuchAlgorithmException, InvalidKeyException;
+ // android-add: @FastNative
static native String get_X509_pubkey_oid(long x509ctx, OpenSSLX509Certificate holder);
+ // android-add: @FastNative
static native byte[] X509_get_ext_oid(long x509ctx, OpenSSLX509Certificate holder, String oid);
- static native String[] get_X509_ext_oids(
- long x509ctx, OpenSSLX509Certificate holder, int critical);
+ // android-add: @FastNative
+ static native String[] get_X509_ext_oids(long x509ctx, OpenSSLX509Certificate holder,
+ int critical);
+ // android-add: @FastNative
static native Object[][] get_X509_GENERAL_NAME_stack(long x509ctx,
- OpenSSLX509Certificate holder, int type) throws CertificateParsingException;
+ OpenSSLX509Certificate holder, int type)
+ throws CertificateParsingException;
+ // android-add: @FastNative
static native boolean[] get_X509_ex_kusage(long x509ctx, OpenSSLX509Certificate holder);
+ // android-add: @FastNative
static native String[] get_X509_ex_xkusage(long x509ctx, OpenSSLX509Certificate holder);
+ // android-add: @FastNative
static native int get_X509_ex_pathlen(long x509ctx, OpenSSLX509Certificate holder);
+ // android-add: @FastNative
static native long X509_get_notBefore(long x509ctx, OpenSSLX509Certificate holder)
throws ParsingException;
+ // android-add: @FastNative
static native long X509_get_notAfter(long x509ctx, OpenSSLX509Certificate holder)
throws ParsingException;
+ // android-add: @FastNative
static native long X509_get_version(long x509ctx, OpenSSLX509Certificate holder);
+ // android-add: @FastNative
static native byte[] X509_get_serialNumber(long x509ctx, OpenSSLX509Certificate holder);
+ // android-add: @FastNative
static native void X509_verify(long x509ctx, OpenSSLX509Certificate holder,
- NativeRef.EVP_PKEY pkeyCtx) throws BadPaddingException, IllegalBlockSizeException;
+ NativeRef.EVP_PKEY pkeyCtx)
+ throws BadPaddingException, IllegalBlockSizeException;
+ // android-add: @FastNative
static native byte[] get_X509_tbs_cert(long x509ctx, OpenSSLX509Certificate holder);
- static native byte[] get_X509_tbs_cert_without_ext(
- long x509ctx, OpenSSLX509Certificate holder, String oid);
+ // android-add: @FastNative
+ static native byte[] get_X509_tbs_cert_without_ext(long x509ctx, OpenSSLX509Certificate holder,
+ String oid);
+ // android-add: @FastNative
static native byte[] get_X509_signature(long x509ctx, OpenSSLX509Certificate holder);
+ // android-add: @FastNative
static native int get_X509_ex_flags(long x509ctx, OpenSSLX509Certificate holder);
// Used by Android platform TrustedCertificateStore.
@SuppressWarnings("unused")
- static native int X509_check_issued(
- long ctx, OpenSSLX509Certificate holder, long ctx2, OpenSSLX509Certificate holder2);
+ // android-add: @FastNative
+ static native int X509_check_issued(long ctx, OpenSSLX509Certificate holder, long ctx2,
+ OpenSSLX509Certificate holder2);
// --- PKCS7 ---------------------------------------------------------------
@@ -609,110 +786,148 @@ static native int X509_check_issued(
static final int PKCS7_CRLS = 2;
/** Returns an array of X509 or X509_CRL pointers. */
+ // android-add: @FastNative
static native long[] d2i_PKCS7_bio(long bioCtx, int which) throws ParsingException;
/** Returns an array of X509 or X509_CRL pointers. */
+ // android-add: @FastNative
static native byte[] i2d_PKCS7(long[] certs);
/** Returns an array of X509 or X509_CRL pointers. */
+ // android-add: @FastNative
static native long[] PEM_read_bio_PKCS7(long bioCtx, int which);
// --- X509_CRL ------------------------------------------------------------
+ // android-add: @FastNative
static native long d2i_X509_CRL_bio(long bioCtx);
+ // android-add: @FastNative
static native long PEM_read_bio_X509_CRL(long bioCtx);
+ // android-add: @FastNative
static native byte[] i2d_X509_CRL(long x509CrlCtx, OpenSSLX509CRL holder);
+ // android-add: @FastNative
static native void X509_CRL_free(long x509CrlCtx, OpenSSLX509CRL holder);
+ // android-add: @FastNative
static native void X509_CRL_print(long bioCtx, long x509CrlCtx, OpenSSLX509CRL holder);
+ // android-add: @FastNative
static native String get_X509_CRL_sig_alg_oid(long x509CrlCtx, OpenSSLX509CRL holder);
+ // android-add: @FastNative
static native byte[] get_X509_CRL_sig_alg_parameter(long x509CrlCtx, OpenSSLX509CRL holder);
+ // android-add: @FastNative
static native byte[] X509_CRL_get_issuer_name(long x509CrlCtx, OpenSSLX509CRL holder);
/** Returns X509_REVOKED reference that is not duplicated! */
- static native long X509_CRL_get0_by_cert(
- long x509CrlCtx, OpenSSLX509CRL holder, long x509Ctx, OpenSSLX509Certificate holder2);
+ // android-add: @FastNative
+ static native long X509_CRL_get0_by_cert(long x509CrlCtx, OpenSSLX509CRL holder, long x509Ctx,
+ OpenSSLX509Certificate holder2);
/** Returns X509_REVOKED reference that is not duplicated! */
- static native long X509_CRL_get0_by_serial(
- long x509CrlCtx, OpenSSLX509CRL holder, byte[] serial);
+ // android-add: @FastNative
+ static native long X509_CRL_get0_by_serial(long x509CrlCtx, OpenSSLX509CRL holder,
+ byte[] serial);
/** Returns an array of X509_REVOKED that are owned by the caller. */
+ // android-add: @FastNative
static native long[] X509_CRL_get_REVOKED(long x509CrlCtx, OpenSSLX509CRL holder);
- static native String[] get_X509_CRL_ext_oids(
- long x509Crlctx, OpenSSLX509CRL holder, int critical);
+ // android-add: @FastNative
+ static native String[] get_X509_CRL_ext_oids(long x509Crlctx, OpenSSLX509CRL holder,
+ int critical);
+ // android-add: @FastNative
static native byte[] X509_CRL_get_ext_oid(long x509CrlCtx, OpenSSLX509CRL holder, String oid);
+ // android-add: @FastNative
static native long X509_CRL_get_version(long x509CrlCtx, OpenSSLX509CRL holder);
+ // android-add: @FastNative
static native long X509_CRL_get_ext(long x509CrlCtx, OpenSSLX509CRL holder, String oid);
+ // android-add: @FastNative
static native byte[] get_X509_CRL_signature(long x509ctx, OpenSSLX509CRL holder);
+ // android-add: @FastNative
static native void X509_CRL_verify(long x509CrlCtx, OpenSSLX509CRL holder,
- NativeRef.EVP_PKEY pkeyCtx) throws BadPaddingException, SignatureException,
- NoSuchAlgorithmException, InvalidKeyException,
- IllegalBlockSizeException;
+ NativeRef.EVP_PKEY pkeyCtx)
+ throws BadPaddingException, SignatureException, NoSuchAlgorithmException,
+ InvalidKeyException, IllegalBlockSizeException;
+ // android-add: @FastNative
static native byte[] get_X509_CRL_crl_enc(long x509CrlCtx, OpenSSLX509CRL holder);
+ // android-add: @FastNative
static native long X509_CRL_get_lastUpdate(long x509CrlCtx, OpenSSLX509CRL holder)
throws ParsingException;
+ // android-add: @FastNative
static native long X509_CRL_get_nextUpdate(long x509CrlCtx, OpenSSLX509CRL holder)
throws ParsingException;
// --- X509_REVOKED --------------------------------------------------------
+ // android-add: @FastNative
static native long X509_REVOKED_dup(long x509RevokedCtx);
+ // android-add: @FastNative
static native byte[] i2d_X509_REVOKED(long x509RevokedCtx, OpenSSLX509CRLEntry holder);
- static native String[] get_X509_REVOKED_ext_oids(
- long x509ctx, int critical, OpenSSLX509CRLEntry holder);
+ // android-add: @FastNative
+ static native String[] get_X509_REVOKED_ext_oids(long x509ctx, int critical,
+ OpenSSLX509CRLEntry holder);
- static native byte[] X509_REVOKED_get_ext_oid(
- long x509RevokedCtx, String oid, OpenSSLX509CRLEntry holder);
+ // android-add: @FastNative
+ static native byte[] X509_REVOKED_get_ext_oid(long x509RevokedCtx, String oid,
+ OpenSSLX509CRLEntry holder);
- static native byte[] X509_REVOKED_get_serialNumber(
- long x509RevokedCtx, OpenSSLX509CRLEntry holder);
+ // android-add: @FastNative
+ static native byte[] X509_REVOKED_get_serialNumber(long x509RevokedCtx,
+ OpenSSLX509CRLEntry holder);
- static native long X509_REVOKED_get_ext(
- long x509RevokedCtx, String oid, OpenSSLX509CRLEntry holder);
+ // android-add: @FastNative
+ static native long X509_REVOKED_get_ext(long x509RevokedCtx, String oid,
+ OpenSSLX509CRLEntry holder);
/** Returns ASN1_TIME reference. */
- static native long get_X509_REVOKED_revocationDate(
- long x509RevokedCtx, OpenSSLX509CRLEntry holder);
+ // android-add: @FastNative
+ static native long get_X509_REVOKED_revocationDate(long x509RevokedCtx,
+ OpenSSLX509CRLEntry holder);
- static native void X509_REVOKED_print(
- long bioRef, long x509RevokedCtx, OpenSSLX509CRLEntry holder);
+ // android-add: @FastNative
+ static native void X509_REVOKED_print(long bioRef, long x509RevokedCtx,
+ OpenSSLX509CRLEntry holder);
+ // android-add: @FastNative
static native void X509_REVOKED_free(long x509RevokedCtx, OpenSSLX509CRLEntry holder);
// --- X509_EXTENSION ------------------------------------------------------
+ // android-add: @FastNative
static native int X509_supported_extension(long x509ExtensionRef);
// --- SPAKE ---------------------------------------------------------------
/**
- * Sets the SPAKE credential for the given SSL context using a password.
- * Used for both client and server.
+ * Sets the SPAKE credential for the given SSL context using a password. Used for both client
+ * and server.
*/
+ // android-add: @FastNative
static native void SSL_CTX_set_spake_credential(byte[] context, byte[] pw_array,
- byte[] id_prover_array, byte[] id_verifier_array, boolean is_client,
- int handshake_limit, long ssl_ctx, AbstractSessionContext holder) throws SSLException;
+ byte[] id_prover_array,
+ byte[] id_verifier_array, boolean is_client,
+ int handshake_limit, long ssl_ctx,
+ AbstractSessionContext holder)
+ throws SSLException;
// --- ASN1_TIME -----------------------------------------------------------
+ // android-add: @FastNative
static native void ASN1_TIME_to_Calendar(long asn1TimeCtx, Calendar cal)
throws ParsingException;
@@ -720,144 +935,151 @@ static native void ASN1_TIME_to_Calendar(long asn1TimeCtx, Calendar cal)
/**
* Allocates and returns an opaque reference to an object that can be used with other
- * asn1_read_* functions to read the ASN.1-encoded data in val. The returned object must
- * be freed after use by calling asn1_read_free.
+ * asn1_read_* functions to read the ASN.1-encoded data in val. The returned object must be
+ * freed after use by calling asn1_read_free.
*/
+ // android-add: @FastNative
static native long asn1_read_init(byte[] val) throws IOException;
/**
* Allocates and returns an opaque reference to an object that can be used with other
- * asn1_read_* functions to read the ASN.1 sequence pointed to by cbsRef. The returned
- * object must be freed after use by calling asn1_read_free.
+ * asn1_read_* functions to read the ASN.1 sequence pointed to by cbsRef. The returned object
+ * must be freed after use by calling asn1_read_free.
*/
+ // android-add: @FastNative
static native long asn1_read_sequence(long cbsRef) throws IOException;
/**
- * Returns whether the next object in the given reference is explicitly tagged with the
- * given tag number.
+ * Returns whether the next object in the given reference is explicitly tagged with the given
+ * tag number.
*/
+ // android-add: @FastNative
static native boolean asn1_read_next_tag_is(long cbsRef, int tag) throws IOException;
/**
- * Allocates and returns an opaque reference to an object that can be used with
- * other asn1_read_* functions to read the ASN.1 data pointed to by cbsRef. The returned
- * object must be freed after use by calling asn1_read_free.
+ * Allocates and returns an opaque reference to an object that can be used with other
+ * asn1_read_* functions to read the ASN.1 data pointed to by cbsRef. The returned object must
+ * be freed after use by calling asn1_read_free.
*/
+ // android-add: @FastNative
static native long asn1_read_tagged(long cbsRef) throws IOException;
- /**
- * Returns the contents of an ASN.1 octet string from the given reference.
- */
+ /** Returns the contents of an ASN.1 octet string from the given reference. */
+ // android-add: @FastNative
static native byte[] asn1_read_octetstring(long cbsRef) throws IOException;
/**
- * Returns an ASN.1 integer from the given reference. If the integer doesn't fit
- * in a uint64, this method will throw an IOException.
+ * Returns an ASN.1 integer from the given reference. If the integer doesn't fit in a uint64,
+ * this method will throw an IOException.
*/
+ // android-add: @FastNative
static native long asn1_read_uint64(long cbsRef) throws IOException;
- /**
- * Consumes an ASN.1 NULL from the given reference.
- */
+ /** Consumes an ASN.1 NULL from the given reference. */
+ // android-add: @FastNative
static native void asn1_read_null(long cbsRef) throws IOException;
/**
* Returns an ASN.1 OID in dotted-decimal notation (eg, "1.3.14.3.2.26" for SHA-1) from the
* given reference.
*/
+ // android-add: @FastNative
static native String asn1_read_oid(long cbsRef) throws IOException;
- /**
- * Returns whether or not the given reference has been read completely.
- */
+ /** Returns whether or not the given reference has been read completely. */
+ // android-add: @FastNative
static native boolean asn1_read_is_empty(long cbsRef);
/**
- * Frees any resources associated with the given reference. After calling, the reference
- * must not be used again. This may be called with a zero reference, in which case nothing
- * will be done.
+ * Frees any resources associated with the given reference. After calling, the reference must
+ * not be used again. This may be called with a zero reference, in which case nothing will be
+ * done.
*/
+ // android-add: @FastNative
static native void asn1_read_free(long cbsRef);
/**
* Allocates and returns an opaque reference to an object that can be used with other
- * asn1_write_* functions to write ASN.1-encoded data. The returned object must be finalized
- * after use by calling either asn1_write_finish or asn1_write_cleanup, and its resources
- * must be freed by calling asn1_write_free.
+ * asn1_write_* functions to write ASN.1-encoded data. The returned object must be finalized
+ * after use by calling either asn1_write_finish or asn1_write_cleanup, and its resources must
+ * be freed by calling asn1_write_free.
*/
+ // android-add: @FastNative
static native long asn1_write_init() throws IOException;
/**
* Allocates and returns an opaque reference to an object that can be used with other
- * asn1_write_* functions to write an ASN.1 sequence into the given reference. The returned
- * reference may only be used until the next call on the parent reference. The returned
- * object must be freed after use by calling asn1_write_free.
+ * asn1_write_* functions to write an ASN.1 sequence into the given reference. The returned
+ * reference may only be used until the next call on the parent reference. The returned object
+ * must be freed after use by calling asn1_write_free.
*/
+ // android-add: @FastNative
static native long asn1_write_sequence(long cbbRef) throws IOException;
/**
* Allocates and returns an opaque reference to an object that can be used with other
- * asn1_write_* functions to write a explicitly-tagged ASN.1 object with the given tag
- * into the given reference. The returned reference may only be used until the next
- * call on the parent reference. The returned object must be freed after use by
- * calling asn1_write_free.
+ * asn1_write_* functions to write a explicitly-tagged ASN.1 object with the given tag into the
+ * given reference. The returned reference may only be used until the next call on the parent
+ * reference. The returned object must be freed after use by calling asn1_write_free.
*/
+ // android-add: @FastNative
static native long asn1_write_tag(long cbbRef, int tag) throws IOException;
- /**
- * Writes the given data into the given reference as an ASN.1-encoded octet string.
- */
+ /** Writes the given data into the given reference as an ASN.1-encoded octet string. */
+ // android-add: @FastNative
static native void asn1_write_octetstring(long cbbRef, byte[] data) throws IOException;
- /**
- * Writes the given value into the given reference as an ASN.1-encoded integer.
- */
+ /** Writes the given value into the given reference as an ASN.1-encoded integer. */
+ // android-add: @FastNative
static native void asn1_write_uint64(long cbbRef, long value) throws IOException;
- /**
- * Writes a NULL value into the given reference.
- */
+ /** Writes a NULL value into the given reference. */
+ // android-add: @FastNative
static native void asn1_write_null(long cbbRef) throws IOException;
- /**
- * Writes the given OID (which must be in dotted-decimal notation) into the given reference.
- */
+ /** Writes the given OID (which must be in dotted-decimal notation) into the given reference. */
+ // android-add: @FastNative
static native void asn1_write_oid(long cbbRef, String oid) throws IOException;
/**
* Flushes the given reference, invalidating any child references and completing their
- * operations. This must be called if the child references are to be freed before
- * asn1_write_finish is called on the ultimate parent. The child references must still
- * be freed.
+ * operations. This must be called if the child references are to be freed before
+ * asn1_write_finish is called on the ultimate parent. The child references must still be freed.
*/
+ // android-add: @FastNative
static native void asn1_write_flush(long cbbRef) throws IOException;
/**
- * Completes any in-progress operations and returns the ASN.1-encoded data. Either this
- * or asn1_write_cleanup must be called on any reference returned from asn1_write_init
- * before it is freed.
+ * Completes any in-progress operations and returns the ASN.1-encoded data. Either this or
+ * asn1_write_cleanup must be called on any reference returned from asn1_write_init before it is
+ * freed.
*/
+ // android-add: @FastNative
static native byte[] asn1_write_finish(long cbbRef) throws IOException;
/**
- * Cleans up intermediate state in the given reference. Either this or asn1_write_finish
- * must be called on any reference returned from asn1_write_init before it is freed.
+ * Cleans up intermediate state in the given reference. Either this or asn1_write_finish must be
+ * called on any reference returned from asn1_write_init before it is freed.
*/
+ // android-add: @FastNative
static native void asn1_write_cleanup(long cbbRef);
/**
- * Frees resources associated with the given reference. After calling, the reference
- * must not be used again. This may be called with a zero reference, in which case nothing
- * will be done.
+ * Frees resources associated with the given reference. After calling, the reference must not be
+ * used again. This may be called with a zero reference, in which case nothing will be done.
*/
+ // android-add: @FastNative
static native void asn1_write_free(long cbbRef);
// --- BIO stream creation -------------------------------------------------
+ // android-add: @FastNative
static native long create_BIO_InputStream(OpenSSLBIOInputStream is, boolean isFinite);
+ // android-add: @FastNative
static native long create_BIO_OutputStream(OutputStream os);
+ // android-add: @FastNative
static native void BIO_free_all(long bioRef);
// --- SSL handling --------------------------------------------------------
@@ -887,23 +1109,18 @@ static native void ASN1_TIME_to_Calendar(long asn1TimeCtx, Calendar cal)
new HashSet(Arrays.asList(SUPPORTED_TLS_1_3_CIPHER_SUITES));
/**
- * TLS_EMPTY_RENEGOTIATION_INFO_SCSV is RFC 5746's renegotiation
- * indication signaling cipher suite value. It is not a real
- * cipher suite. It is just an indication in the default and
- * supported cipher suite lists indicates that the implementation
- * supports secure renegotiation.
- *
- * In the RI, its presence means that the SCSV is sent in the
- * cipher suite list to indicate secure renegotiation support and
- * its absense means to send an empty TLS renegotiation info
+ * TLS_EMPTY_RENEGOTIATION_INFO_SCSV is RFC 5746's renegotiation indication signaling cipher
+ * suite value. It is not a real cipher suite. It is just an indication in the default and
+ * supported cipher suite lists indicates that the implementation supports secure renegotiation.
+ *
+ *
In the RI, its presence means that the SCSV is sent in the cipher suite list to indicate
+ * secure renegotiation support and its absense means to send an empty TLS renegotiation info
* extension instead.
- *
- * However, OpenSSL doesn't provide an API to give this level of
- * control, instead always sending the SCSV and always including
- * the empty renegotiation info if TLS is used (as opposed to
- * SSL). So we simply allow TLS_EMPTY_RENEGOTIATION_INFO_SCSV to
- * be passed for compatibility as to provide the hint that we
- * support secure renegotiation.
+ *
+ *
However, OpenSSL doesn't provide an API to give this level of control, instead always
+ * sending the SCSV and always including the empty renegotiation info if TLS is used (as opposed
+ * to SSL). So we simply allow TLS_EMPTY_RENEGOTIATION_INFO_SCSV to be passed for compatibility
+ * as to provide the hint that we support secure renegotiation.
*/
static final String TLS_EMPTY_RENEGOTIATION_INFO_SCSV = "TLS_EMPTY_RENEGOTIATION_INFO_SCSV";
@@ -923,15 +1140,14 @@ static String cipherSuiteFromJava(String javaCipherSuite) {
}
/**
- * TLS_FALLBACK_SCSV is from
- * https://tools.ietf.org/html/draft-ietf-tls-downgrade-scsv-00
- * to indicate to the server that this is a fallback protocol
- * request.
+ * TLS_FALLBACK_SCSV is from https://tools.ietf.org/html/draft-ietf-tls-downgrade-scsv-00 to
+ * indicate to the server that this is a fallback protocol request.
*/
private static final String TLS_FALLBACK_SCSV = "TLS_FALLBACK_SCSV";
private static final boolean HAS_AES_HARDWARE;
private static final String[] SUPPORTED_TLS_1_2_CIPHER_SUITES;
+
static {
if (loadError == null) {
// If loadError is not null, it means the native code was not loaded, so
@@ -965,11 +1181,13 @@ static String cipherSuiteFromJava(String javaCipherSuite) {
}
/**
- * Returns 1 if the BoringSSL believes the CPU has AES accelerated hardware
- * instructions. Used to determine cipher suite ordering.
+ * Returns 1 if the BoringSSL believes the CPU has AES accelerated hardware instructions. Used
+ * to determine cipher suite ordering.
*/
+ // android-add: @FastNative
static native int EVP_has_aes_hardware();
+ // android-add: @FastNative
static native long SSL_CTX_new();
// IMPLEMENTATION NOTE: The default list of cipher suites is a trade-off between what we'd like
@@ -991,39 +1209,40 @@ static String cipherSuiteFromJava(String javaCipherSuite) {
// prevent apps from connecting to servers they were previously able to connect to.
/** X.509 based cipher suites enabled by default (if requested), in preference order. */
- static final String[] DEFAULT_X509_CIPHER_SUITES = HAS_AES_HARDWARE ?
- new String[] {
- "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
- "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
- "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
- "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
- "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
- "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
- "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
- "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
- "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
- "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
- "TLS_RSA_WITH_AES_128_GCM_SHA256",
- "TLS_RSA_WITH_AES_256_GCM_SHA384",
- "TLS_RSA_WITH_AES_128_CBC_SHA",
- "TLS_RSA_WITH_AES_256_CBC_SHA",
- } :
- new String[] {
- "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
- "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
- "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
- "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
- "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
- "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
- "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
- "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
- "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
- "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
- "TLS_RSA_WITH_AES_128_GCM_SHA256",
- "TLS_RSA_WITH_AES_256_GCM_SHA384",
- "TLS_RSA_WITH_AES_128_CBC_SHA",
- "TLS_RSA_WITH_AES_256_CBC_SHA",
- };
+ static final String[] DEFAULT_X509_CIPHER_SUITES =
+ HAS_AES_HARDWARE
+ ? new String[] {
+ "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
+ "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
+ "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
+ "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
+ "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
+ "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
+ "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
+ "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
+ "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
+ "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
+ "TLS_RSA_WITH_AES_128_GCM_SHA256",
+ "TLS_RSA_WITH_AES_256_GCM_SHA384",
+ "TLS_RSA_WITH_AES_128_CBC_SHA",
+ "TLS_RSA_WITH_AES_256_CBC_SHA",
+ }
+ : new String[] {
+ "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
+ "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
+ "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
+ "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
+ "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
+ "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
+ "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
+ "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
+ "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
+ "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
+ "TLS_RSA_WITH_AES_128_GCM_SHA256",
+ "TLS_RSA_WITH_AES_256_GCM_SHA384",
+ "TLS_RSA_WITH_AES_128_CBC_SHA",
+ "TLS_RSA_WITH_AES_256_CBC_SHA",
+ };
/** TLS-PSK cipher suites enabled by default (if requested), in preference order. */
static final String[] DEFAULT_PSK_CIPHER_SUITES = new String[] {
@@ -1040,27 +1259,34 @@ static String cipherSuiteFromJava(String javaCipherSuite) {
};
static String[] getSupportedCipherSuites() {
- return SSLUtils.concat(
- SUPPORTED_TLS_1_3_CIPHER_SUITES, SUPPORTED_TLS_1_2_CIPHER_SUITES.clone());
+ return SSLUtils.concat(SUPPORTED_TLS_1_3_CIPHER_SUITES,
+ SUPPORTED_TLS_1_2_CIPHER_SUITES.clone());
}
+ // android-add: @FastNative
static native void SSL_CTX_free(long ssl_ctx, AbstractSessionContext holder);
- static native void SSL_CTX_set_session_id_context(
- long ssl_ctx, AbstractSessionContext holder, byte[] sid_ctx);
+ // android-add: @FastNative
+ static native void SSL_CTX_set_session_id_context(long ssl_ctx, AbstractSessionContext holder,
+ byte[] sid_ctx);
- static native long SSL_CTX_set_timeout(
- long ssl_ctx, AbstractSessionContext holder, long seconds);
+ // android-add: @FastNative
+ static native long SSL_CTX_set_timeout(long ssl_ctx, AbstractSessionContext holder,
+ long seconds);
+ // android-add: @FastNative
static native long SSL_new(long ssl_ctx, AbstractSessionContext holder) throws SSLException;
+ // android-add: @FastNative
static native void SSL_enable_tls_channel_id(long ssl, NativeSsl ssl_holder)
throws SSLException;
+ // android-add: @FastNative
static native byte[] SSL_get_tls_channel_id(long ssl, NativeSsl ssl_holder) throws SSLException;
- static native void SSL_set1_tls_channel_id(
- long ssl, NativeSsl ssl_holder, NativeRef.EVP_PKEY pkey);
+ // android-add: @FastNative
+ static native void SSL_set1_tls_channel_id(long ssl, NativeSsl ssl_holder,
+ NativeRef.EVP_PKEY pkey);
/**
* Sets the local certificates and private key.
@@ -1070,47 +1296,67 @@ static native void SSL_set1_tls_channel_id(
* @param pkey a reference to the private key.
* @throws SSLException if a problem occurs setting the cert/key.
*/
+ // android-add: @FastNative
static native void setLocalCertsAndPrivateKey(long ssl, NativeSsl ssl_holder,
- byte[][] encodedCertificates, NativeRef.EVP_PKEY pkey) throws SSLException;
+ byte[][] encodedCertificates,
+ NativeRef.EVP_PKEY pkey) throws SSLException;
+ // android-add: @FastNative
static native void SSL_set_client_CA_list(long ssl, NativeSsl ssl_holder,
- byte[][] asn1DerEncodedX500Principals) throws SSLException;
+ byte[][] asn1DerEncodedX500Principals)
+ throws SSLException;
+ // android-add: @FastNative
static native long SSL_set_mode(long ssl, NativeSsl ssl_holder, long mode);
+ // android-add: @FastNative
static native long SSL_set_options(long ssl, NativeSsl ssl_holder, long options);
+ // android-add: @FastNative
static native long SSL_clear_options(long ssl, NativeSsl ssl_holder, long options);
- static native int SSL_set_protocol_versions(
- long ssl, NativeSsl ssl_holder, int min_version, int max_version);
+ // android-add: @FastNative
+ static native int SSL_set_protocol_versions(long ssl, NativeSsl ssl_holder, int min_version,
+ int max_version);
+ // android-add: @FastNative
static native void SSL_enable_signed_cert_timestamps(long ssl, NativeSsl ssl_holder);
+ // android-add: @FastNative
static native byte[] SSL_get_signed_cert_timestamp_list(long ssl, NativeSsl ssl_holder);
- static native void SSL_set_signed_cert_timestamp_list(
- long ssl, NativeSsl ssl_holder, byte[] list);
+ // android-add: @FastNative
+ static native void SSL_set_signed_cert_timestamp_list(long ssl, NativeSsl ssl_holder,
+ byte[] list);
+ // android-add: @FastNative
static native void SSL_enable_ocsp_stapling(long ssl, NativeSsl ssl_holder);
+ // android-add: @FastNative
static native byte[] SSL_get_ocsp_response(long ssl, NativeSsl ssl_holder);
+ // android-add: @FastNative
static native void SSL_set_ocsp_response(long ssl, NativeSsl ssl_holder, byte[] response);
+ // android-add: @FastNative
static native byte[] SSL_get_tls_unique(long ssl, NativeSsl ssl_holder);
+ // android-add: @FastNative
static native byte[] SSL_export_keying_material(long ssl, NativeSsl ssl_holder, byte[] label,
- byte[] context, int num_bytes) throws SSLException;
+ byte[] context, int num_bytes)
+ throws SSLException;
- static native void SSL_use_psk_identity_hint(
- long ssl, NativeSsl ssl_holder, String identityHint) throws SSLException;
+ // android-add: @FastNative
+ static native void SSL_use_psk_identity_hint(long ssl, NativeSsl ssl_holder,
+ String identityHint) throws SSLException;
- static native void set_SSL_psk_client_callback_enabled(
- long ssl, NativeSsl ssl_holder, boolean enabled);
+ // android-add: @FastNative
+ static native void set_SSL_psk_client_callback_enabled(long ssl, NativeSsl ssl_holder,
+ boolean enabled);
- static native void set_SSL_psk_server_callback_enabled(
- long ssl, NativeSsl ssl_holder, boolean enabled);
+ // android-add: @FastNative
+ static native void set_SSL_psk_server_callback_enabled(long ssl, NativeSsl ssl_holder,
+ boolean enabled);
public static void setTlsV1DeprecationStatus(boolean deprecated, boolean supported) {
if (deprecated) {
@@ -1180,6 +1426,7 @@ static String[] getSupportedProtocols() {
private static class Range {
public final String min;
public final String max;
+
public Range(String min, String max) {
this.min = min;
this.max = max;
@@ -1215,8 +1462,8 @@ private static Range getProtocolRange(String[] protocols) {
static void setEnabledProtocols(long ssl, NativeSsl ssl_holder, String[] protocols) {
checkEnabledProtocols(protocols);
Range range = getProtocolRange(protocols);
- SSL_set_protocol_versions(
- ssl, ssl_holder, getProtocolConstant(range.min), getProtocolConstant(range.max));
+ SSL_set_protocol_versions(ssl, ssl_holder, getProtocolConstant(range.min),
+ getProtocolConstant(range.max));
}
private static int getProtocolConstant(String protocol) {
@@ -1248,6 +1495,7 @@ static String[] checkEnabledProtocols(String[] protocols) {
return protocols;
}
+ // android-add: @FastNative
static native void SSL_set_cipher_lists(long ssl, NativeSsl ssl_holder, String[] ciphers);
/**
@@ -1255,10 +1503,11 @@ static String[] checkEnabledProtocols(String[] protocols) {
*
* @return array of {@code SSL_CIPHER} references.
*/
+ // android-add: @FastNative
static native long[] SSL_get_ciphers(long ssl, NativeSsl ssl_holder);
- static void setEnabledCipherSuites(
- long ssl, NativeSsl ssl_holder, String[] cipherSuites, String[] protocols) {
+ static void setEnabledCipherSuites(long ssl, NativeSsl ssl_holder, String[] cipherSuites,
+ String[] protocols) {
checkEnabledCipherSuites(cipherSuites);
String maxProtocol = getProtocolRange(protocols).max;
List opensslSuites = new ArrayList();
@@ -1271,15 +1520,15 @@ static void setEnabledCipherSuites(
// problems when servers upgrade. See https://github.com/google/conscrypt/issues/574
// for more discussion.
if (cipherSuite.equals(TLS_FALLBACK_SCSV)
- && (maxProtocol.equals(DEPRECATED_PROTOCOL_TLSV1)
- || maxProtocol.equals(DEPRECATED_PROTOCOL_TLSV1_1))) {
+ && (maxProtocol.equals(DEPRECATED_PROTOCOL_TLSV1)
+ || maxProtocol.equals(DEPRECATED_PROTOCOL_TLSV1_1))) {
SSL_set_mode(ssl, ssl_holder, NativeConstants.SSL_MODE_SEND_FALLBACK_SCSV);
continue;
}
opensslSuites.add(cipherSuiteFromJava(cipherSuite));
}
- SSL_set_cipher_lists(
- ssl, ssl_holder, opensslSuites.toArray(new String[opensslSuites.size()]));
+ SSL_set_cipher_lists(ssl, ssl_holder,
+ opensslSuites.toArray(new String[opensslSuites.size()]));
}
static String[] checkEnabledCipherSuites(String[] cipherSuites) {
@@ -1292,7 +1541,7 @@ static String[] checkEnabledCipherSuites(String[] cipherSuites) {
throw new IllegalArgumentException("cipherSuites[" + i + "] == null");
}
if (cipherSuites[i].equals(TLS_EMPTY_RENEGOTIATION_INFO_SCSV)
- || cipherSuites[i].equals(TLS_FALLBACK_SCSV)) {
+ || cipherSuites[i].equals(TLS_FALLBACK_SCSV)) {
continue;
}
if (SUPPORTED_TLS_1_2_CIPHER_SUITES_SET.contains(cipherSuites[i])) {
@@ -1310,106 +1559,136 @@ static String[] checkEnabledCipherSuites(String[] cipherSuites) {
// TODO log warning about using backward compatability
continue;
}
- throw new IllegalArgumentException(
- "cipherSuite " + cipherSuites[i] + " is not supported.");
+ throw new IllegalArgumentException("cipherSuite " + cipherSuites[i]
+ + " is not supported.");
}
return cipherSuites;
}
+ // android-add: @FastNative
static native void SSL_set_accept_state(long ssl, NativeSsl ssl_holder);
+ // android-add: @FastNative
static native void SSL_set_connect_state(long ssl, NativeSsl ssl_holder);
+ // android-add: @FastNative
static native void SSL_set_verify(long ssl, NativeSsl ssl_holder, int mode);
+ // android-add: @FastNative
static native void SSL_set_session(long ssl, NativeSsl ssl_holder, long sslSessionNativePointer)
throws SSLException;
- static native void SSL_set_session_creation_enabled(
- long ssl, NativeSsl ssl_holder, boolean creationEnabled) throws SSLException;
+ // android-add: @FastNative
+ static native void SSL_set_session_creation_enabled(long ssl, NativeSsl ssl_holder,
+ boolean creationEnabled)
+ throws SSLException;
+ // android-add: @FastNative
static native boolean SSL_session_reused(long ssl, NativeSsl ssl_holder);
+ // android-add: @FastNative
static native void SSL_accept_renegotiations(long ssl, NativeSsl ssl_holder)
throws SSLException;
+ // android-add: @FastNative
static native void SSL_set_tlsext_host_name(long ssl, NativeSsl ssl_holder, String hostname)
throws SSLException;
+
+ // android-add: @FastNative
static native String SSL_get_servername(long ssl, NativeSsl ssl_holder);
static native void SSL_do_handshake(long ssl, NativeSsl ssl_holder, FileDescriptor fd,
- SSLHandshakeCallbacks shc, int timeoutMillis)
+ SSLHandshakeCallbacks shc, int timeoutMillis)
throws SSLException, SocketTimeoutException, CertificateException;
+ // android-add: @FastNative
public static native String SSL_get_current_cipher(long ssl, NativeSsl ssl_holder);
+ // android-add: @FastNative
+ public static native String SSL_get_version(long ssl, NativeSsl ssl_holder);
+
public static native void SSL_set1_groups(long ssl, NativeSsl sslHolder, int[] groups);
public static native String SSL_get_curve_name(long ssl, NativeSsl sslHolder);
- public static native String SSL_get_version(long ssl, NativeSsl ssl_holder);
-
- /**
- * Returns the peer certificate chain.
- */
+ /** Returns the peer certificate chain. */
+ // android-add: @FastNative
static native byte[][] SSL_get0_peer_certificates(long ssl, NativeSsl ssl_holder);
/**
* Reads with the native SSL_read function from the encrypted data stream
+ *
* @return -1 if error or the end of the stream is reached.
*/
static native int SSL_read(long ssl, NativeSsl ssl_holder, FileDescriptor fd,
- SSLHandshakeCallbacks shc, byte[] b, int off, int len, int readTimeoutMillis)
- throws IOException;
+ SSLHandshakeCallbacks shc, byte[] b, int off, int len,
+ int readTimeoutMillis) throws IOException;
- /**
- * Writes with the native SSL_write function to the encrypted data stream.
- */
+ /** Writes with the native SSL_write function to the encrypted data stream. */
static native void SSL_write(long ssl, NativeSsl ssl_holder, FileDescriptor fd,
- SSLHandshakeCallbacks shc, byte[] b, int off, int len, int writeTimeoutMillis)
- throws IOException;
+ SSLHandshakeCallbacks shc, byte[] b, int off, int len,
+ int writeTimeoutMillis) throws IOException;
+ // android-add: @FastNative
static native void SSL_interrupt(long ssl, NativeSsl ssl_holder);
+
static native void SSL_shutdown(long ssl, NativeSsl ssl_holder, FileDescriptor fd,
- SSLHandshakeCallbacks shc) throws IOException;
+ SSLHandshakeCallbacks shc) throws IOException;
+ // android-add: @FastNative
static native int SSL_get_shutdown(long ssl, NativeSsl ssl_holder);
+ // android-add: @FastNative
static native void SSL_free(long ssl, NativeSsl ssl_holder);
+ // android-add: @FastNative
static native long SSL_get_time(long ssl, NativeSsl ssl_holder);
+ // android-add: @FastNative
static native long SSL_set_timeout(long ssl, NativeSsl ssl_holder, long millis);
+ // android-add: @FastNative
static native long SSL_get_timeout(long ssl, NativeSsl ssl_holder);
+ // android-add: @FastNative
static native int SSL_get_signature_algorithm_key_type(int signatureAlg);
+ // android-add: @FastNative
static native byte[] SSL_session_id(long ssl, NativeSsl ssl_holder);
+ // android-add: @FastNative
static native byte[] SSL_SESSION_session_id(long sslSessionNativePointer);
+ // android-add: @FastNative
static native long SSL_SESSION_get_time(long sslSessionNativePointer);
+ // android-add: @FastNative
static native long SSL_SESSION_get_timeout(long sslSessionNativePointer);
+ // android-add: @FastNative
static native String SSL_SESSION_get_version(long sslSessionNativePointer);
+ // android-add: @FastNative
static native String SSL_SESSION_cipher(long sslSessionNativePointer);
+ // android-add: @FastNative
static native boolean SSL_SESSION_should_be_single_use(long sslSessionNativePointer);
+ // android-add: @FastNative
static native void SSL_SESSION_up_ref(long sslSessionNativePointer);
+ // android-add: @FastNative
static native void SSL_SESSION_free(long sslSessionNativePointer);
+ // android-add: @FastNative
static native byte[] i2d_SSL_SESSION(long sslSessionNativePointer);
+ // android-add: @FastNative
static native long d2i_SSL_SESSION(byte[] data) throws IOException;
/**
- * A collection of callbacks from the native OpenSSL code that are
- * related to the SSL handshake initiated by SSL_do_handshake.
+ * A collection of callbacks from the native OpenSSL code that are related to the SSL handshake
+ * initiated by SSL_do_handshake.
*/
interface SSLHandshakeCallbacks {
/**
@@ -1417,7 +1696,6 @@ interface SSLHandshakeCallbacks {
*
* @param certificateChain chain of X.509 certificates in their encoded form
* @param authMethod auth algorithm name
- *
* @throws CertificateException if the certificate is untrusted
*/
@SuppressWarnings("unused")
@@ -1433,14 +1711,14 @@ void verifyCertificateChain(byte[][] certificateChain, String authMethod)
* @param asn1DerEncodedX500Principals CAs known to the server
*/
@SuppressWarnings("unused")
- void clientCertificateRequested(
- byte[] keyTypes, int[] signatureAlgs, byte[][] asn1DerEncodedX500Principals)
+ void clientCertificateRequested(byte[] keyTypes, int[] signatureAlgs,
+ byte[][] asn1DerEncodedX500Principals)
throws CertificateEncodingException, SSLException;
/**
- * Called when acting as a server during ClientHello processing before a decision
- * to resume a session is made. This allows the selection of the correct server
- * certificate based on things like Server Name Indication (SNI).
+ * Called when acting as a server during ClientHello processing before a decision to resume
+ * a session is made. This allows the selection of the correct server certificate based on
+ * things like Server Name Indication (SNI).
*
* @throws IOException if there was an error during certificate selection.
*/
@@ -1451,13 +1729,12 @@ void clientCertificateRequested(
* exchange.
*
* @param identityHint PSK identity hint provided by the server or {@code null} if no hint
- * provided.
+ * provided.
* @param identity buffer to be populated with PSK identity (NULL-terminated modified UTF-8)
- * by this method. This identity will be provided to the server.
+ * by this method. This identity will be provided to the server.
* @param key buffer to be populated with key material by this method.
- *
* @return number of bytes this method stored in the {@code key} buffer or {@code 0} if an
- * error occurred in which case the handshake will be aborted.
+ * error occurred in which case the handshake will be aborted.
*/
int clientPSKKeyRequested(String identityHint, byte[] identity, byte[] key);
@@ -1465,33 +1742,30 @@ void clientCertificateRequested(
* Gets the key to be used in server mode for this connection in Pre-Shared Key (PSK) key
* exchange.
*
- * @param identityHint PSK identity hint provided by this server to the client or
- * {@code null} if no hint was provided.
+ * @param identityHint PSK identity hint provided by this server to the client or {@code
+ * null} if no hint was provided.
* @param identity PSK identity provided by the client.
* @param key buffer to be populated with key material by this method.
- *
* @return number of bytes this method stored in the {@code key} buffer or {@code 0} if an
- * error occurred in which case the handshake will be aborted.
+ * error occurred in which case the handshake will be aborted.
*/
int serverPSKKeyRequested(String identityHint, String identity, byte[] key);
- /**
- * Called when SSL state changes. This could be handshake completion.
- */
+ /** Called when SSL state changes. This could be handshake completion. */
@SuppressWarnings("unused") void onSSLStateChange(int type, int val);
/**
- * Called when a new session has been established and may be added to the session cache.
- * The callee is responsible for incrementing the reference count on the returned session.
+ * Called when a new session has been established and may be added to the session cache. The
+ * callee is responsible for incrementing the reference count on the returned session.
*/
@SuppressWarnings("unused") void onNewSessionEstablished(long sslSessionNativePtr);
/**
- * Called for servers where TLS < 1.3 (TLS 1.3 uses session tickets rather than
- * application session caches).
+ * Called for servers where TLS < 1.3 (TLS 1.3 uses session tickets rather than application
+ * session caches).
*
- * Looks up the session by ID in the application's session cache. If a valid session
- * is returned, this callback is responsible for incrementing the reference count (and any
+ *
Looks up the session by ID in the application's session cache. If a valid session is
+ * returned, this callback is responsible for incrementing the reference count (and any
* required synchronization).
*
* @param id the ID of the session to find.
@@ -1501,7 +1775,7 @@ void clientCertificateRequested(
/**
* Called when acting as a server, the socket has an {@link
- * ApplicationProtocolSelectorAdapter} associated with it, and the application protocol
+ * ApplicationProtocolSelectorAdapter} associated with it, and the application protocol
* needs to be selected.
*
* @param applicationProtocols list of application protocols in length-prefix format
@@ -1510,131 +1784,146 @@ void clientCertificateRequested(
@SuppressWarnings("unused") int selectApplicationProtocol(byte[] applicationProtocols);
}
+ // android-add: @FastNative
static native String SSL_CIPHER_get_kx_name(long cipherAddress);
+ // android-add: @FastNative
static native String[] get_cipher_names(String selection);
+ // android-add: @FastNative
public static native byte[] get_ocsp_single_extension(byte[] ocspResponse, String oid,
- long x509Ref, OpenSSLX509Certificate holder, long issuerX509Ref,
- OpenSSLX509Certificate holder2);
+ long x509Ref,
+ OpenSSLX509Certificate holder,
+ long issuerX509Ref,
+ OpenSSLX509Certificate holder2);
/**
- * Returns the starting address of the memory region referenced by the provided direct
- * {@link Buffer} or {@code 0} if the provided buffer is not direct or if such access to direct
- * buffers is not supported by the platform.
+ * Returns the starting address of the memory region referenced by the provided direct {@link
+ * Buffer} or {@code 0} if the provided buffer is not direct or if such access to direct buffers
+ * is not supported by the platform.
*
*
NOTE: This method ignores the buffer's current {@code position}.
*/
+ // android-add: @FastNative
static native long getDirectBufferAddress(Buffer buf);
+ // android-add: @FastNative
static native long SSL_BIO_new(long ssl, NativeSsl ssl_holder) throws SSLException;
+ // android-add: @FastNative
static native int SSL_get_error(long ssl, NativeSsl ssl_holder, int ret);
+ // android-add: @FastNative
static native void SSL_clear_error();
+ // android-add: @FastNative
static native int SSL_pending_readable_bytes(long ssl, NativeSsl ssl_holder);
+ // android-add: @FastNative
static native int SSL_pending_written_bytes_in_BIO(long bio);
- /**
- * Returns the maximum overhead, in bytes, of sealing a record with SSL.
- */
+ /** Returns the maximum overhead, in bytes, of sealing a record with SSL. */
+ // android-add: @FastNative
static native int SSL_max_seal_overhead(long ssl, NativeSsl ssl_holder);
/**
* Enables ALPN for this TLS endpoint and sets the list of supported ALPN protocols in
* wire-format (length-prefixed 8-bit strings).
*/
- static native void setApplicationProtocols(
- long ssl, NativeSsl ssl_holder, boolean client, byte[] protocols) throws IOException;
+ // android-add: @FastNative
+ static native void setApplicationProtocols(long ssl, NativeSsl ssl_holder, boolean client,
+ byte[] protocols) throws IOException;
/**
* Called for a server endpoint only. Enables ALPN and indicates that the {@link
- * SSLHandshakeCallbacks#selectApplicationProtocol} will be called to select the
- * correct protocol during a handshake. Calling this method overrides
- * {@link #setApplicationProtocols(long, NativeSsl, boolean, byte[])}.
+ * SSLHandshakeCallbacks#selectApplicationProtocol} will be called to select the correct
+ * protocol during a handshake. Calling this method overrides {@link
+ * #setApplicationProtocols(long, NativeSsl, boolean, byte[])}.
*/
- static native void setHasApplicationProtocolSelector(
- long ssl, NativeSsl ssl_holder, boolean hasSelector) throws IOException;
+ // android-add: @FastNative
+ static native void setHasApplicationProtocolSelector(long ssl, NativeSsl ssl_holder,
+ boolean hasSelector) throws IOException;
/**
- * Returns the selected ALPN protocol. If the server did not select a
- * protocol, {@code null} will be returned.
+ * Returns the selected ALPN protocol. If the server did not select a protocol, {@code null}
+ * will be returned.
*/
+ // android-add: @FastNative
static native byte[] getApplicationProtocol(long ssl, NativeSsl ssl_holder);
/**
* Variant of the {@link #SSL_do_handshake} used by {@link ConscryptEngine}. This differs
- * slightly from the raw BoringSSL API in that it returns the SSL error code from the
- * operation, rather than the return value from {@code SSL_do_handshake}. This is done in
- * order to allow to properly handle SSL errors and propagate useful exceptions.
+ * slightly from the raw BoringSSL API in that it returns the SSL error code from the operation,
+ * rather than the return value from {@code SSL_do_handshake}. This is done in order to allow to
+ * properly handle SSL errors and propagate useful exceptions.
*
* @return Returns the SSL error code for the operation when the error was {@code
- * SSL_ERROR_NONE}, {@code SSL_ERROR_WANT_READ}, or {@code SSL_ERROR_WANT_WRITE}.
+ * SSL_ERROR_NONE}, {@code SSL_ERROR_WANT_READ}, or {@code SSL_ERROR_WANT_WRITE}.
* @throws IOException when the error code is anything except those returned by this method.
*/
- static native int ENGINE_SSL_do_handshake(
- long ssl, NativeSsl ssl_holder, SSLHandshakeCallbacks shc) throws IOException;
+ static native int ENGINE_SSL_do_handshake(long ssl, NativeSsl ssl_holder,
+ SSLHandshakeCallbacks shc) throws IOException;
/**
* Variant of the {@link #SSL_read} for a direct {@link java.nio.ByteBuffer} used by {@link
* ConscryptEngine}.
*
- * @return if positive, represents the number of bytes read into the given buffer.
- * Returns {@code -SSL_ERROR_WANT_READ} if more data is needed. Returns
- * {@code -SSL_ERROR_WANT_WRITE} if data needs to be written out to flush the BIO.
- *
+ * @return if positive, represents the number of bytes read into the given buffer. Returns
+ * {@code -SSL_ERROR_WANT_READ} if more data is needed. Returns {@code
+ * -SSL_ERROR_WANT_WRITE} if data needs to be written out to flush the BIO.
* @throws java.io.InterruptedIOException if the read was interrupted.
* @throws java.io.EOFException if the end of stream has been reached.
* @throws CertificateException if the application's certificate verification callback failed.
- * Only occurs during handshake processing.
+ * Only occurs during handshake processing.
* @throws SSLException if any other error occurs.
*/
static native int ENGINE_SSL_read_direct(long ssl, NativeSsl ssl_holder, long address,
- int length, SSLHandshakeCallbacks shc) throws IOException, CertificateException;
+ int length, SSLHandshakeCallbacks shc)
+ throws IOException, CertificateException;
/**
* Variant of the {@link #SSL_write} for a direct {@link java.nio.ByteBuffer} used by {@link
* ConscryptEngine}. This version does not lock or and does no error pre-processing.
*/
static native int ENGINE_SSL_write_direct(long ssl, NativeSsl ssl_holder, long address,
- int length, SSLHandshakeCallbacks shc) throws IOException;
+ int length, SSLHandshakeCallbacks shc)
+ throws IOException;
/**
* Writes data from the given direct {@link java.nio.ByteBuffer} to the BIO.
*/
static native int ENGINE_SSL_write_BIO_direct(long ssl, NativeSsl ssl_holder, long bioRef,
- long pos, int length, SSLHandshakeCallbacks shc) throws IOException;
+ long pos, int length, SSLHandshakeCallbacks shc)
+ throws IOException;
/**
* Reads data from the given BIO into a direct {@link java.nio.ByteBuffer}.
*/
static native int ENGINE_SSL_read_BIO_direct(long ssl, NativeSsl ssl_holder, long bioRef,
- long address, int len, SSLHandshakeCallbacks shc) throws IOException;
+ long address, int len, SSLHandshakeCallbacks shc)
+ throws IOException;
/**
* Forces the SSL object to process any data pending in the BIO.
*/
- static native void ENGINE_SSL_force_read(
- long ssl, NativeSsl ssl_holder, SSLHandshakeCallbacks shc) throws IOException;
+ static native void ENGINE_SSL_force_read(long ssl, NativeSsl ssl_holder,
+ SSLHandshakeCallbacks shc) throws IOException;
/**
* Variant of the {@link #SSL_shutdown} used by {@link ConscryptEngine}. This version does not
* lock.
*/
- static native void ENGINE_SSL_shutdown(
- long ssl, NativeSsl ssl_holder, SSLHandshakeCallbacks shc) throws IOException;
+ static native void ENGINE_SSL_shutdown(long ssl, NativeSsl ssl_holder,
+ SSLHandshakeCallbacks shc) throws IOException;
/**
* Generates a key from a password and salt using Scrypt.
*/
- static native byte[] Scrypt_generate_key(
- byte[] password, byte[] salt, int n, int r, int p, int key_len);
+ static native byte[] Scrypt_generate_key(byte[] password, byte[] salt, int n, int r, int p,
+ int key_len);
- /**
- * Return {@code true} if BoringSSL has been built in FIPS mode.
- */
+ /** Return {@code true} if BoringSSL has been built in FIPS mode. */
+ // android-add: @FastNative
static native boolean usesBoringSsl_FIPS_mode();
/* ECH */
@@ -1660,17 +1949,28 @@ static native boolean SSL_set1_ech_config_list(long ssl, NativeSsl ssl_holder, b
static native boolean SSL_ech_accepted(long ssl, NativeSsl ssl_holder);
- static native boolean SSL_CTX_ech_enable_server(
- long sslCtx, AbstractSessionContext holder, byte[] key, byte[] config);
+ static native boolean SSL_CTX_ech_enable_server(long sslCtx, AbstractSessionContext holder,
+ byte[] key, byte[] config);
/**
* Used for testing only.
*/
+ // android-add: @FastNative
static native int BIO_read(long bioRef, byte[] buffer) throws IOException;
+
+ // android-add: @FastNative
static native void BIO_write(long bioRef, byte[] buffer, int offset, int length)
throws IOException, IndexOutOfBoundsException;
+
+ // android-add: @FastNative
static native long SSL_clear_mode(long ssl, NativeSsl ssl_holder, long mode);
+
+ // android-add: @FastNative
static native long SSL_get_mode(long ssl, NativeSsl ssl_holder);
+
+ // android-add: @FastNative
static native long SSL_get_options(long ssl, NativeSsl ssl_holder);
+
+ // android-add: @FastNative
static native long SSL_get1_session(long ssl, NativeSsl ssl_holder);
}
diff --git a/common/src/main/java/org/conscrypt/NativeSsl.java b/common/src/main/java/org/conscrypt/NativeSsl.java
index ebf915ed9..02bc62496 100644
--- a/common/src/main/java/org/conscrypt/NativeSsl.java
+++ b/common/src/main/java/org/conscrypt/NativeSsl.java
@@ -65,8 +65,8 @@ final class NativeSsl {
private volatile long ssl;
private NativeSsl(long ssl, SSLParametersImpl parameters,
- SSLHandshakeCallbacks handshakeCallbacks, AliasChooser aliasChooser,
- PSKCallbacks pskCallbacks) {
+ SSLHandshakeCallbacks handshakeCallbacks, AliasChooser aliasChooser,
+ PSKCallbacks pskCallbacks) {
this.ssl = ssl;
this.parameters = parameters;
this.handshakeCallbacks = handshakeCallbacks;
@@ -75,8 +75,8 @@ private NativeSsl(long ssl, SSLParametersImpl parameters,
}
static NativeSsl newInstance(SSLParametersImpl parameters,
- SSLHandshakeCallbacks handshakeCallbacks, AliasChooser chooser,
- PSKCallbacks pskCallbacks) throws SSLException {
+ SSLHandshakeCallbacks handshakeCallbacks, AliasChooser chooser,
+ PSKCallbacks pskCallbacks) throws SSLException {
long ssl = parameters.getSessionContext().newSsl();
return new NativeSsl(ssl, parameters, handshakeCallbacks, chooser, pskCallbacks);
}
@@ -209,7 +209,7 @@ int serverPSKKeyRequested(String identityHint, String identity, byte[] key) {
}
void chooseClientCertificate(byte[] keyTypeBytes, int[] signatureAlgs,
- byte[][] asn1DerEncodedPrincipals)
+ byte[][] asn1DerEncodedPrincipals)
throws SSLException, CertificateEncodingException {
Set keyTypesSet = SSLUtils.getSupportedClientKeyTypes(keyTypeBytes, signatureAlgs);
String[] keyTypes = keyTypesSet.toArray(new String[0]);
@@ -322,8 +322,8 @@ static int[] toBoringSslGroups(String[] javaNamedGroups) {
}
}
if (i == 0) {
- throw new IllegalArgumentException(
- "No valid known group found in: " + Arrays.toString(javaNamedGroups));
+ throw new IllegalArgumentException("No valid known group found in: "
+ + Arrays.toString(javaNamedGroups));
}
if (i < javaNamedGroups.length) {
return Arrays.copyOf(outputGroups, i);
@@ -363,6 +363,7 @@ void initialize(String hostname, OpenSSLKey channelIdPrivateKey) throws IOExcept
if (parameters.isCTVerificationEnabled(hostname)) {
NativeCrypto.SSL_enable_signed_cert_timestamps(ssl, this);
}
+ enableEchBasedOnPolicy(hostname);
} else {
NativeCrypto.SSL_set_accept_state(ssl, this);
@@ -373,17 +374,17 @@ void initialize(String hostname, OpenSSLKey channelIdPrivateKey) throws IOExcept
}
if (parameters.getEnabledProtocols().length == 0 && parameters.isEnabledProtocolsFiltered) {
- throw new SSLHandshakeException("No enabled protocols; "
- + NativeCrypto.OBSOLETE_PROTOCOL_SSLV3 + ", "
- + NativeCrypto.DEPRECATED_PROTOCOL_TLSV1
- + " and " + NativeCrypto.DEPRECATED_PROTOCOL_TLSV1_1
+ throw new SSLHandshakeException(
+ "No enabled protocols; " + NativeCrypto.OBSOLETE_PROTOCOL_SSLV3 + ", "
+ + NativeCrypto.DEPRECATED_PROTOCOL_TLSV1 + " and "
+ + NativeCrypto.DEPRECATED_PROTOCOL_TLSV1_1
+ " are no longer supported and were filtered from the list");
}
NativeCrypto.setEnabledProtocols(ssl, this, parameters.enabledProtocols);
// We only set the cipher suites if we are not using SPAKE.
if (!parameters.isSpake()) {
- NativeCrypto.setEnabledCipherSuites(
- ssl, this, parameters.enabledCipherSuites, parameters.enabledProtocols);
+ NativeCrypto.setEnabledCipherSuites(ssl, this, parameters.enabledCipherSuites,
+ parameters.enabledProtocols);
}
String[] paramsNamedGroups = parameters.getNamedGroups();
@@ -408,7 +409,8 @@ void initialize(String hostname, OpenSSLKey channelIdPrivateKey) throws IOExcept
}
if (parameters.applicationProtocols.length > 0) {
- NativeCrypto.setApplicationProtocols(ssl, this, isClient(), parameters.applicationProtocols);
+ NativeCrypto.setApplicationProtocols(ssl, this, isClient(),
+ parameters.applicationProtocols);
}
if (!isClient() && parameters.applicationProtocolSelector != null) {
NativeCrypto.setHasApplicationProtocolSelector(ssl, this, true);
@@ -520,8 +522,8 @@ int read(FileDescriptor fd, byte[] buf, int offset, int len, int timeoutMillis)
if (isClosed() || fd == null || !fd.valid()) {
throw new SocketException("Socket is closed");
}
- return NativeCrypto
- .SSL_read(ssl, this, fd, handshakeCallbacks, buf, offset, len, timeoutMillis);
+ return NativeCrypto.SSL_read(ssl, this, fd, handshakeCallbacks, buf, offset, len,
+ timeoutMillis);
} finally {
lock.readLock().unlock();
}
@@ -535,8 +537,8 @@ void write(FileDescriptor fd, byte[] buf, int offset, int len, int timeoutMillis
if (isClosed() || fd == null || !fd.valid()) {
throw new SocketException("Socket is closed");
}
- NativeCrypto
- .SSL_write(ssl, this, fd, handshakeCallbacks, buf, offset, len, timeoutMillis);
+ NativeCrypto.SSL_write(ssl, this, fd, handshakeCallbacks, buf, offset, len,
+ timeoutMillis);
} finally {
lock.readLock().unlock();
}
@@ -583,14 +585,35 @@ private void setTlsChannelId(OpenSSLKey channelIdPrivateKey) throws SSLException
}
}
+ private void enableEchBasedOnPolicy(String hostname) throws SSLException {
+ EchOptions opts = parameters.getEchOptions(hostname);
+ if (opts == null) {
+ return;
+ }
+
+ byte[] configList = opts.getConfigList();
+ if (configList != null) {
+ try {
+ NativeCrypto.SSL_set1_ech_config_list(ssl, this, configList);
+ } catch (SSLException e) {
+ // The platform may provide a more specialized exception type for this error.
+ throw Platform.wrapInvalidEchDataException(e);
+ }
+ }
+
+ if (opts.isGreaseEnabled()) {
+ NativeCrypto.SSL_set_enable_ech_grease(ssl, this, /* enable= */ true);
+ }
+ }
+
private void setCertificateValidation() throws SSLException {
// setup peer certificate verification
if (!isClient()) {
// needing client auth takes priority...
boolean certRequested;
if (parameters.getNeedClientAuth()) {
- NativeCrypto.SSL_set_verify(ssl, this, SSL_VERIFY_PEER
- | SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
+ NativeCrypto.SSL_set_verify(ssl, this,
+ SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
certRequested = true;
// ... over just wanting it...
} else if (parameters.getWantClientAuth()) {
@@ -658,8 +681,8 @@ int readDirectByteBuffer(long destAddress, int destLength)
throws IOException, CertificateException {
lock.readLock().lock();
try {
- return NativeCrypto.ENGINE_SSL_read_direct(
- ssl, this, destAddress, destLength, handshakeCallbacks);
+ return NativeCrypto.ENGINE_SSL_read_direct(ssl, this, destAddress, destLength,
+ handshakeCallbacks);
} finally {
lock.readLock().unlock();
}
@@ -668,8 +691,8 @@ int readDirectByteBuffer(long destAddress, int destLength)
int writeDirectByteBuffer(long sourceAddress, int sourceLength) throws IOException {
lock.readLock().lock();
try {
- return NativeCrypto.ENGINE_SSL_write_direct(
- ssl, this, sourceAddress, sourceLength, handshakeCallbacks);
+ return NativeCrypto.ENGINE_SSL_write_direct(ssl, this, sourceAddress, sourceLength,
+ handshakeCallbacks);
} finally {
lock.readLock().unlock();
}
@@ -764,8 +787,8 @@ int writeDirectByteBuffer(long address, int length) throws IOException {
if (isClosed()) {
throw new SSLException("Connection closed");
}
- return NativeCrypto.ENGINE_SSL_write_BIO_direct(
- ssl, NativeSsl.this, bio, address, length, handshakeCallbacks);
+ return NativeCrypto.ENGINE_SSL_write_BIO_direct(ssl, NativeSsl.this, bio, address,
+ length, handshakeCallbacks);
} finally {
lock.readLock().unlock();
}
diff --git a/common/src/main/java/org/conscrypt/NetworkSecurityPolicy.java b/common/src/main/java/org/conscrypt/NetworkSecurityPolicy.java
new file mode 100644
index 000000000..499c5eda0
--- /dev/null
+++ b/common/src/main/java/org/conscrypt/NetworkSecurityPolicy.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.conscrypt;
+
+import org.conscrypt.metrics.CertificateTransparencyVerificationReason;
+
+/**
+ * A policy provided by the platform to decide on the behaviour of TrustManagerImpl.
+ *
+ * See the platform-specific implementations in PlatformNetworkSecurityPolicy.
+ */
+@Internal
+public interface NetworkSecurityPolicy {
+ boolean isCertificateTransparencyVerificationRequired(String hostname);
+
+ CertificateTransparencyVerificationReason getCertificateTransparencyVerificationReason(
+ String hostname);
+
+ DomainEncryptionMode getDomainEncryptionMode(String hostname);
+}
diff --git a/common/src/main/java/org/conscrypt/OpenSSLAeadCipher.java b/common/src/main/java/org/conscrypt/OpenSSLAeadCipher.java
index 867803af1..7ff4b3925 100644
--- a/common/src/main/java/org/conscrypt/OpenSSLAeadCipher.java
+++ b/common/src/main/java/org/conscrypt/OpenSSLAeadCipher.java
@@ -24,6 +24,7 @@
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;
+import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
@@ -33,6 +34,8 @@
@Internal
public abstract class OpenSSLAeadCipher extends OpenSSLCipher {
+ private static final Logger logger = Logger.getLogger(OpenSSLAeadCipher.class.getName());
+
/**
* Controls whether no-copy optimizations for direct ByteBuffers are enabled.
*/
@@ -97,8 +100,10 @@ private void checkInitialization() {
}
}
- /** Constant-time array comparison. Since we are using this to compare keys, we want to
- * ensure there's no opportunity for a timing attack. */
+ /**
+ * Constant-time array comparison. Since we are using this to compare keys, we want to
+ * ensure there's no opportunity for a timing attack.
+ */
private boolean arraysAreEqual(byte[] a, byte[] b) {
if (a.length != b.length) {
return false;
@@ -130,9 +135,8 @@ private void reset() {
}
@Override
- void engineInitInternal(byte[] encodedKey, AlgorithmParameterSpec params,
- SecureRandom random) throws InvalidKeyException,
- InvalidAlgorithmParameterException {
+ void engineInitInternal(byte[] encodedKey, AlgorithmParameterSpec params, SecureRandom random)
+ throws InvalidKeyException, InvalidAlgorithmParameterException {
byte[] iv;
final int tagLenBits;
if (params == null) {
@@ -165,7 +169,7 @@ void engineInitInternal(byte[] encodedKey, AlgorithmParameterSpec params,
if (iv == null && expectedIvLength != 0) {
if (!encrypting) {
throw new InvalidAlgorithmParameterException("IV must be specified in " + mode
- + " mode");
+ + " mode");
}
iv = new byte[expectedIvLength];
@@ -177,14 +181,13 @@ void engineInitInternal(byte[] encodedKey, AlgorithmParameterSpec params,
} else if (expectedIvLength == 0 && iv != null) {
throw new InvalidAlgorithmParameterException("IV not used in " + mode + " mode");
} else if (iv != null && iv.length != expectedIvLength) {
- throw new InvalidAlgorithmParameterException("Expected IV length of "
- + expectedIvLength + " but was " + iv.length);
+ throw new InvalidAlgorithmParameterException("Expected IV length of " + expectedIvLength
+ + " but was " + iv.length);
}
if (isEncrypting() && iv != null && !allowsNonceReuse()) {
- if (previousKey != null && previousIv != null
- && arraysAreEqual(previousKey, encodedKey)
- && arraysAreEqual(previousIv, iv)) {
+ if (previousKey != null && previousIv != null && arraysAreEqual(previousKey, encodedKey)
+ && arraysAreEqual(previousIv, iv)) {
mustInitialize = true;
throw new InvalidAlgorithmParameterException(
"When using AEAD key and IV must not be re-used");
@@ -202,11 +205,10 @@ && arraysAreEqual(previousIv, iv)) {
bufCount = 0;
}
- void checkSupportedTagLength(int tagLenBits)
- throws InvalidAlgorithmParameterException {
+ void checkSupportedTagLength(int tagLenBits) throws InvalidAlgorithmParameterException {
if (tagLenBits % 8 != 0) {
- throw new InvalidAlgorithmParameterException(
- "Tag length must be a multiple of 8; was " + tagLenBits);
+ throw new InvalidAlgorithmParameterException("Tag length must be a multiple of 8; was "
+ + tagLenBits);
}
}
@@ -220,8 +222,8 @@ boolean allowsNonceReuse() {
}
@Override
- protected int engineDoFinal(ByteBuffer input, ByteBuffer output) throws ShortBufferException,
- IllegalBlockSizeException, BadPaddingException {
+ protected int engineDoFinal(ByteBuffer input, ByteBuffer output)
+ throws ShortBufferException, IllegalBlockSizeException, BadPaddingException {
if (!ENABLE_BYTEBUFFER_OPTIMIZATIONS) {
return super.engineDoFinal(input, output);
}
@@ -247,14 +249,13 @@ protected int engineDoFinal(ByteBuffer input, ByteBuffer output) throws ShortBuf
input = inputClone;
}
if (!output.isDirect()) {
- ByteBuffer outputClone = ByteBuffer.allocateDirect(
- getOutputSizeForFinal(input.remaining()));
+ ByteBuffer outputClone =
+ ByteBuffer.allocateDirect(getOutputSizeForFinal(input.remaining()));
bytesWritten = doFinalInternal(input, outputClone);
output.put(outputClone);
input.position(input.limit()); // API reasons
- }
- else {
- bytesWritten = doFinalInternal(input, output);
+ } else {
+ bytesWritten = doFinalInternal(input, output);
output.position(output.position() + bytesWritten);
input.position(input.limit()); // API reasons
}
@@ -288,8 +289,8 @@ protected byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen)
@Override
protected int engineDoFinal(byte[] input, int inputOffset, int inputLen, byte[] output,
- int outputOffset) throws ShortBufferException, IllegalBlockSizeException,
- BadPaddingException {
+ int outputOffset)
+ throws ShortBufferException, IllegalBlockSizeException, BadPaddingException {
if (output == null) {
throw new NullPointerException("output == null");
}
@@ -309,8 +310,8 @@ void appendToBuf(byte[] input, int inputOffset, int inputLen) {
}
@Override
- int updateInternal(byte[] input, int inputOffset, int inputLen, byte[] output,
- int outputOffset, int maximumLen) throws ShortBufferException {
+ int updateInternal(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset,
+ int maximumLen) throws ShortBufferException {
checkInitialization();
appendToBuf(input, inputOffset, inputLen);
return 0;
@@ -321,8 +322,8 @@ private void throwAEADBadTagExceptionIfAvailable(String message, Throwable cause
throws BadPaddingException {
Constructor> aeadBadTagConstructor;
try {
- aeadBadTagConstructor = Class.forName("javax.crypto.AEADBadTagException")
- .getConstructor(String.class);
+ aeadBadTagConstructor =
+ Class.forName("javax.crypto.AEADBadTagException").getConstructor(String.class);
} catch (Exception ignored) {
return;
}
@@ -336,8 +337,7 @@ private void throwAEADBadTagExceptionIfAvailable(String message, Throwable cause
} catch (InstantiationException e2) {
// Fall through
} catch (InvocationTargetException e2) {
- throw(BadPaddingException) new BadPaddingException().initCause(
- e2.getTargetException());
+ throw(BadPaddingException) new BadPaddingException().initCause(e2.getTargetException());
}
if (badTagException != null) {
throw badTagException;
@@ -378,8 +378,8 @@ int doFinalInternal(ByteBuffer input, ByteBuffer output)
return bytesWritten;
}
- int doFinalInternal(byte[] input, int inputOffset, int inputLen,
- byte[] output, int outputOffset)
+ int doFinalInternal(byte[] input, int inputOffset, int inputLen, byte[] output,
+ int outputOffset)
throws ShortBufferException, IllegalBlockSizeException, BadPaddingException {
checkInitialization();
@@ -398,9 +398,9 @@ int doFinalInternal(byte[] input, int inputOffset, int inputLen,
in = EmptyArray.BYTE; // input can be null when inputLen == 0
inOffset = inputOffset;
} else if (input == output
- && ((inputOffset + inputLen > outputOffset && inputOffset <= outputOffset)
- || (inputOffset >= outputOffset
- && outputOffset + inputLen + tagLengthInBytes > inputOffset))) {
+ && ((inputOffset + inputLen > outputOffset && inputOffset <= outputOffset)
+ || (inputOffset >= outputOffset
+ && outputOffset + inputLen + tagLengthInBytes > inputOffset))) {
// BoringSSL requires that input and output do not overlap. To be on the safe side,
// we copy the input to a new array.
in = Arrays.copyOfRange(input, inputOffset, inputOffset + inputLen);
@@ -416,11 +416,13 @@ int doFinalInternal(byte[] input, int inputOffset, int inputLen,
final int bytesWritten;
try {
if (isEncrypting()) {
- bytesWritten = NativeCrypto.EVP_AEAD_CTX_seal(evpAead, encodedKey,
- tagLengthInBytes, output, outputOffset, iv, in, inOffset, inLen, aad);
+ bytesWritten = NativeCrypto.EVP_AEAD_CTX_seal(evpAead, encodedKey, tagLengthInBytes,
+ output, outputOffset, iv, in,
+ inOffset, inLen, aad);
} else {
- bytesWritten = NativeCrypto.EVP_AEAD_CTX_open(evpAead, encodedKey,
- tagLengthInBytes, output, outputOffset, iv, in, inOffset, inLen, aad);
+ bytesWritten = NativeCrypto.EVP_AEAD_CTX_open(evpAead, encodedKey, tagLengthInBytes,
+ output, outputOffset, iv, in,
+ inOffset, inLen, aad);
}
} catch (BadPaddingException e) {
throwAEADBadTagExceptionIfAvailable(e.getMessage(), e.getCause());
diff --git a/common/src/main/java/org/conscrypt/OpenSSLContextImpl.java b/common/src/main/java/org/conscrypt/OpenSSLContextImpl.java
index 802506603..755d63cd8 100644
--- a/common/src/main/java/org/conscrypt/OpenSSLContextImpl.java
+++ b/common/src/main/java/org/conscrypt/OpenSSLContextImpl.java
@@ -67,6 +67,10 @@ public static OpenSSLContextImpl getPreferred() {
serverSessionContext = new ServerSessionContext();
}
+ private OpenSSLContextImpl() throws GeneralSecurityException, IOException {
+ this(NativeCrypto.TLSV13_PROTOCOLS, true);
+ }
+
/**
* Constructor for the DefaultSSLContextImpl. The unused boolean parameter is solely to
* indicate that this constructor is desired.
@@ -92,9 +96,10 @@ public static OpenSSLContextImpl getPreferred() {
(ServerSessionContext)
defaultSslContextImpl.engineGetServerSessionContext();
}
- sslParameters = new SSLParametersImpl(defaultSslContextImpl.getKeyManagers(),
- defaultSslContextImpl.getTrustManagers(), null, clientSessionContext,
- serverSessionContext, protocols);
+ sslParameters =
+ new SSLParametersImpl(defaultSslContextImpl.getKeyManagers(),
+ defaultSslContextImpl.getTrustManagers(), null,
+ clientSessionContext, serverSessionContext, protocols);
}
}
@@ -111,8 +116,8 @@ public static OpenSSLContextImpl getPreferred() {
@Override
public void engineInit(KeyManager[] kms, TrustManager[] tms, SecureRandom sr)
throws KeyManagementException {
- sslParameters = new SSLParametersImpl(
- kms, tms, sr, clientSessionContext, serverSessionContext, protocols);
+ sslParameters = new SSLParametersImpl(kms, tms, sr, clientSessionContext,
+ serverSessionContext, protocols);
}
@Override
diff --git a/common/src/main/java/org/conscrypt/OpenSSLProvider.java b/common/src/main/java/org/conscrypt/OpenSSLProvider.java
index e3a158073..71fdc5cf0 100644
--- a/common/src/main/java/org/conscrypt/OpenSSLProvider.java
+++ b/common/src/main/java/org/conscrypt/OpenSSLProvider.java
@@ -52,18 +52,16 @@ public OpenSSLProvider() {
@SuppressWarnings("deprecation")
public OpenSSLProvider(String providerName) {
this(providerName, Platform.provideTrustManagerByDefault(), "TLSv1.3",
- Platform.isTlsV1Deprecated(), Platform.isTlsV1Supported());
+ Platform.isTlsV1Deprecated(), Platform.isTlsV1Supported());
}
- OpenSSLProvider(String providerName, boolean includeTrustManager,
- String defaultTlsProtocol) {
+ OpenSSLProvider(String providerName, boolean includeTrustManager, String defaultTlsProtocol) {
this(providerName, includeTrustManager, defaultTlsProtocol, Platform.isTlsV1Deprecated(),
- Platform.isTlsV1Supported());
+ Platform.isTlsV1Supported());
}
- OpenSSLProvider(String providerName, boolean includeTrustManager,
- String defaultTlsProtocol, boolean deprecatedTlsV1,
- boolean enabledTlsV1) {
+ OpenSSLProvider(String providerName, boolean includeTrustManager, String defaultTlsProtocol,
+ boolean deprecatedTlsV1, boolean enabledTlsV1) {
super(providerName, 1.0, "Android's OpenSSL-backed security provider");
// Ensure that the native library has been loaded.
@@ -88,8 +86,8 @@ public OpenSSLProvider(String providerName) {
defaultSSLContextSuffix = tls13SSLContextSuffix;
break;
default:
- throw new IllegalArgumentException(
- "Choice of default protocol is unsupported: " + defaultTlsProtocol);
+ throw new IllegalArgumentException("Choice of default protocol is unsupported: "
+ + defaultTlsProtocol);
}
// Keep SSL as an alias to TLS
put("SSLContext.SSL", classOpenSSLContextImpl + defaultSSLContextSuffix);
@@ -295,36 +293,30 @@ public OpenSSLProvider(String providerName) {
put("Alg.Alias.Signature.SHA224/RSA", "SHA224withRSA");
put("Alg.Alias.Signature.1.2.840.113549.1.1.14", "SHA224withRSA");
put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.14", "SHA224withRSA");
- put("Alg.Alias.Signature.2.16.840.1.101.3.4.2.4with1.2.840.113549.1.1.1",
- "SHA224withRSA");
- put("Alg.Alias.Signature.2.16.840.1.101.3.4.2.4with1.2.840.113549.1.1.14",
- "SHA224withRSA");
+ put("Alg.Alias.Signature.2.16.840.1.101.3.4.2.4with1.2.840.113549.1.1.1", "SHA224withRSA");
+ put("Alg.Alias.Signature.2.16.840.1.101.3.4.2.4with1.2.840.113549.1.1.14", "SHA224withRSA");
putSignatureImplClass("SHA256withRSA", "OpenSSLSignature$SHA256RSA");
put("Alg.Alias.Signature.SHA256withRSAEncryption", "SHA256withRSA");
put("Alg.Alias.Signature.SHA256/RSA", "SHA256withRSA");
put("Alg.Alias.Signature.1.2.840.113549.1.1.11", "SHA256withRSA");
put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.11", "SHA256withRSA");
- put("Alg.Alias.Signature.2.16.840.1.101.3.4.2.1with1.2.840.113549.1.1.1",
- "SHA256withRSA");
- put("Alg.Alias.Signature.2.16.840.1.101.3.4.2.1with1.2.840.113549.1.1.11",
- "SHA256withRSA");
+ put("Alg.Alias.Signature.2.16.840.1.101.3.4.2.1with1.2.840.113549.1.1.1", "SHA256withRSA");
+ put("Alg.Alias.Signature.2.16.840.1.101.3.4.2.1with1.2.840.113549.1.1.11", "SHA256withRSA");
putSignatureImplClass("SHA384withRSA", "OpenSSLSignature$SHA384RSA");
put("Alg.Alias.Signature.SHA384withRSAEncryption", "SHA384withRSA");
put("Alg.Alias.Signature.SHA384/RSA", "SHA384withRSA");
put("Alg.Alias.Signature.1.2.840.113549.1.1.12", "SHA384withRSA");
put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.12", "SHA384withRSA");
- put("Alg.Alias.Signature.2.16.840.1.101.3.4.2.2with1.2.840.113549.1.1.1",
- "SHA384withRSA");
+ put("Alg.Alias.Signature.2.16.840.1.101.3.4.2.2with1.2.840.113549.1.1.1", "SHA384withRSA");
putSignatureImplClass("SHA512withRSA", "OpenSSLSignature$SHA512RSA");
put("Alg.Alias.Signature.SHA512withRSAEncryption", "SHA512withRSA");
put("Alg.Alias.Signature.SHA512/RSA", "SHA512withRSA");
put("Alg.Alias.Signature.1.2.840.113549.1.1.13", "SHA512withRSA");
put("Alg.Alias.Signature.OID.1.2.840.113549.1.1.13", "SHA512withRSA");
- put("Alg.Alias.Signature.2.16.840.1.101.3.4.2.3with1.2.840.113549.1.1.1",
- "SHA512withRSA");
+ put("Alg.Alias.Signature.2.16.840.1.101.3.4.2.3with1.2.840.113549.1.1.1", "SHA512withRSA");
putRAWRSASignatureImplClass("OpenSSLSignatureRawRSA");
@@ -416,23 +408,23 @@ public OpenSSLProvider(String providerName) {
put("Alg.Alias.Cipher.RSA/None/OAEPPadding", "RSA/ECB/OAEPPadding");
putRSACipherImplClass("RSA/ECB/OAEPWithSHA-1AndMGF1Padding", "OpenSSLCipherRSA$OAEP$SHA1");
put("Alg.Alias.Cipher.RSA/None/OAEPWithSHA-1AndMGF1Padding",
- "RSA/ECB/OAEPWithSHA-1AndMGF1Padding");
- putRSACipherImplClass(
- "RSA/ECB/OAEPWithSHA-224AndMGF1Padding", "OpenSSLCipherRSA$OAEP$SHA224");
+ "RSA/ECB/OAEPWithSHA-1AndMGF1Padding");
+ putRSACipherImplClass("RSA/ECB/OAEPWithSHA-224AndMGF1Padding",
+ "OpenSSLCipherRSA$OAEP$SHA224");
put("Alg.Alias.Cipher.RSA/None/OAEPWithSHA-224AndMGF1Padding",
- "RSA/ECB/OAEPWithSHA-224AndMGF1Padding");
- putRSACipherImplClass(
- "RSA/ECB/OAEPWithSHA-256AndMGF1Padding", "OpenSSLCipherRSA$OAEP$SHA256");
+ "RSA/ECB/OAEPWithSHA-224AndMGF1Padding");
+ putRSACipherImplClass("RSA/ECB/OAEPWithSHA-256AndMGF1Padding",
+ "OpenSSLCipherRSA$OAEP$SHA256");
put("Alg.Alias.Cipher.RSA/None/OAEPWithSHA-256AndMGF1Padding",
- "RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
- putRSACipherImplClass(
- "RSA/ECB/OAEPWithSHA-384AndMGF1Padding", "OpenSSLCipherRSA$OAEP$SHA384");
+ "RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
+ putRSACipherImplClass("RSA/ECB/OAEPWithSHA-384AndMGF1Padding",
+ "OpenSSLCipherRSA$OAEP$SHA384");
put("Alg.Alias.Cipher.RSA/None/OAEPWithSHA-384AndMGF1Padding",
- "RSA/ECB/OAEPWithSHA-384AndMGF1Padding");
- putRSACipherImplClass(
- "RSA/ECB/OAEPWithSHA-512AndMGF1Padding", "OpenSSLCipherRSA$OAEP$SHA512");
+ "RSA/ECB/OAEPWithSHA-384AndMGF1Padding");
+ putRSACipherImplClass("RSA/ECB/OAEPWithSHA-512AndMGF1Padding",
+ "OpenSSLCipherRSA$OAEP$SHA512");
put("Alg.Alias.Cipher.RSA/None/OAEPWithSHA-512AndMGF1Padding",
- "RSA/ECB/OAEPWithSHA-512AndMGF1Padding");
+ "RSA/ECB/OAEPWithSHA-512AndMGF1Padding");
/*
* OpenSSL only supports a subset of modes, so we'll name them
@@ -447,27 +439,25 @@ public OpenSSLProvider(String providerName) {
* than 64 bits. We solve this confusion by making PKCS7Padding an
* alias for PKCS5Padding.
*/
- putSymmetricCipherImplClass("AES/ECB/NoPadding",
- "OpenSSLEvpCipherAES$AES$ECB$NoPadding");
+ putSymmetricCipherImplClass("AES/ECB/NoPadding", "OpenSSLEvpCipherAES$AES$ECB$NoPadding");
putSymmetricCipherImplClass("AES/ECB/PKCS5Padding",
- "OpenSSLEvpCipherAES$AES$ECB$PKCS5Padding");
+ "OpenSSLEvpCipherAES$AES$ECB$PKCS5Padding");
put("Alg.Alias.Cipher.AES/ECB/PKCS7Padding", "AES/ECB/PKCS5Padding");
- putSymmetricCipherImplClass("AES/CBC/NoPadding",
- "OpenSSLEvpCipherAES$AES$CBC$NoPadding");
+ putSymmetricCipherImplClass("AES/CBC/NoPadding", "OpenSSLEvpCipherAES$AES$CBC$NoPadding");
putSymmetricCipherImplClass("AES/CBC/PKCS5Padding",
- "OpenSSLEvpCipherAES$AES$CBC$PKCS5Padding");
+ "OpenSSLEvpCipherAES$AES$CBC$PKCS5Padding");
put("Alg.Alias.Cipher.AES/CBC/PKCS7Padding", "AES/CBC/PKCS5Padding");
putSymmetricCipherImplClass("AES/CTR/NoPadding", "OpenSSLEvpCipherAES$AES$CTR");
- putSymmetricCipherImplClass(
- "AES_128/ECB/NoPadding", "OpenSSLEvpCipherAES$AES_128$ECB$NoPadding");
- putSymmetricCipherImplClass(
- "AES_128/ECB/PKCS5Padding", "OpenSSLEvpCipherAES$AES_128$ECB$PKCS5Padding");
+ putSymmetricCipherImplClass("AES_128/ECB/NoPadding",
+ "OpenSSLEvpCipherAES$AES_128$ECB$NoPadding");
+ putSymmetricCipherImplClass("AES_128/ECB/PKCS5Padding",
+ "OpenSSLEvpCipherAES$AES_128$ECB$PKCS5Padding");
put("Alg.Alias.Cipher.AES_128/ECB/PKCS7Padding", "AES_128/ECB/PKCS5Padding");
- putSymmetricCipherImplClass(
- "AES_128/CBC/NoPadding", "OpenSSLEvpCipherAES$AES_128$CBC$NoPadding");
- putSymmetricCipherImplClass(
- "AES_128/CBC/PKCS5Padding", "OpenSSLEvpCipherAES$AES_128$CBC$PKCS5Padding");
+ putSymmetricCipherImplClass("AES_128/CBC/NoPadding",
+ "OpenSSLEvpCipherAES$AES_128$CBC$NoPadding");
+ putSymmetricCipherImplClass("AES_128/CBC/PKCS5Padding",
+ "OpenSSLEvpCipherAES$AES_128$CBC$PKCS5Padding");
put("Alg.Alias.Cipher.AES_128/CBC/PKCS7Padding", "AES_128/CBC/PKCS5Padding");
put("Alg.Alias.Cipher.PBEWithHmacSHA1AndAES_128", "AES_128/CBC/PKCS5PADDING");
@@ -476,15 +466,15 @@ public OpenSSLProvider(String providerName) {
put("Alg.Alias.Cipher.PBEWithHmacSHA384AndAES_128", "AES_128/CBC/PKCS5PADDING");
put("Alg.Alias.Cipher.PBEWithHmacSHA512AndAES_128", "AES_128/CBC/PKCS5PADDING");
- putSymmetricCipherImplClass(
- "AES_256/ECB/NoPadding", "OpenSSLEvpCipherAES$AES_256$ECB$NoPadding");
- putSymmetricCipherImplClass(
- "AES_256/ECB/PKCS5Padding", "OpenSSLEvpCipherAES$AES_256$ECB$PKCS5Padding");
+ putSymmetricCipherImplClass("AES_256/ECB/NoPadding",
+ "OpenSSLEvpCipherAES$AES_256$ECB$NoPadding");
+ putSymmetricCipherImplClass("AES_256/ECB/PKCS5Padding",
+ "OpenSSLEvpCipherAES$AES_256$ECB$PKCS5Padding");
put("Alg.Alias.Cipher.AES_256/ECB/PKCS7Padding", "AES_256/ECB/PKCS5Padding");
- putSymmetricCipherImplClass(
- "AES_256/CBC/NoPadding", "OpenSSLEvpCipherAES$AES_256$CBC$NoPadding");
- putSymmetricCipherImplClass(
- "AES_256/CBC/PKCS5Padding", "OpenSSLEvpCipherAES$AES_256$CBC$PKCS5Padding");
+ putSymmetricCipherImplClass("AES_256/CBC/NoPadding",
+ "OpenSSLEvpCipherAES$AES_256$CBC$NoPadding");
+ putSymmetricCipherImplClass("AES_256/CBC/PKCS5Padding",
+ "OpenSSLEvpCipherAES$AES_256$CBC$PKCS5Padding");
put("Alg.Alias.Cipher.AES_256/CBC/PKCS7Padding", "AES_256/CBC/PKCS5Padding");
put("Alg.Alias.Cipher.PBEWithHmacSHA1AndAES_256", "AES_256/CBC/PKCS5PADDING");
@@ -493,10 +483,9 @@ public OpenSSLProvider(String providerName) {
put("Alg.Alias.Cipher.PBEWithHmacSHA384AndAES_256", "AES_256/CBC/PKCS5PADDING");
put("Alg.Alias.Cipher.PBEWithHmacSHA512AndAES_256", "AES_256/CBC/PKCS5PADDING");
- putSymmetricCipherImplClass("DESEDE/CBC/NoPadding",
- "OpenSSLEvpCipherDESEDE$CBC$NoPadding");
+ putSymmetricCipherImplClass("DESEDE/CBC/NoPadding", "OpenSSLEvpCipherDESEDE$CBC$NoPadding");
putSymmetricCipherImplClass("DESEDE/CBC/PKCS5Padding",
- "OpenSSLEvpCipherDESEDE$CBC$PKCS5Padding");
+ "OpenSSLEvpCipherDESEDE$CBC$PKCS5Padding");
put("Alg.Alias.Cipher.DESEDE/CBC/PKCS7Padding", "DESEDE/CBC/PKCS5Padding");
putSymmetricCipherImplClass("ARC4", "OpenSSLEvpCipherARC4");
@@ -510,21 +499,17 @@ public OpenSSLProvider(String providerName) {
put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.6", "AES/GCM/NoPadding");
put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.26", "AES/GCM/NoPadding");
put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.46", "AES/GCM/NoPadding");
- putSymmetricCipherImplClass(
- "AES_128/GCM/NoPadding", "OpenSSLAeadCipherAES$GCM$AES_128");
- putSymmetricCipherImplClass(
- "AES_256/GCM/NoPadding", "OpenSSLAeadCipherAES$GCM$AES_256");
+ putSymmetricCipherImplClass("AES_128/GCM/NoPadding", "OpenSSLAeadCipherAES$GCM$AES_128");
+ putSymmetricCipherImplClass("AES_256/GCM/NoPadding", "OpenSSLAeadCipherAES$GCM$AES_256");
putSymmetricCipherImplClass("AES/GCM-SIV/NoPadding", "OpenSSLAeadCipherAES$GCM_SIV");
- putSymmetricCipherImplClass(
- "AES_128/GCM-SIV/NoPadding", "OpenSSLAeadCipherAES$GCM_SIV$AES_128");
- putSymmetricCipherImplClass(
- "AES_256/GCM-SIV/NoPadding", "OpenSSLAeadCipherAES$GCM_SIV$AES_256");
-
- putSymmetricCipherImplClass("ChaCha20",
- "OpenSSLCipherChaCha20");
- putSymmetricCipherImplClass("ChaCha20/Poly1305/NoPadding",
- "OpenSSLAeadCipherChaCha20");
+ putSymmetricCipherImplClass("AES_128/GCM-SIV/NoPadding",
+ "OpenSSLAeadCipherAES$GCM_SIV$AES_128");
+ putSymmetricCipherImplClass("AES_256/GCM-SIV/NoPadding",
+ "OpenSSLAeadCipherAES$GCM_SIV$AES_256");
+
+ putSymmetricCipherImplClass("ChaCha20", "OpenSSLCipherChaCha20");
+ putSymmetricCipherImplClass("ChaCha20/Poly1305/NoPadding", "OpenSSLAeadCipherChaCha20");
put("Alg.Alias.Cipher.ChaCha20-Poly1305", "ChaCha20/Poly1305/NoPadding");
/* === Mac === */
@@ -580,26 +565,29 @@ public OpenSSLProvider(String providerName) {
put("Alg.Alias.CertificateFactory.X.509", "X509");
/* === HPKE === */
- String baseClass = classExists("android.crypto.hpke.HpkeSpi")
- ? PREFIX + "AndroidHpkeSpi"
- : PREFIX + "HpkeImpl";
+ // BEGIN google3-changed: b/393827797 - This logic was only correct in the Android platform.
+ // String baseClass = classExists("android.crypto.hpke.HpkeSpi")
+ // ? PREFIX + "AndroidHpkeSpi"
+ // : PREFIX + "HpkeImpl";
+ String baseClass = PREFIX + "HpkeImpl";
+ // END google3-changed: b/393827797 - This logic was only correct in the Android platform.
put("ConscryptHpke.DHKEM_X25519_HKDF_SHA256/HKDF_SHA256/AES_128_GCM",
- baseClass + "$X25519_AES_128");
+ baseClass + "$X25519_AES_128");
put("Alg.Alias.ConscryptHpke.DHKEM_X25519_HKDF_SHA256_HKDF_SHA256_AES_128_GCM",
- "DHKEM_X25519_HKDF_SHA256/HKDF_SHA256/AES_128_GCM");
+ "DHKEM_X25519_HKDF_SHA256/HKDF_SHA256/AES_128_GCM");
put("ConscryptHpke.DHKEM_X25519_HKDF_SHA256/HKDF_SHA256/AES_256_GCM",
- baseClass + "$X25519_AES_256");
+ baseClass + "$X25519_AES_256");
put("Alg.Alias.ConscryptHpke.DHKEM_X25519_HKDF_SHA256_HKDF_SHA256_AES_256_GCM",
- "DHKEM_X25519_HKDF_SHA256/HKDF_SHA256/AES_256_GCM");
+ "DHKEM_X25519_HKDF_SHA256/HKDF_SHA256/AES_256_GCM");
put("ConscryptHpke.DHKEM_X25519_HKDF_SHA256/HKDF_SHA256/CHACHA20POLY1305",
- baseClass + "$X25519_CHACHA20");
+ baseClass + "$X25519_CHACHA20");
put("Alg.Alias.ConscryptHpke.DHKEM_X25519_HKDF_SHA256_HKDF_SHA256_GhpkeCHACHA20POLY1305",
- "DHKEM_X25519_HKDF_SHA256/HKDF_SHA256/CHACHA20POLY1305");
+ "DHKEM_X25519_HKDF_SHA256/HKDF_SHA256/CHACHA20POLY1305");
put("ConscryptHpke.XWING/HKDF_SHA256/AES_128_GCM", baseClass + "$XwingHkdfSha256Aes128Gcm");
put("ConscryptHpke.XWING/HKDF_SHA256/AES_256_GCM", baseClass + "$XwingHkdfSha256Aes256Gcm");
put("ConscryptHpke.XWING/HKDF_SHA256/CHACHA20POLY1305",
- baseClass + "$XwingHkdfSha256ChaCha20Poly1305");
+ baseClass + "$XwingHkdfSha256ChaCha20Poly1305");
/* === PAKE === */
if (Platform.isPakeSupported()) {
@@ -623,11 +611,8 @@ private void putMacImplClass(String algorithm, String className) {
// * the key provides its key material in "RAW" encoding via Key.getEncoded.
String supportedKeyClasses = PREFIX + "OpenSSLKeyHolder";
String supportedKeyFormats = "RAW";
- putImplClassWithKeyConstraints(
- "Mac." + algorithm,
- PREFIX + className,
- supportedKeyClasses,
- supportedKeyFormats);
+ putImplClassWithKeyConstraints("Mac." + algorithm, PREFIX + className, supportedKeyClasses,
+ supportedKeyFormats);
}
private void putSymmetricCipherImplClass(String transformation, String className) {
@@ -635,11 +620,8 @@ private void putSymmetricCipherImplClass(String transformation, String className
// * the key provides its key material in "RAW" encoding via Key.getEncoded.
String supportedKeyClasses = null; // ignored -- filtered based on encoding format only
String supportedKeyFormats = "RAW";
- putImplClassWithKeyConstraints(
- "Cipher." + transformation,
- PREFIX + className,
- supportedKeyClasses,
- supportedKeyFormats);
+ putImplClassWithKeyConstraints("Cipher." + transformation, PREFIX + className,
+ supportedKeyClasses, supportedKeyFormats);
}
private void putRSACipherImplClass(String transformation, String className) {
@@ -647,15 +629,12 @@ private void putRSACipherImplClass(String transformation, String className) {
// * the key is instance of OpenSSLRSAPrivateKey, RSAPrivateKey, OpenSSLRSAPublicKey, or
// RSAPublicKey.
String supportedKeyClasses = PREFIX + "OpenSSLRSAPrivateKey"
- + "|" + STANDARD_RSA_PRIVATE_KEY_INTERFACE_CLASS_NAME
- + "|" + PREFIX + "OpenSSLRSAPublicKey"
+ + "|" + STANDARD_RSA_PRIVATE_KEY_INTERFACE_CLASS_NAME + "|" + PREFIX
+ + "OpenSSLRSAPublicKey"
+ "|" + STANDARD_RSA_PUBLIC_KEY_INTERFACE_CLASS_NAME;
String supportedKeyFormats = null; // ignored -- filtered based on class only
- putImplClassWithKeyConstraints(
- "Cipher." + transformation,
- PREFIX + className,
- supportedKeyClasses,
- supportedKeyFormats);
+ putImplClassWithKeyConstraints("Cipher." + transformation, PREFIX + className,
+ supportedKeyClasses, supportedKeyFormats);
}
private void putSignatureImplClass(String algorithm, String className) {
@@ -667,15 +646,12 @@ private void putSignatureImplClass(String algorithm, String className) {
// transparent public keys -- it only accepts them if they provide their key material in
// encoded form (see above).
String supportedKeyClasses = PREFIX + "OpenSSLKeyHolder"
- + "|" + STANDARD_RSA_PRIVATE_KEY_INTERFACE_CLASS_NAME
- + "|" + STANDARD_EC_PRIVATE_KEY_INTERFACE_CLASS_NAME
- + "|" + STANDARD_RSA_PUBLIC_KEY_INTERFACE_CLASS_NAME;
+ + "|" + STANDARD_RSA_PRIVATE_KEY_INTERFACE_CLASS_NAME + "|"
+ + STANDARD_EC_PRIVATE_KEY_INTERFACE_CLASS_NAME + "|"
+ + STANDARD_RSA_PUBLIC_KEY_INTERFACE_CLASS_NAME;
String supportedKeyFormats = "PKCS#8|X.509";
- putImplClassWithKeyConstraints(
- "Signature." + algorithm,
- PREFIX + className,
- supportedKeyClasses,
- supportedKeyFormats);
+ putImplClassWithKeyConstraints("Signature." + algorithm, PREFIX + className,
+ supportedKeyClasses, supportedKeyFormats);
}
private void putRAWRSASignatureImplClass(String className) {
@@ -683,15 +659,12 @@ private void putRAWRSASignatureImplClass(String className) {
// * the key is instance of OpenSSLRSAPrivateKey, RSAPrivateKey, OpenSSLRSAPublicKey, or
// RSAPublicKey.
String supportedKeyClasses = PREFIX + "OpenSSLRSAPrivateKey"
- + "|" + STANDARD_RSA_PRIVATE_KEY_INTERFACE_CLASS_NAME
- + "|" + PREFIX + "OpenSSLRSAPublicKey"
+ + "|" + STANDARD_RSA_PRIVATE_KEY_INTERFACE_CLASS_NAME + "|" + PREFIX
+ + "OpenSSLRSAPublicKey"
+ "|" + STANDARD_RSA_PUBLIC_KEY_INTERFACE_CLASS_NAME;
String supportedKeyFormats = null; // ignored -- filtered based on class only
- putImplClassWithKeyConstraints(
- "Signature.NONEwithRSA",
- PREFIX + className,
- supportedKeyClasses,
- supportedKeyFormats);
+ putImplClassWithKeyConstraints("Signature.NONEwithRSA", PREFIX + className,
+ supportedKeyClasses, supportedKeyFormats);
}
private void putECDHKeyAgreementImplClass(String className) {
@@ -702,11 +675,8 @@ private void putECDHKeyAgreementImplClass(String className) {
String supportedKeyClasses = PREFIX + "OpenSSLKeyHolder"
+ "|" + STANDARD_EC_PRIVATE_KEY_INTERFACE_CLASS_NAME;
String supportedKeyFormats = "PKCS#8";
- putImplClassWithKeyConstraints(
- "KeyAgreement.ECDH",
- PREFIX + className,
- supportedKeyClasses,
- supportedKeyFormats);
+ putImplClassWithKeyConstraints("KeyAgreement.ECDH", PREFIX + className, supportedKeyClasses,
+ supportedKeyFormats);
}
private void putXDHKeyAgreementImplClass(String className) {
@@ -715,22 +685,19 @@ private void putXDHKeyAgreementImplClass(String className) {
// * the key provides its key material in "PKCS#8" encoding via Key.getEncoded.
// * the key is a transparent XEC private key (subclass of XECPrivateKey).
String supportedKeyClasses = PREFIX + "OpenSSLKeyHolder"
- + "|" + STANDARD_XEC_PRIVATE_KEY_INTERFACE_CLASS_NAME
- + "|" + PREFIX + "OpenSSLX25519PrivateKey";
+ + "|" + STANDARD_XEC_PRIVATE_KEY_INTERFACE_CLASS_NAME + "|" + PREFIX
+ + "OpenSSLX25519PrivateKey";
String supportedKeyFormats = "PKCS#8";
- putImplClassWithKeyConstraints(
- "KeyAgreement.XDH",
- PREFIX + className,
- supportedKeyClasses,
- supportedKeyFormats);
+ putImplClassWithKeyConstraints("KeyAgreement.XDH", PREFIX + className, supportedKeyClasses,
+ supportedKeyFormats);
put("Alg.Alias.KeyAgreement.X25519", "XDH");
}
private void putImplClassWithKeyConstraints(String typeAndAlgName,
- String fullyQualifiedClassName,
- String supportedKeyClasses,
- String supportedKeyFormats) {
+ String fullyQualifiedClassName,
+ String supportedKeyClasses,
+ String supportedKeyFormats) {
put(typeAndAlgName, fullyQualifiedClassName);
if (supportedKeyClasses != null) {
put(typeAndAlgName + " SupportedKeyClasses", supportedKeyClasses);
diff --git a/common/src/main/java/org/conscrypt/OpenSSLSocketImpl.java b/common/src/main/java/org/conscrypt/OpenSSLSocketImpl.java
index f0c2571e1..327f77e3c 100644
--- a/common/src/main/java/org/conscrypt/OpenSSLSocketImpl.java
+++ b/common/src/main/java/org/conscrypt/OpenSSLSocketImpl.java
@@ -22,6 +22,7 @@
import java.net.Socket;
import java.net.SocketException;
import java.security.PrivateKey;
+
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
@@ -31,8 +32,7 @@
*/
@Internal
public abstract class OpenSSLSocketImpl extends AbstractConscryptSocket {
- OpenSSLSocketImpl() throws IOException {
- }
+ OpenSSLSocketImpl() throws IOException {}
OpenSSLSocketImpl(String hostname, int port) throws IOException {
super(hostname, port);
@@ -43,18 +43,17 @@ public abstract class OpenSSLSocketImpl extends AbstractConscryptSocket {
}
OpenSSLSocketImpl(String hostname, int port, InetAddress clientAddress, int clientPort)
- throws IOException {
+ throws IOException {
super(hostname, port, clientAddress, clientPort);
}
- OpenSSLSocketImpl(InetAddress address, int port, InetAddress clientAddress,
- int clientPort)
- throws IOException {
+ OpenSSLSocketImpl(InetAddress address, int port, InetAddress clientAddress, int clientPort)
+ throws IOException {
super(address, port, clientAddress, clientPort);
}
OpenSSLSocketImpl(Socket socket, String hostname, int port, boolean autoClose)
- throws IOException {
+ throws IOException {
super(socket, hostname, port, autoClose);
}
@@ -93,20 +92,17 @@ public void setHandshakeTimeout(int handshakeTimeoutMilliseconds) throws SocketE
super.setHandshakeTimeout(handshakeTimeoutMilliseconds);
}
- @Override
- public abstract SSLSession getHandshakeSession();
+ @Override public abstract SSLSession getHandshakeSession();
- @Override
- public abstract void setUseSessionTickets(boolean useSessionTickets);
+ @Override public abstract void setUseSessionTickets(boolean useSessionTickets);
- @Override
- public abstract void setChannelIdEnabled(boolean enabled);
+ @Override public abstract void setEchConfigList(byte[] echConfigList);
- @Override
- public abstract byte[] getChannelId() throws SSLException;
+ @Override public abstract void setChannelIdEnabled(boolean enabled);
- @Override
- public abstract void setChannelIdPrivateKey(PrivateKey privateKey);
+ @Override public abstract byte[] getChannelId() throws SSLException;
+
+ @Override public abstract void setChannelIdPrivateKey(PrivateKey privateKey);
/**
* @deprecated NPN is not supported
@@ -122,8 +118,7 @@ public final byte[] getNpnSelectedProtocol() {
*/
@Deprecated
@SuppressWarnings("InlineMeSuggester")
- public final void setNpnProtocols(byte[] npnProtocols) {
- }
+ public final void setNpnProtocols(byte[] npnProtocols) {}
/**
* @deprecated use {@link #setApplicationProtocols(String[])} instead.
@@ -149,7 +144,8 @@ public final byte[] getAlpnSelectedProtocol() {
@Override
@Deprecated
public final void setAlpnProtocols(byte[] protocols) {
- setApplicationProtocols(SSLUtils.decodeProtocols(protocols == null ? EmptyArray.BYTE : protocols));
+ setApplicationProtocols(
+ SSLUtils.decodeProtocols(protocols == null ? EmptyArray.BYTE : protocols));
}
@Override public abstract String getCurveNameForTesting();
diff --git a/common/src/main/java/org/conscrypt/OpenSSLX25519PrivateKey.java b/common/src/main/java/org/conscrypt/OpenSSLX25519PrivateKey.java
index e816d2df0..af7bb7767 100644
--- a/common/src/main/java/org/conscrypt/OpenSSLX25519PrivateKey.java
+++ b/common/src/main/java/org/conscrypt/OpenSSLX25519PrivateKey.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2022 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,19 +29,18 @@
public class OpenSSLX25519PrivateKey implements OpenSSLX25519Key, PrivateKey {
private static final long serialVersionUID = -3136201500221850916L;
- private static final byte[] PKCS8_PREAMBLE = new byte[]{
- 0x30, 0x2e, // Sequence: 46 bytes
- 0x02, 0x01, 0x00, // Integer: 0 (version)
- 0x30, 0x05, // Sequence: 5 bytes
- 0x06, 0x03, 0x2b, 0x65, 0x6e, // OID: 1.3.101.110 (X25519)
- 0x04, 0x22, 0x04, 0x20, // Octet string: 32 bytes
+ private static final byte[] PKCS8_PREAMBLE = new byte[] {
+ 0x30, 0x2e, // Sequence: 46 bytes
+ 0x02, 0x01, 0x00, // Integer: 0 (version)
+ 0x30, 0x05, // Sequence: 5 bytes
+ 0x06, 0x03, 0x2b, 0x65, 0x6e, // OID: 1.3.101.110 (X25519)
+ 0x04, 0x22, 0x04, 0x20, // Octet string: 32 bytes
// Key bytes follow directly
};
private byte[] uCoordinate;
- public OpenSSLX25519PrivateKey(EncodedKeySpec keySpec)
- throws InvalidKeySpecException {
+ public OpenSSLX25519PrivateKey(EncodedKeySpec keySpec) throws InvalidKeySpecException {
byte[] encoded = keySpec.getEncoded();
if ("PKCS#8".equals(keySpec.getFormat())) {
try {
@@ -107,8 +106,10 @@ public boolean isDestroyed() {
@Override
public boolean equals(Object o) {
- if (this == o) return true;
- if (!(o instanceof OpenSSLX25519PrivateKey)) return false;
+ if (this == o)
+ return true;
+ if (!(o instanceof OpenSSLX25519PrivateKey))
+ return false;
OpenSSLX25519PrivateKey that = (OpenSSLX25519PrivateKey) o;
return Arrays.equals(uCoordinate, that.uCoordinate);
}
diff --git a/common/src/main/java/org/conscrypt/OpenSSLX25519PublicKey.java b/common/src/main/java/org/conscrypt/OpenSSLX25519PublicKey.java
index 246ff64f0..ddeed1f51 100644
--- a/common/src/main/java/org/conscrypt/OpenSSLX25519PublicKey.java
+++ b/common/src/main/java/org/conscrypt/OpenSSLX25519PublicKey.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2022 The Android Open Source Project
+ * Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,10 +28,10 @@ public class OpenSSLX25519PublicKey implements OpenSSLX25519Key, PublicKey {
private static final long serialVersionUID = 453861992373478445L;
private static final byte[] X509_PREAMBLE = new byte[] {
- 0x30, 0x2a, // Sequence: 42 bytes
- 0x30, 0x05, // Sequence: 5 bytes
- 0x06, 0x03, 0x2b, 0x65, 0x6e, // OID: 1.3.101.110 (X25519)
- 0x03, 0x21, 0x00, // Bit string: 256 bits
+ 0x30, 0x2a, // Sequence: 42 bytes
+ 0x30, 0x05, // Sequence: 5 bytes
+ 0x06, 0x03, 0x2b, 0x65, 0x6e, // OID: 1.3.101.110 (X25519)
+ 0x03, 0x21, 0x00, // Bit string: 256 bits
// Key bytes follow directly
};
@@ -98,8 +98,10 @@ public boolean equals(Object o) {
throw new IllegalStateException("key is destroyed");
}
- if (this == o) return true;
- if (!(o instanceof OpenSSLX25519PublicKey)) return false;
+ if (this == o)
+ return true;
+ if (!(o instanceof OpenSSLX25519PublicKey))
+ return false;
OpenSSLX25519PublicKey that = (OpenSSLX25519PublicKey) o;
return Arrays.equals(uCoordinate, that.uCoordinate);
}
diff --git a/common/src/main/java/org/conscrypt/OpenSSLX509CRLEntry.java b/common/src/main/java/org/conscrypt/OpenSSLX509CRLEntry.java
index d798dafb6..b778e69a8 100644
--- a/common/src/main/java/org/conscrypt/OpenSSLX509CRLEntry.java
+++ b/common/src/main/java/org/conscrypt/OpenSSLX509CRLEntry.java
@@ -31,7 +31,7 @@
* An implementation of {@link X509CRLEntry} based on BoringSSL.
*/
final class OpenSSLX509CRLEntry extends X509CRLEntry {
- private final long mContext;
+ private long mContext;
private final Date revocationDate;
OpenSSLX509CRLEntry(long ctx) throws ParsingException {
@@ -53,10 +53,11 @@ public Set getCriticalExtensionOIDs() {
* non-critical extensions.
*/
if ((critOids.length == 0)
- && (NativeCrypto.get_X509_REVOKED_ext_oids(
- mContext, NativeCrypto.EXTENSION_TYPE_NON_CRITICAL, this)
- .length
- == 0)) {
+ && (NativeCrypto
+ .get_X509_REVOKED_ext_oids(mContext,
+ NativeCrypto.EXTENSION_TYPE_NON_CRITICAL, this)
+ .length
+ == 0)) {
return null;
}
@@ -79,10 +80,11 @@ public Set getNonCriticalExtensionOIDs() {
* check critical extensions.
*/
if ((critOids.length == 0)
- && (NativeCrypto.get_X509_REVOKED_ext_oids(
- mContext, NativeCrypto.EXTENSION_TYPE_CRITICAL, this)
- .length
- == 0)) {
+ && (NativeCrypto
+ .get_X509_REVOKED_ext_oids(mContext, NativeCrypto.EXTENSION_TYPE_CRITICAL,
+ this)
+ .length
+ == 0)) {
return null;
}
@@ -121,14 +123,16 @@ public Date getRevocationDate() {
@Override
public boolean hasExtensions() {
- return (NativeCrypto.get_X509_REVOKED_ext_oids(
- mContext, NativeCrypto.EXTENSION_TYPE_NON_CRITICAL, this)
- .length
- != 0)
- || (NativeCrypto.get_X509_REVOKED_ext_oids(
- mContext, NativeCrypto.EXTENSION_TYPE_CRITICAL, this)
- .length
- != 0);
+ return (NativeCrypto
+ .get_X509_REVOKED_ext_oids(mContext,
+ NativeCrypto.EXTENSION_TYPE_NON_CRITICAL, this)
+ .length
+ != 0)
+ || (NativeCrypto
+ .get_X509_REVOKED_ext_oids(mContext,
+ NativeCrypto.EXTENSION_TYPE_CRITICAL, this)
+ .length
+ != 0);
}
@Override
diff --git a/common/src/main/java/org/conscrypt/OpenSslXwingKeyFactory.java b/common/src/main/java/org/conscrypt/OpenSslXwingKeyFactory.java
index b8bdaa95e..4dcc801e8 100644
--- a/common/src/main/java/org/conscrypt/OpenSslXwingKeyFactory.java
+++ b/common/src/main/java/org/conscrypt/OpenSslXwingKeyFactory.java
@@ -40,8 +40,8 @@ protected PublicKey engineGeneratePublic(KeySpec keySpec) throws InvalidKeySpecE
if (keySpec instanceof EncodedKeySpec) {
return new OpenSslXwingPublicKey((EncodedKeySpec) keySpec);
}
- throw new InvalidKeySpecException(
- "Currently only EncodedKeySpec is supported; was " + keySpec.getClass().getName());
+ throw new InvalidKeySpecException("Currently only EncodedKeySpec is supported; was "
+ + keySpec.getClass().getName());
}
@Override
@@ -52,8 +52,8 @@ protected PrivateKey engineGeneratePrivate(KeySpec keySpec) throws InvalidKeySpe
if (keySpec instanceof EncodedKeySpec) {
return new OpenSslXwingPrivateKey((EncodedKeySpec) keySpec);
}
- throw new InvalidKeySpecException(
- "Currently only EncodedKeySpec is supported; was " + keySpec.getClass().getName());
+ throw new InvalidKeySpecException("Currently only EncodedKeySpec is supported; was "
+ + keySpec.getClass().getName());
}
@Override
@@ -65,32 +65,26 @@ protected T engineGetKeySpec(Key key, Class keySpec)
if (keySpec == null) {
throw new InvalidKeySpecException("keySpec == null");
}
- try {
- key = engineTranslateKey(key);
- } catch (InvalidKeyException e) {
- throw new InvalidKeySpecException("Unsupported key class: " + key.getClass(), e);
- }
if (key instanceof OpenSslXwingPublicKey) {
OpenSslXwingPublicKey conscryptKey = (OpenSslXwingPublicKey) key;
if (X509EncodedKeySpec.class.isAssignableFrom(keySpec)) {
- @SuppressWarnings("unchecked") // safe because of isAssignableFrom check above
- T result = (T) new X509EncodedKeySpec(key.getEncoded());
- return result;
+ throw new UnsupportedOperationException(
+ "X509EncodedKeySpec is currently not supported");
} else if (EncodedKeySpec.class.isAssignableFrom(keySpec)) {
return KeySpecUtil.makeRawKeySpec(conscryptKey.getRaw(), keySpec);
}
} else if (key instanceof OpenSslXwingPrivateKey) {
OpenSslXwingPrivateKey conscryptKey = (OpenSslXwingPrivateKey) key;
if (PKCS8EncodedKeySpec.class.isAssignableFrom(keySpec)) {
- @SuppressWarnings("unchecked") // safe because of isAssignableFrom check above
- T result = (T) new PKCS8EncodedKeySpec(key.getEncoded());
- return result;
+ throw new UnsupportedOperationException(
+ "PKCS8EncodedKeySpec is currently not supported");
} else if (EncodedKeySpec.class.isAssignableFrom(keySpec)) {
return KeySpecUtil.makeRawKeySpec(conscryptKey.getRaw(), keySpec);
}
}
throw new InvalidKeySpecException("Unsupported key type and key spec combination; key="
- + key.getClass().getName() + ", keySpec=" + keySpec.getName());
+ + key.getClass().getName()
+ + ", keySpec=" + keySpec.getName());
}
@Override
@@ -101,28 +95,7 @@ protected Key engineTranslateKey(Key key) throws InvalidKeyException {
if ((key instanceof OpenSslXwingPublicKey) || (key instanceof OpenSslXwingPrivateKey)) {
return key;
}
- if ((key instanceof PrivateKey) && key.getFormat().equals("PKCS#8")) {
- byte[] encoded = key.getEncoded();
- if (encoded == null) {
- throw new InvalidKeyException("Key does not support encoding");
- }
- try {
- return engineGeneratePrivate(new PKCS8EncodedKeySpec(encoded));
- } catch (InvalidKeySpecException e) {
- throw new InvalidKeyException(e);
- }
- } else if ((key instanceof PublicKey) && key.getFormat().equals("X.509")) {
- byte[] encoded = key.getEncoded();
- if (encoded == null) {
- throw new InvalidKeyException("Key does not support encoding");
- }
- try {
- return engineGeneratePublic(new X509EncodedKeySpec(encoded));
- } catch (InvalidKeySpecException e) {
- throw new InvalidKeyException(e);
- }
- } else {
- throw new InvalidKeyException("Key is not a XWING key");
- }
+ throw new InvalidKeyException(
+ "Key must be OpenSslXwingPublicKey or OpenSslXwingPrivateKey");
}
}
diff --git a/common/src/main/java/org/conscrypt/OpenSslXwingPrivateKey.java b/common/src/main/java/org/conscrypt/OpenSslXwingPrivateKey.java
index 059e12ebb..50693744c 100644
--- a/common/src/main/java/org/conscrypt/OpenSslXwingPrivateKey.java
+++ b/common/src/main/java/org/conscrypt/OpenSslXwingPrivateKey.java
@@ -30,47 +30,11 @@ public class OpenSslXwingPrivateKey implements PrivateKey {
static final int PRIVATE_KEY_SIZE_BYTES = 32;
- // The PKCS#8 encoding of a X-Wing private key is always the concatenation of a fixed
- // prefix and the raw key.
- private static final byte[] pkcs8Preamble = new byte[] {
- 0x30,
- 0x34,
- 0x02,
- 0x01,
- 0x00,
- 0x30,
- 0x0d,
- 0x06,
- 0x0b,
- 0x2b,
- 0x06,
- 0x01,
- 0x04,
- 0x01,
- (byte) 0x83,
- (byte) 0xe6,
- 0x2d,
- (byte) 0x81,
- (byte) 0xc8,
- (byte) 0x7a,
- 0x04,
- 0x20,
- };
-
private byte[] raw;
public OpenSslXwingPrivateKey(EncodedKeySpec keySpec) throws InvalidKeySpecException {
byte[] encoded = keySpec.getEncoded();
- if (keySpec.getFormat().equals("PKCS#8")) {
- byte[] preamble = Arrays.copyOf(encoded, pkcs8Preamble.length);
- if (!Arrays.equals(preamble, pkcs8Preamble)) {
- throw new InvalidKeySpecException("Invalid X-Wing PKCS8 key preamble");
- }
- raw = Arrays.copyOfRange(encoded, pkcs8Preamble.length, encoded.length);
- if (raw.length != PRIVATE_KEY_SIZE_BYTES) {
- throw new InvalidKeySpecException("Invalid key size");
- }
- } else if (keySpec.getFormat().equalsIgnoreCase("raw")) {
+ if (keySpec.getFormat().equalsIgnoreCase("raw")) {
if (encoded.length != PRIVATE_KEY_SIZE_BYTES) {
throw new InvalidKeySpecException("Invalid key size");
}
@@ -94,15 +58,12 @@ public String getAlgorithm() {
@Override
public String getFormat() {
- return "PKCS#8";
+ throw new UnsupportedOperationException("getFormat() not yet supported");
}
@Override
public byte[] getEncoded() {
- if (raw == null) {
- throw new IllegalStateException("key is destroyed");
- }
- return ArrayUtils.concat(pkcs8Preamble, raw);
+ throw new UnsupportedOperationException("getEncoded() not yet supported");
}
byte[] getRaw() {
diff --git a/common/src/main/java/org/conscrypt/OpenSslXwingPublicKey.java b/common/src/main/java/org/conscrypt/OpenSslXwingPublicKey.java
index bfd1b26e2..a7706bd34 100644
--- a/common/src/main/java/org/conscrypt/OpenSslXwingPublicKey.java
+++ b/common/src/main/java/org/conscrypt/OpenSslXwingPublicKey.java
@@ -29,48 +29,11 @@ public class OpenSslXwingPublicKey implements PublicKey {
static final int PUBLIC_KEY_SIZE_BYTES = 1216;
- // The X.509 encoding of a X-Wing public key is always the concatenation of a fixed
- // prefix and the raw key.
- private static final byte[] x509Preamble = new byte[] {
- 0x30,
- (byte) 0x82,
- 0x04,
- (byte) 0xd4,
- 0x30,
- 0x0d,
- 0x06,
- 0x0b,
- 0x2b,
- 0x06,
- 0x01,
- 0x04,
- 0x01,
- (byte) 0x83,
- (byte) 0xe6,
- 0x2d,
- (byte) 0x81,
- (byte) 0xc8,
- (byte) 0x7a,
- 0x03,
- (byte) 0x82,
- 0x04,
- (byte) 0xc1,
- 0x00,
- };
-
private final byte[] raw;
public OpenSslXwingPublicKey(EncodedKeySpec keySpec) throws InvalidKeySpecException {
byte[] encoded = keySpec.getEncoded();
- if (keySpec.getFormat().equals("X.509")) {
- if (!ArrayUtils.startsWith(encoded, x509Preamble)) {
- throw new InvalidKeySpecException("Invalid X-Wing X.509 key preamble");
- }
- raw = Arrays.copyOfRange(encoded, x509Preamble.length, encoded.length);
- if (raw.length != PUBLIC_KEY_SIZE_BYTES) {
- throw new InvalidKeySpecException("Invalid key size");
- }
- } else if (keySpec.getFormat().equalsIgnoreCase("raw")) {
+ if (keySpec.getFormat().equalsIgnoreCase("raw")) {
if (encoded.length != PUBLIC_KEY_SIZE_BYTES) {
throw new InvalidKeySpecException("Invalid key size");
}
@@ -94,15 +57,12 @@ public String getAlgorithm() {
@Override
public String getFormat() {
- return "X.509";
+ throw new UnsupportedOperationException("getFormat() not yet supported");
}
@Override
public byte[] getEncoded() {
- if (raw == null) {
- throw new IllegalStateException("key is destroyed");
- }
- return ArrayUtils.concat(x509Preamble, raw);
+ throw new UnsupportedOperationException("getEncoded() not yet supported");
}
byte[] getRaw() {
diff --git a/common/src/main/java/org/conscrypt/SSLParametersImpl.java b/common/src/main/java/org/conscrypt/SSLParametersImpl.java
index f78b8691b..bc4c335ba 100644
--- a/common/src/main/java/org/conscrypt/SSLParametersImpl.java
+++ b/common/src/main/java/org/conscrypt/SSLParametersImpl.java
@@ -17,6 +17,8 @@
package org.conscrypt;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
import java.security.AlgorithmConstraints;
import java.security.KeyManagementException;
import java.security.KeyStore;
@@ -29,10 +31,13 @@
import java.util.Collection;
import java.util.List;
import java.util.Set;
+import java.util.logging.Logger;
+
import javax.crypto.SecretKey;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SNIMatcher;
+import javax.net.ssl.SSLException;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509KeyManager;
@@ -48,6 +53,7 @@
* socket or not.
*/
final class SSLParametersImpl implements Cloneable {
+ private static final Logger logger = Logger.getLogger(SSLParametersImpl.class.getName());
// default source of X.509 certificate based authentication keys
private static volatile X509KeyManager defaultX509KeyManager;
@@ -73,6 +79,8 @@ final class SSLParametersImpl implements Cloneable {
private final Spake2PlusTrustManager spake2PlusTrustManager;
// source of Spake authentication or null if not provided
private final Spake2PlusKeyManager spake2PlusKeyManager;
+ // getNetworkSecurityPolicy reflected method for x509TrustManager
+ private final Method getNetworkSecurityPolicy;
// protocols enabled for SSL connection
String[] enabledProtocols;
@@ -109,6 +117,7 @@ final class SSLParametersImpl implements Cloneable {
byte[] applicationProtocols = EmptyArray.BYTE;
ApplicationProtocolSelectorAdapter applicationProtocolSelector;
boolean useSessionTickets;
+ byte[] echConfigList;
private Boolean useSni;
/**
@@ -125,9 +134,9 @@ final class SSLParametersImpl implements Cloneable {
* See {@link javax.net.ssl.SSLContext#init(KeyManager[],TrustManager[],
* SecureRandom)} for more information
*/
- SSLParametersImpl(KeyManager[] kms, TrustManager[] tms,
- SecureRandom sr, ClientSessionContext clientSessionContext,
- ServerSessionContext serverSessionContext, String[] protocols)
+ SSLParametersImpl(KeyManager[] kms, TrustManager[] tms, SecureRandom sr,
+ ClientSessionContext clientSessionContext,
+ ServerSessionContext serverSessionContext, String[] protocols)
throws KeyManagementException {
this.serverSessionContext = serverSessionContext;
this.clientSessionContext = clientSessionContext;
@@ -168,6 +177,8 @@ final class SSLParametersImpl implements Cloneable {
"Spake2PlusTrustManager and Spake2PlusKeyManager should be set together");
}
+ getNetworkSecurityPolicy = getNetworkSecurityPolicyMethod(x509TrustManager);
+
// initialize the list of cipher suites and protocols enabled by default
if (isSpake()) {
enabledProtocols = new String[] {NativeCrypto.SUPPORTED_PROTOCOL_TLSV1_3};
@@ -175,13 +186,12 @@ final class SSLParametersImpl implements Cloneable {
enabledProtocols = NativeCrypto.getDefaultProtocols().clone();
} else {
String[] filteredProtocols =
- filterFromProtocols(protocols, Arrays.asList(!Platform.isTlsV1Filtered()
- ? new String[0]
- : new String[] {
+ filterFromProtocols(protocols, Arrays.asList(Platform.isTlsV1Filtered()
+ ? new String[] {
NativeCrypto.OBSOLETE_PROTOCOL_SSLV3,
NativeCrypto.DEPRECATED_PROTOCOL_TLSV1,
- NativeCrypto.DEPRECATED_PROTOCOL_TLSV1_1,
- }));
+ NativeCrypto.DEPRECATED_PROTOCOL_TLSV1_1,}
+ : new String[0]));
isEnabledProtocolsFiltered = protocols.length != filteredProtocols.length;
enabledProtocols = NativeCrypto.checkEnabledProtocols(filteredProtocols).clone();
}
@@ -201,15 +211,18 @@ final class SSLParametersImpl implements Cloneable {
// Copy constructor for the purposes of changing the final fields
@SuppressWarnings("deprecation") // for PSKKeyManager
private SSLParametersImpl(ClientSessionContext clientSessionContext,
- ServerSessionContext serverSessionContext, X509KeyManager x509KeyManager,
- PSKKeyManager pskKeyManager, X509TrustManager x509TrustManager,
- Spake2PlusTrustManager spake2PlusTrustManager,
- Spake2PlusKeyManager spake2PlusKeyManager, SSLParametersImpl sslParams) {
+ ServerSessionContext serverSessionContext,
+ X509KeyManager x509KeyManager, PSKKeyManager pskKeyManager,
+ X509TrustManager x509TrustManager,
+ Spake2PlusTrustManager spake2PlusTrustManager,
+ Spake2PlusKeyManager spake2PlusKeyManager,
+ SSLParametersImpl sslParams) {
this.clientSessionContext = clientSessionContext;
this.serverSessionContext = serverSessionContext;
this.x509KeyManager = x509KeyManager;
this.pskKeyManager = pskKeyManager;
this.x509TrustManager = x509TrustManager;
+ this.getNetworkSecurityPolicy = getNetworkSecurityPolicyMethod(x509TrustManager);
this.spake2PlusKeyManager = spake2PlusKeyManager;
this.spake2PlusTrustManager = spake2PlusTrustManager;
@@ -235,6 +248,8 @@ private SSLParametersImpl(ClientSessionContext clientSessionContext,
: sslParams.applicationProtocols.clone();
this.applicationProtocolSelector = sslParams.applicationProtocolSelector;
this.useSessionTickets = sslParams.useSessionTickets;
+ this.echConfigList =
+ (sslParams.echConfigList == null) ? null : sslParams.echConfigList.clone();
this.useSni = sslParams.useSni;
this.channelIdEnabled = sslParams.channelIdEnabled;
}
@@ -250,16 +265,23 @@ void initSpake() throws KeyManagementException {
}
}
+ private Method getNetworkSecurityPolicyMethod(X509TrustManager tm) {
+ if (tm == null) {
+ return null;
+ }
+ try {
+ return tm.getClass().getMethod("getNetworkSecurityPolicy");
+ } catch (NoSuchMethodException ignored) {
+ return null;
+ }
+ }
+
static SSLParametersImpl getDefault() throws KeyManagementException {
SSLParametersImpl result = defaultParameters;
if (result == null) {
// single-check idiom
- defaultParameters = result = new SSLParametersImpl(null,
- null,
- null,
- new ClientSessionContext(),
- new ServerSessionContext(),
- null);
+ defaultParameters = result = new SSLParametersImpl(
+ null, null, null, new ClientSessionContext(), new ServerSessionContext(), null);
}
return (SSLParametersImpl) result.clone();
}
@@ -319,8 +341,8 @@ X509TrustManager getX509TrustManager() {
*/
String[] getEnabledCipherSuites() {
if (Arrays.asList(enabledProtocols).contains(NativeCrypto.SUPPORTED_PROTOCOL_TLSV1_3)) {
- return SSLUtils.concat(
- NativeCrypto.SUPPORTED_TLS_1_3_CIPHER_SUITES, enabledCipherSuites);
+ return SSLUtils.concat(NativeCrypto.SUPPORTED_TLS_1_3_CIPHER_SUITES,
+ enabledCipherSuites);
}
return enabledCipherSuites.clone();
}
@@ -332,9 +354,8 @@ void setEnabledCipherSuites(String[] cipherSuites) {
// Filter out any TLS 1.3 cipher suites the user may have passed. Our TLS 1.3 suites
// are always enabled, no matter what the user requests, so we only store the 1.0-1.2
// suites in enabledCipherSuites.
- enabledCipherSuites = NativeCrypto.checkEnabledCipherSuites(
- filterFromCipherSuites(cipherSuites,
- NativeCrypto.SUPPORTED_TLS_1_3_CIPHER_SUITES_SET));
+ enabledCipherSuites = NativeCrypto.checkEnabledCipherSuites(filterFromCipherSuites(
+ cipherSuites, NativeCrypto.SUPPORTED_TLS_1_3_CIPHER_SUITES_SET));
}
/*
@@ -353,14 +374,15 @@ void setEnabledProtocols(String[] protocols) {
} else if (isSpake()) {
return;
}
- String[] filteredProtocols =
- filterFromProtocols(protocols, Arrays.asList(!Platform.isTlsV1Filtered()
- ? new String[0]
- : new String[] {
- NativeCrypto.OBSOLETE_PROTOCOL_SSLV3,
- NativeCrypto.DEPRECATED_PROTOCOL_TLSV1,
- NativeCrypto.DEPRECATED_PROTOCOL_TLSV1_1,
- }));
+ String[] filteredProtocols = filterFromProtocols(
+ protocols,
+ Arrays.asList(!Platform.isTlsV1Filtered()
+ ? new String[0]
+ : new String[] {
+ NativeCrypto.OBSOLETE_PROTOCOL_SSLV3,
+ NativeCrypto.DEPRECATED_PROTOCOL_TLSV1,
+ NativeCrypto.DEPRECATED_PROTOCOL_TLSV1_1,
+ }));
isEnabledProtocolsFiltered = protocols.length != filteredProtocols.length;
enabledProtocols = NativeCrypto.checkEnabledProtocols(filteredProtocols).clone();
}
@@ -395,7 +417,8 @@ String[] getApplicationProtocols() {
* Used for server-mode only. Sets or clears the application-provided ALPN protocol selector.
* If set, will override the protocol list provided by setApplicationProtocols(String[]).
*/
- void setApplicationProtocolSelector(ApplicationProtocolSelectorAdapter applicationProtocolSelector) {
+ void setApplicationProtocolSelector(
+ ApplicationProtocolSelectorAdapter applicationProtocolSelector) {
this.applicationProtocolSelector = applicationProtocolSelector;
}
@@ -475,6 +498,10 @@ void setUseSessionTickets(boolean useSessionTickets) {
this.useSessionTickets = useSessionTickets;
}
+ void setEchConfigList(byte[] echConfigList) {
+ this.echConfigList = echConfigList;
+ }
+
/*
* Whether connections using this SSL connection should use the TLS
* extension Server Name Indication (SNI).
@@ -521,7 +548,7 @@ byte[] getOCSPResponse() {
* to help with app compatibility.
*/
private static String[] filterFromProtocols(String[] protocols,
- List obsoleteProtocols) {
+ List obsoleteProtocols) {
if (protocols.length == 1 && obsoleteProtocols.contains(protocols[0])) {
return EMPTY_STRING_ARRAY;
}
@@ -579,7 +606,7 @@ private boolean isSniEnabledByDefault() {
*/
interface AliasChooser {
String chooseClientAlias(X509KeyManager keyManager, X500Principal[] issuers,
- String[] keyTypes);
+ String[] keyTypes);
String chooseServerAlias(X509KeyManager keyManager, String keyType);
}
@@ -610,12 +637,12 @@ protected Object clone() {
SSLParametersImpl cloneWithTrustManager(X509TrustManager newTrustManager) {
return new SSLParametersImpl(clientSessionContext, serverSessionContext, x509KeyManager,
- pskKeyManager, newTrustManager, null, null, this);
+ pskKeyManager, newTrustManager, null, null, this);
}
SSLParametersImpl cloneWithSpake() {
return new SSLParametersImpl(clientSessionContext, serverSessionContext, null, null, null,
- spake2PlusTrustManager, spake2PlusKeyManager, this);
+ spake2PlusTrustManager, spake2PlusKeyManager, this);
}
private static X509KeyManager getDefaultX509KeyManager() throws KeyManagementException {
@@ -635,7 +662,7 @@ private static X509KeyManager createDefaultX509KeyManager() throws KeyManagement
X509KeyManager result = findFirstX509KeyManager(kms);
if (result == null) {
throw new KeyManagementException("No X509KeyManager among default KeyManagers: "
- + Arrays.toString(kms));
+ + Arrays.toString(kms));
}
return result;
} catch (NoSuchAlgorithmException e) {
@@ -653,7 +680,7 @@ private static X509KeyManager createDefaultX509KeyManager() throws KeyManagement
private static X509KeyManager findFirstX509KeyManager(KeyManager[] kms) {
for (KeyManager km : kms) {
if (km instanceof X509KeyManager) {
- return (X509KeyManager)km;
+ return (X509KeyManager) km;
}
}
return null;
@@ -666,7 +693,7 @@ private static X509KeyManager findFirstX509KeyManager(KeyManager[] kms) {
private static PSKKeyManager findFirstPSKKeyManager(KeyManager[] kms) {
for (KeyManager km : kms) {
if (km instanceof PSKKeyManager) {
- return (PSKKeyManager)km;
+ return (PSKKeyManager) km;
} else if (km != null) {
try {
return DuckTypedPSKKeyManager.getInstance(km);
@@ -702,8 +729,7 @@ static X509TrustManager getDefaultX509TrustManager() throws KeyManagementExcepti
return result;
}
- private static X509TrustManager createDefaultX509TrustManager()
- throws KeyManagementException {
+ private static X509TrustManager createDefaultX509TrustManager() throws KeyManagementException {
try {
String algorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
@@ -713,7 +739,7 @@ private static X509TrustManager createDefaultX509TrustManager()
if (trustManager == null) {
throw new KeyManagementException(
"No X509TrustManager in among default TrustManagers: "
- + Arrays.toString(tms));
+ + Arrays.toString(tms));
}
return trustManager;
} catch (NoSuchAlgorithmException e) {
@@ -783,7 +809,8 @@ void setUseCipherSuitesOrder(boolean useCipherSuitesOrder) {
}
private static String[] getDefaultCipherSuites(boolean x509CipherSuitesNeeded,
- boolean pskCipherSuitesNeeded, boolean spake2PlusCipherSuitesNeeded) {
+ boolean pskCipherSuitesNeeded,
+ boolean spake2PlusCipherSuitesNeeded) {
if (x509CipherSuitesNeeded) {
// X.509 based cipher suites need to be listed.
if (pskCipherSuitesNeeded) {
@@ -805,17 +832,44 @@ private static String[] getDefaultCipherSuites(boolean x509CipherSuitesNeeded,
}
} else if (pskCipherSuitesNeeded) {
// Only PSK cipher suites need to be listed.
- return SSLUtils.concat(
- NativeCrypto.DEFAULT_PSK_CIPHER_SUITES,
- new String[] {NativeCrypto.TLS_EMPTY_RENEGOTIATION_INFO_SCSV});
+ return SSLUtils.concat(NativeCrypto.DEFAULT_PSK_CIPHER_SUITES,
+ new String[] {NativeCrypto.TLS_EMPTY_RENEGOTIATION_INFO_SCSV});
} else {
// Neither X.509 nor PSK cipher suites need to be listed.
return new String[] {NativeCrypto.TLS_EMPTY_RENEGOTIATION_INFO_SCSV};
}
}
+ private NetworkSecurityPolicy getPolicy() {
+ // If the TrustManager has a security policy attached, use it. We are using reflection here.
+ // The Android framework may provide a high-level TrustManager (e.g., RootTrustManager or
+ // NetworkSecurityTrustManager), which we need to query.
+ if (getNetworkSecurityPolicy != null) {
+ try {
+ Object objPolicy = getNetworkSecurityPolicy.invoke(x509TrustManager);
+ if (objPolicy instanceof NetworkSecurityPolicy) {
+ return (NetworkSecurityPolicy) objPolicy;
+ }
+ } catch (IllegalAccessException | IllegalArgumentException e) {
+ // This is the unlikely scenario where an external TrustManager is being used and it
+ // defines a getNetworkSecurityPolicy method which does not match our expectations.
+ logger.warning("Unable to call getNetworkSecurityPolicy on TrustManager: "
+ + e.getMessage());
+ } catch (InvocationTargetException e) {
+ // getNetworkSecurityPolicy raised an exception. Unwrap it.
+ throw new RuntimeException(
+ "Unable to retrieve the NetworkSecurityPolicy associated "
+ + "with the TrustManager",
+ e.getCause());
+ }
+ }
+ // Otherwise, rely on the global platform policy.
+ return ConscryptNetworkSecurityPolicy.getDefault();
+ }
+
/*
- * Checks whether SCT verification is enforced for a given hostname.
+ * Checks whether SCT verification is enforced for a given hostname. This
+ * will be used to decide if the TLS extension should be sent.
*/
boolean isCTVerificationEnabled(String hostname) {
if (hostname == null) {
@@ -826,7 +880,26 @@ boolean isCTVerificationEnabled(String hostname) {
if (ctVerificationEnabled) {
return true;
}
- return Platform.isCTVerificationRequired(hostname);
+
+ return getPolicy().isCertificateTransparencyVerificationRequired(hostname);
+ }
+
+ EchOptions getEchOptions(String hostname) throws SSLException {
+ switch (getPolicy().getDomainEncryptionMode(hostname)) {
+ case DISABLED:
+ return null;
+ case OPPORTUNISTIC:
+ return new EchOptions(echConfigList, /* enableGrease= */ false);
+ case ENABLED:
+ return new EchOptions(echConfigList, /* enableGrease= */ true);
+ case REQUIRED:
+ if (echConfigList == null) {
+ throw new SSLException("No ECH config provided when required");
+ }
+ return new EchOptions(echConfigList, /* enableGrease= */ false);
+ default:
+ return null;
+ }
}
boolean isSpake() {
diff --git a/common/src/main/java/org/conscrypt/ScryptSecretKeyFactory.java b/common/src/main/java/org/conscrypt/ScryptSecretKeyFactory.java
index a58cfee38..87c5f0bb0 100644
--- a/common/src/main/java/org/conscrypt/ScryptSecretKeyFactory.java
+++ b/common/src/main/java/org/conscrypt/ScryptSecretKeyFactory.java
@@ -16,21 +16,20 @@
package org.conscrypt;
+import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
-import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
+
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactorySpi;
@Internal
public class ScryptSecretKeyFactory extends SecretKeyFactorySpi {
-
@Override
protected SecretKey engineGenerateSecret(KeySpec inKeySpec) throws InvalidKeySpecException {
-
char[] password;
byte[] salt;
int n, r, p, keyOutputBits;
@@ -62,10 +61,13 @@ protected SecretKey engineGenerateSecret(KeySpec inKeySpec) throws InvalidKeySpe
throw new InvalidKeySpecException("Cannot produce fractional-byte outputs");
}
- return new ScryptKey(
- NativeCrypto.Scrypt_generate_key(
- new String(password).getBytes(StandardCharsets.UTF_8),
- salt, n, r, p, keyOutputBits / 8));
+ try {
+ return new ScryptKey(NativeCrypto.Scrypt_generate_key(
+ new String(password).getBytes("UTF-8"), salt, n, r, p, keyOutputBits / 8));
+ } catch (UnsupportedEncodingException e) {
+ // Impossible according to the Java docs: UTF-8 is always supported.
+ throw new IllegalStateException(e);
+ }
}
private Object getValue(KeySpec spec, String methodName)
@@ -75,8 +77,8 @@ private Object getValue(KeySpec spec, String methodName)
}
@Override
- protected KeySpec engineGetKeySpec(
- SecretKey secretKey, @SuppressWarnings("rawtypes") Class aClass)
+ protected KeySpec engineGetKeySpec(SecretKey secretKey,
+ @SuppressWarnings("rawtypes") Class aClass)
throws InvalidKeySpecException {
if (secretKey == null) {
throw new InvalidKeySpecException("Null KeySpec");
@@ -118,8 +120,6 @@ public byte[] getEncoded() {
}
private static class NotImplementedException extends RuntimeException {
- private static final long serialVersionUID = -7755435858585859108L;
-
NotImplementedException() {
super("Not implemented");
}
diff --git a/common/src/main/java/org/conscrypt/TrustManagerImpl.java b/common/src/main/java/org/conscrypt/TrustManagerImpl.java
index bedb2ce24..352e0a75a 100644
--- a/common/src/main/java/org/conscrypt/TrustManagerImpl.java
+++ b/common/src/main/java/org/conscrypt/TrustManagerImpl.java
@@ -61,6 +61,7 @@
import java.util.HashSet;
import java.util.List;
import java.util.Set;
+import java.util.function.Supplier;
import java.util.logging.Logger;
import javax.net.ssl.HttpsURLConnection;
@@ -72,14 +73,16 @@
/**
* TrustManager implementation. The implementation is based on CertPathValidator
- * PKIX and CertificateFactory X509 implementations. This implementations should
+ * PKIX and CertificateFactory X509 implementations. These implementations should
* be provided by some certification provider.
*
* @see javax.net.ssl.X509ExtendedTrustManager
+ * @see org.conscrypt.ConscryptX509TrustManager
*/
@Internal
@SuppressWarnings("CustomX509TrustManager")
-public final class TrustManagerImpl extends X509ExtendedTrustManager {
+public final class TrustManagerImpl
+ extends X509ExtendedTrustManager implements ConscryptX509TrustManager {
private static final Logger logger = Logger.getLogger(TrustManagerImpl.class.getName());
/**
@@ -88,8 +91,7 @@ public final class TrustManagerImpl extends X509ExtendedTrustManager {
private static final TrustAnchorComparator TRUST_ANCHOR_COMPARATOR =
new TrustAnchorComparator();
- private static final Set