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/android-stub/src/main/java/android/crypto/hpke/HpkeSpi.java b/android-stub/src/main/java/android/crypto/hpke/HpkeSpi.java index 98c0f607d..fe2672325 100644 --- a/android-stub/src/main/java/android/crypto/hpke/HpkeSpi.java +++ b/android-stub/src/main/java/android/crypto/hpke/HpkeSpi.java @@ -16,13 +16,13 @@ package android.crypto.hpke; +import libcore.util.NonNull; +import libcore.util.Nullable; + import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.PrivateKey; import java.security.PublicKey; -import libcore.util.NonNull; -import libcore.util.Nullable; - /** * Service Provider Interface for HPKE client API classes to communicate with implementations @@ -64,13 +64,9 @@ public interface HpkeSpi { * @throws UnsupportedOperationException if the mode is not supported by this implementation * @throws IllegalStateException if this SPI has already been initialised */ - void engineInitSender( - @NonNull PublicKey recipientKey, - @Nullable byte[] info, - @Nullable PrivateKey senderKey, - @Nullable byte[] psk, - @Nullable byte[] psk_id) - throws InvalidKeyException; + void engineInitSender(@NonNull PublicKey recipientKey, @Nullable byte[] info, + @Nullable PrivateKey senderKey, @Nullable byte[] psk, + @Nullable byte[] psk_id) throws InvalidKeyException; /** * Initialises an HPKE SPI in one of the sender modes described in RFC 9180 with @@ -109,13 +105,9 @@ void engineInitSender( * @throws UnsupportedOperationException if the mode is not supported by this implementation * @throws IllegalStateException if this SPI has already been initialised */ - void engineInitSenderWithSeed( - @NonNull PublicKey recipientKey, - @Nullable byte[] info, - @Nullable PrivateKey senderKey, - @Nullable byte[] psk, - @Nullable byte[] psk_id, - @NonNull byte[] sKe) + void engineInitSenderWithSeed(@NonNull PublicKey recipientKey, @Nullable byte[] info, + @Nullable PrivateKey senderKey, @Nullable byte[] psk, + @Nullable byte[] psk_id, @NonNull byte[] sKe) throws InvalidKeyException; /** @@ -149,13 +141,9 @@ void engineInitSenderWithSeed( * @throws UnsupportedOperationException if the mode is not supported by this implementation * @throws IllegalStateException if this SPI has already been initialised */ - void engineInitRecipient( - @NonNull byte[] encapsulated, - @NonNull PrivateKey recipientKey, - @Nullable byte[] info, - @Nullable PublicKey senderKey, - @Nullable byte[] psk, - @Nullable byte[] psk_id) + void engineInitRecipient(@NonNull byte[] encapsulated, @NonNull PrivateKey recipientKey, + @Nullable byte[] info, @Nullable PublicKey senderKey, + @Nullable byte[] psk, @Nullable byte[] psk_id) throws InvalidKeyException; /** @@ -180,7 +168,8 @@ void engineInitRecipient( * as a sender * @throws GeneralSecurityException on decryption failures */ - @NonNull byte[] engineOpen(@NonNull byte[] ciphertext, @Nullable byte[] aad) + @NonNull + byte[] engineOpen(@NonNull byte[] ciphertext, @Nullable byte[] aad) throws GeneralSecurityException; /** diff --git a/android-stub/src/main/java/android/pake/PakeServerKeyManagerParameters.java b/android-stub/src/main/java/android/pake/PakeServerKeyManagerParameters.java index a0fd86806..f05593ec1 100644 --- a/android-stub/src/main/java/android/pake/PakeServerKeyManagerParameters.java +++ b/android-stub/src/main/java/android/pake/PakeServerKeyManagerParameters.java @@ -72,8 +72,8 @@ public final class PakeServerKeyManagerParameters implements ManagerFactoryParam * @param serverId The server identifier for the link. * @return An unmodifiable list of PAKE options for the given link. */ - public @NonNull List getOptions( - @Nullable byte[] clientId, @Nullable byte[] serverId) { + public @NonNull List getOptions(@Nullable byte[] clientId, + @Nullable byte[] serverId) { throw new RuntimeException("Stub!"); } @@ -139,7 +139,7 @@ public static final class Builder { * @throws InvalidParameterException If the provided options are invalid. */ public @NonNull Builder setOptions(@Nullable byte[] clientId, @Nullable byte[] serverId, - @NonNull List options) { + @NonNull List options) { throw new RuntimeException("Stub!"); } diff --git a/android-stub/src/main/java/android/util/StatsEvent.java b/android-stub/src/main/java/android/util/StatsEvent.java index 928532d33..8705e29b1 100644 --- a/android-stub/src/main/java/android/util/StatsEvent.java +++ b/android-stub/src/main/java/android/util/StatsEvent.java @@ -16,7 +16,7 @@ package android.util; -@SuppressWarnings({"unused", "DoNotCallSuggester"}) +@SuppressWarnings({"unused", "DoNotCallSuggester"}) public final class StatsEvent { public static StatsEvent.Builder newBuilder() { throw new RuntimeException("Stub!"); @@ -38,10 +38,9 @@ public void release() { throw new RuntimeException("Stub!"); } - private static final class Buffer { - } + private static final class Buffer {} - @SuppressWarnings({"unused", "DoNotCallSuggester"}) + @SuppressWarnings({"unused", "DoNotCallSuggester"}) public static final class Builder { public StatsEvent.Builder setAtomId(int atomId) { throw new RuntimeException("Stub!"); diff --git a/android-stub/src/main/java/com/android/org/conscrypt/NativeCrypto.java b/android-stub/src/main/java/com/android/org/conscrypt/NativeCrypto.java index 851e27b5d..836ca8da9 100644 --- a/android-stub/src/main/java/com/android/org/conscrypt/NativeCrypto.java +++ b/android-stub/src/main/java/com/android/org/conscrypt/NativeCrypto.java @@ -18,6 +18,7 @@ import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; + import javax.net.ssl.SSLException; @SuppressWarnings("unused") @@ -31,8 +32,8 @@ public interface SSLHandshakeCallbacks { * * @throws CertificateException if the certificate is untrusted */ - void verifyCertificateChain(byte[][] asn1DerEncodedCertificateChain, - String authMethod) throws CertificateException; + void verifyCertificateChain(byte[][] asn1DerEncodedCertificateChain, String authMethod) + throws CertificateException; /** * Called on an SSL client when the server requests (or * requires a certificate). The client can respond by using @@ -44,8 +45,7 @@ void verifyCertificateChain(byte[][] asn1DerEncodedCertificateChain, * convertible to strings with #keyType * @param asn1DerEncodedX500Principals CAs known to the server */ - void clientCertificateRequested( - byte[] keyTypes, byte[][] asn1DerEncodedX500Principals) + void clientCertificateRequested(byte[] keyTypes, byte[][] asn1DerEncodedX500Principals) throws CertificateEncodingException, SSLException; /** * Called when SSL handshake is completed. Note that this can diff --git a/android-stub/src/main/java/com/android/org/conscrypt/OpenSSLSocketImpl.java b/android-stub/src/main/java/com/android/org/conscrypt/OpenSSLSocketImpl.java index 8beee1c4f..a2be95473 100644 --- a/android-stub/src/main/java/com/android/org/conscrypt/OpenSSLSocketImpl.java +++ b/android-stub/src/main/java/com/android/org/conscrypt/OpenSSLSocketImpl.java @@ -25,6 +25,7 @@ import java.security.PrivateKey; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; + import javax.net.ssl.HandshakeCompletedListener; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; @@ -46,7 +47,7 @@ protected OpenSSLSocketImpl(SSLParametersImpl sslParameters) throws IOException } protected OpenSSLSocketImpl(SSLParametersImpl sslParameters, String[] enabledProtocols, - String[] enabledCipherSuites) throws IOException { + String[] enabledCipherSuites) throws IOException { throw new RuntimeException("Stub!"); } @@ -61,17 +62,18 @@ protected OpenSSLSocketImpl(InetAddress address, int port, SSLParametersImpl ssl } protected OpenSSLSocketImpl(String host, int port, InetAddress clientAddress, int clientPort, - SSLParametersImpl sslParameters) throws IOException { + SSLParametersImpl sslParameters) throws IOException { throw new RuntimeException("Stub!"); } protected OpenSSLSocketImpl(InetAddress address, int port, InetAddress clientAddress, - int clientPort, SSLParametersImpl sslParameters) throws IOException { + int clientPort, SSLParametersImpl sslParameters) + throws IOException { throw new RuntimeException("Stub!"); } protected OpenSSLSocketImpl(Socket socket, String host, int port, boolean autoClose, - SSLParametersImpl sslParameters) throws IOException { + SSLParametersImpl sslParameters) throws IOException { throw new RuntimeException("Stub!"); } diff --git a/android-stub/src/main/java/dalvik/system/BlockGuard.java b/android-stub/src/main/java/dalvik/system/BlockGuard.java index b097905a5..bfc2c5231 100644 --- a/android-stub/src/main/java/dalvik/system/BlockGuard.java +++ b/android-stub/src/main/java/dalvik/system/BlockGuard.java @@ -24,7 +24,9 @@ public static Policy getThreadPolicy() { throw new UnsupportedOperationException("Stub!"); } - public interface Policy { void onNetwork(); } + public interface Policy { + void onNetwork(); + } public static class PolicyWrapper implements Policy { private PolicyWrapper() {} diff --git a/android/src/main/java/org/conscrypt/BaseOpenSSLSocketAdapterFactory.java b/android/src/main/java/org/conscrypt/BaseOpenSSLSocketAdapterFactory.java index 610280749..f1390f304 100644 --- a/android/src/main/java/org/conscrypt/BaseOpenSSLSocketAdapterFactory.java +++ b/android/src/main/java/org/conscrypt/BaseOpenSSLSocketAdapterFactory.java @@ -20,11 +20,11 @@ import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; + import javax.net.ssl.SSLSocketFactory; @Internal public abstract class BaseOpenSSLSocketAdapterFactory extends SSLSocketFactory { - private final OpenSSLSocketFactoryImpl delegate; protected BaseOpenSSLSocketAdapterFactory(OpenSSLSocketFactoryImpl delegate) { @@ -47,8 +47,7 @@ public Socket createSocket() throws IOException { } @Override - public Socket createSocket(String hostname, int port) - throws IOException, UnknownHostException { + public Socket createSocket(String hostname, int port) throws IOException, UnknownHostException { return wrap((OpenSSLSocketImpl) delegate.createSocket(hostname, port)); } @@ -64,11 +63,8 @@ public Socket createSocket(InetAddress address, int port) throws IOException { } @Override - public Socket createSocket(InetAddress address, - int port, - InetAddress localAddress, - int localPort) - throws IOException { + public Socket createSocket(InetAddress address, int port, InetAddress localAddress, + int localPort) throws IOException { return wrap( (OpenSSLSocketImpl) delegate.createSocket(address, port, localAddress, localPort)); } diff --git a/android/src/main/java/org/conscrypt/KitKatPlatformOpenSSLSocketAdapterFactory.java b/android/src/main/java/org/conscrypt/KitKatPlatformOpenSSLSocketAdapterFactory.java index 0ce57afc9..7e7c92373 100644 --- a/android/src/main/java/org/conscrypt/KitKatPlatformOpenSSLSocketAdapterFactory.java +++ b/android/src/main/java/org/conscrypt/KitKatPlatformOpenSSLSocketAdapterFactory.java @@ -25,7 +25,6 @@ */ @Internal public class KitKatPlatformOpenSSLSocketAdapterFactory extends BaseOpenSSLSocketAdapterFactory { - public KitKatPlatformOpenSSLSocketAdapterFactory(OpenSSLSocketFactoryImpl delegate) { super(delegate); } diff --git a/android/src/main/java/org/conscrypt/KitKatPlatformOpenSSLSocketImplAdapter.java b/android/src/main/java/org/conscrypt/KitKatPlatformOpenSSLSocketImplAdapter.java index 5c46c5679..2f567ded5 100644 --- a/android/src/main/java/org/conscrypt/KitKatPlatformOpenSSLSocketImplAdapter.java +++ b/android/src/main/java/org/conscrypt/KitKatPlatformOpenSSLSocketImplAdapter.java @@ -27,6 +27,7 @@ import java.security.PrivateKey; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; + import javax.net.ssl.HandshakeCompletedListener; import javax.net.ssl.SSLException; import javax.net.ssl.SSLParameters; @@ -44,8 +45,6 @@ @Internal public class KitKatPlatformOpenSSLSocketImplAdapter extends com.android.org.conscrypt.OpenSSLSocketImpl { - - private final AbstractConscryptSocket delegate; public KitKatPlatformOpenSSLSocketImplAdapter(AbstractConscryptSocket delegate) diff --git a/android/src/main/java/org/conscrypt/NativeCryptoJni.java b/android/src/main/java/org/conscrypt/NativeCryptoJni.java index a4bf20776..8f4baa706 100644 --- a/android/src/main/java/org/conscrypt/NativeCryptoJni.java +++ b/android/src/main/java/org/conscrypt/NativeCryptoJni.java @@ -22,13 +22,13 @@ */ class NativeCryptoJni { public static void init() { - if ("com.google.android.gms.org.conscrypt".equals(NativeCrypto.class.getPackage().getName())) { + if ("com.google.android.gms.org.conscrypt".equals( + NativeCrypto.class.getPackage().getName())) { System.loadLibrary("conscrypt_gmscore_jni"); } else { System.loadLibrary("conscrypt_jni"); } } - private NativeCryptoJni() { - } + private NativeCryptoJni() {} } diff --git a/android/src/main/java/org/conscrypt/Platform.java b/android/src/main/java/org/conscrypt/Platform.java index 65fc084ad..b3433f12c 100644 --- a/android/src/main/java/org/conscrypt/Platform.java +++ b/android/src/main/java/org/conscrypt/Platform.java @@ -88,7 +88,7 @@ final public class Platform { m_getCurveName = ECParameterSpec.class.getDeclaredMethod("getCurveName"); m_getCurveName.setAccessible(true); } catch (Exception ignored) { - //Ignored + // Ignored } } @@ -146,7 +146,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 +212,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. @@ -262,8 +263,8 @@ private static void setSSLParametersOnImpl(SSLParameters params, SSLParametersIm } } - 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 +275,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 +295,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 +324,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); @@ -339,8 +340,8 @@ private static void getSSLParametersFromImpl(SSLParameters params, SSLParameters } } - 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 +349,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 +378,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 +406,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 +427,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 +451,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 +512,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 +521,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 +530,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 +540,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 +550,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 +568,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 +577,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 +586,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 +659,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 +705,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 +761,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 +783,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 +828,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 +848,7 @@ public static String getHostStringFromInetSocketAddress(InetSocketAddress addr) } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (Exception ignored) { - //Ignored + // Ignored } } return null; @@ -932,8 +952,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/compatibility_close_monitor.cc b/common/src/jni/main/cpp/conscrypt/compatibility_close_monitor.cc index c74706457..a4d9a9e82 100644 --- a/common/src/jni/main/cpp/conscrypt/compatibility_close_monitor.cc +++ b/common/src/jni/main/cpp/conscrypt/compatibility_close_monitor.cc @@ -36,10 +36,10 @@ CompatibilityCloseMonitor::acm_dtor_func CompatibilityCloseMonitor::asyncCloseMo void CompatibilityCloseMonitor::init() { #ifndef _WIN32 - void *lib = dlopen("libandroidio.so", RTLD_NOW); + void* lib = dlopen("libandroidio.so", RTLD_NOW); if (lib != nullptr) { - asyncCloseMonitorCreate = (acm_create_func) dlsym(lib, "async_close_monitor_create"); - asyncCloseMonitorDestroy = (acm_destroy_func) dlsym(lib, "async_close_monitor_destroy"); + asyncCloseMonitorCreate = (acm_create_func)dlsym(lib, "async_close_monitor_create"); + asyncCloseMonitorDestroy = (acm_destroy_func)dlsym(lib, "async_close_monitor_destroy"); return; } #ifdef CONSCRYPT_UNBUNDLED diff --git a/common/src/jni/main/cpp/conscrypt/jniload.cc b/common/src/jni/main/cpp/conscrypt/jniload.cc index c06cac3b8..49a3bd24d 100644 --- a/common/src/jni/main/cpp/conscrypt/jniload.cc +++ b/common/src/jni/main/cpp/conscrypt/jniload.cc @@ -14,12 +14,11 @@ * limitations under the License. */ -#include - #include #include #include #include +#include #ifndef CONSCRYPT_JNI_VERSION #define CONSCRYPT_JNI_VERSION JNI_VERSION_1_6 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..eaea7717f 100644 --- a/common/src/jni/main/cpp/conscrypt/native_crypto.cc +++ b/common/src/jni/main/cpp/conscrypt/native_crypto.cc @@ -216,7 +216,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 +501,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 +543,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 +570,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 +603,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 +636,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 +776,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 +1573,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 +1603,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 +1874,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 +2041,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 +2067,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 +2157,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 +2693,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 +2714,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 +2724,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 +3093,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 +3120,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 +3129,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 +3600,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 +4256,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 +4453,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 +4487,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 +4514,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 +4545,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 +4574,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 +4596,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 +4606,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 +4632,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 +4682,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 +4754,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 +4811,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 +4861,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 +4928,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 +4979,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 +5004,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 +5067,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 +5094,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 +5148,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 +5466,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 +5490,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 +5567,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 +5645,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 +6581,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 +7171,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 +7184,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 +7194,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 +7220,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 +7871,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 +8098,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); @@ -9113,8 +9110,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 +9125,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 +9488,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 +9514,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 +9575,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 +10060,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 +10339,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); @@ -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/NetFd.h b/common/src/jni/main/include/conscrypt/NetFd.h index 3f988fb17..522250c5e 100644 --- a/common/src/jni/main/include/conscrypt/NetFd.h +++ b/common/src/jni/main/include/conscrypt/NetFd.h @@ -23,7 +23,7 @@ * Wraps access to the int inside a java.io.FileDescriptor, taking care of throwing exceptions. */ class NetFd { - public: +public: NetFd(JNIEnv* env, jobject fileDescriptor) : mEnv(env), mFileDescriptor(fileDescriptor), mFd(-1) {} @@ -40,7 +40,7 @@ class NetFd { return mFd; } - private: +private: JNIEnv* mEnv; jobject mFileDescriptor; int mFd; diff --git a/common/src/jni/main/include/conscrypt/app_data.h b/common/src/jni/main/include/conscrypt/app_data.h index 9f64f94d0..cc8d72ffc 100644 --- a/common/src/jni/main/include/conscrypt/app_data.h +++ b/common/src/jni/main/include/conscrypt/app_data.h @@ -22,8 +22,8 @@ #include #include #include - #include + #include #include #include // NOLINT(build/c++11) @@ -104,7 +104,7 @@ namespace conscrypt { * SSL_do_handshake, SSL_read, SSL_write, and SSL_shutdown. */ class AppData { - public: +public: std::atomic aliveAndKicking; int waitingThreads; #ifdef _WIN32 @@ -175,7 +175,7 @@ class AppData { clearApplicationProtocols(); if (applicationProtocolsJava != nullptr) { jbyte* applicationProtocols = - e->GetByteArrayElements(applicationProtocolsJava, nullptr); + e->GetByteArrayElements(applicationProtocolsJava, nullptr); if (applicationProtocols == nullptr) { clearCallbackState(); JNI_TRACE("appData=%p setApplicationCallbackState => applicationProtocols == null", @@ -183,7 +183,7 @@ class AppData { return false; } applicationProtocolsLength = - static_cast(e->GetArrayLength(applicationProtocolsJava)); + static_cast(e->GetArrayLength(applicationProtocolsJava)); applicationProtocolsData = new char[applicationProtocolsLength]; memcpy(applicationProtocolsData, applicationProtocols, applicationProtocolsLength); e->ReleaseByteArrayElements(applicationProtocolsJava, applicationProtocols, JNI_ABORT); @@ -219,7 +219,7 @@ class AppData { env = nullptr; } - private: +private: AppData() : aliveAndKicking(true), waitingThreads(0), diff --git a/common/src/jni/main/include/conscrypt/bio_input_stream.h b/common/src/jni/main/include/conscrypt/bio_input_stream.h index f4b35d281..1b7d22490 100644 --- a/common/src/jni/main/include/conscrypt/bio_input_stream.h +++ b/common/src/jni/main/include/conscrypt/bio_input_stream.h @@ -17,23 +17,22 @@ #ifndef CONSCRYPT_BIO_INPUT_STREAM_H_ #define CONSCRYPT_BIO_INPUT_STREAM_H_ -#include -#include - #include +#include #include +#include namespace conscrypt { class BioInputStream : public BioStream { - public: +public: BioInputStream(jobject stream, bool isFinite) : BioStream(stream), isFinite_(isFinite) {} - int read(char *buf, int len) { + int read(char* buf, int len) { return read_internal(buf, len, jniutil::inputStream_readMethod); } - int gets(char *buf, int len) { + int gets(char* buf, int len) { if (len > PEM_LINE_LENGTH) { len = PEM_LINE_LENGTH; } @@ -48,11 +47,11 @@ class BioInputStream : public BioStream { return isFinite_; } - private: +private: const bool isFinite_; - int read_internal(char *buf, int len, jmethodID method) { - JNIEnv *env = jniutil::getJNIEnv(); + int read_internal(char* buf, int len, jmethodID method) { + JNIEnv* env = jniutil::getJNIEnv(); if (env == nullptr) { JNI_TRACE("BioInputStream::read could not get JNIEnv"); return -1; @@ -80,13 +79,13 @@ class BioInputStream : public BioStream { setEof(true); read = 0; } else if (read > 0) { - env->GetByteArrayRegion(javaBytes.get(), 0, read, reinterpret_cast(buf)); + env->GetByteArrayRegion(javaBytes.get(), 0, read, reinterpret_cast(buf)); } return read; } - public: +public: /** Length of PEM-encoded line (64) plus CR plus NUL */ static const int PEM_LINE_LENGTH = 66; }; diff --git a/common/src/jni/main/include/conscrypt/bio_output_stream.h b/common/src/jni/main/include/conscrypt/bio_output_stream.h index eeebf4d1a..ed4b6745c 100644 --- a/common/src/jni/main/include/conscrypt/bio_output_stream.h +++ b/common/src/jni/main/include/conscrypt/bio_output_stream.h @@ -17,14 +17,13 @@ #ifndef CONSCRYPT_BIO_OUTPUT_STREAM_H_ #define CONSCRYPT_BIO_OUTPUT_STREAM_H_ -#include - #include +#include namespace conscrypt { class BioOutputStream : public BioStream { - public: +public: explicit BioOutputStream(jobject stream) : BioStream(stream) {} int write(const char* buf, int len) { diff --git a/common/src/jni/main/include/conscrypt/bio_stream.h b/common/src/jni/main/include/conscrypt/bio_stream.h index bcd2f9905..a592c7875 100644 --- a/common/src/jni/main/include/conscrypt/bio_stream.h +++ b/common/src/jni/main/include/conscrypt/bio_stream.h @@ -17,10 +17,9 @@ #ifndef CONSCRYPT_BIO_STREAM_H_ #define CONSCRYPT_BIO_STREAM_H_ -#include - #include #include +#include namespace conscrypt { @@ -28,7 +27,7 @@ namespace conscrypt { * BIO for InputStream */ class BioStream { - public: +public: explicit BioStream(jobject stream) : mEof(false) { JNIEnv* env = jniutil::getJNIEnv(); mStream = env->NewGlobalRef(stream); @@ -64,7 +63,7 @@ class BioStream { return 1; } - protected: +protected: jobject getStream() { return mStream; } @@ -73,7 +72,7 @@ class BioStream { mEof = eof; } - private: +private: jobject mStream; bool mEof; }; diff --git a/common/src/jni/main/include/conscrypt/compat.h b/common/src/jni/main/include/conscrypt/compat.h index c324e0cbd..b19e4d56b 100644 --- a/common/src/jni/main/include/conscrypt/compat.h +++ b/common/src/jni/main/include/conscrypt/compat.h @@ -30,9 +30,8 @@ // OTOH, we need to have _GNU_SOURCE defined to pick up asprintf from stdio.h. #define _GNU_SOURCE -#include - #include +#include #else /* !ANDROID || CONSCRYPT_OPENJDK */ @@ -47,6 +46,7 @@ #include #include #include + #include // NOLINTNEXTLINE(runtime/int) @@ -55,14 +55,14 @@ typedef long ssize_t; #define strcasecmp _stricmp // Windows doesn't define this either *sigh*... -inline int vasprintf(char **ret, const char *format, va_list args) { +inline int vasprintf(char** ret, const char* format, va_list args) { va_list copy; va_copy(copy, args); *ret = nullptr; int count = vsnprintf(nullptr, 0, format, args); if (count >= 0) { - char *buffer = static_cast(malloc((std::size_t)count + 1)); + char* buffer = static_cast(malloc((std::size_t)count + 1)); if (buffer == nullptr) { count = -1; } else if ((count = vsnprintf(buffer, static_cast(count + 1), format, copy)) < @@ -77,7 +77,7 @@ inline int vasprintf(char **ret, const char *format, va_list args) { return count; } -inline int asprintf(char **strp, const char *fmt, ...) { +inline int asprintf(char** strp, const char* fmt, ...) { va_list ap; va_start(ap, fmt); int r = vasprintf(strp, fmt, ap); @@ -85,7 +85,7 @@ inline int asprintf(char **strp, const char *fmt, ...) { return r; } -inline int gettimeofday(struct timeval *tp, struct timezone *) { +inline int gettimeofday(struct timeval* tp, struct timezone*) { // Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing // zero's // This magic number is the number of 100 nanosecond intervals since January 1, 1601 (UTC) @@ -101,7 +101,7 @@ inline int gettimeofday(struct timeval *tp, struct timezone *) { time = ((uint64_t)file_time.dwLowDateTime); time += ((uint64_t)file_time.dwHighDateTime) << 32; - tp->tv_sec = static_cast((time - EPOCH) / 10000000L); // NOLINT(runtime/int) + tp->tv_sec = static_cast((time - EPOCH) / 10000000L); // NOLINT(runtime/int) tp->tv_usec = static_cast(system_time.wMilliseconds * 1000); // NOLINT(runtime/int) return 0; } diff --git a/common/src/jni/main/include/conscrypt/compatibility_close_monitor.h b/common/src/jni/main/include/conscrypt/compatibility_close_monitor.h index 0b6194966..70f6ad3ad 100644 --- a/common/src/jni/main/include/conscrypt/compatibility_close_monitor.h +++ b/common/src/jni/main/include/conscrypt/compatibility_close_monitor.h @@ -32,15 +32,15 @@ namespace conscrypt { * to create and destroy AsynchronousCloseMonitor instances will be null. */ class CompatibilityCloseMonitor { - public: - explicit CompatibilityCloseMonitor(int fd) : monitor(nullptr) { - if (asyncCloseMonitorCreate != nullptr) { - monitor = asyncCloseMonitorCreate(fd); - } +public: + explicit CompatibilityCloseMonitor(int fd) : monitor(nullptr) { + if (asyncCloseMonitorCreate != nullptr) { + monitor = asyncCloseMonitorCreate(fd); + } #ifdef CONSCRYPT_UNBUNDLED - else if (asyncCloseMonitorConstructor != nullptr) { // NOLINT(readability/braces) - asyncCloseMonitorConstructor(objBuffer, fd); - } + else if (asyncCloseMonitorConstructor != nullptr) { // NOLINT(readability/braces) + asyncCloseMonitorConstructor(objBuffer, fd); + } #endif // CONSCRYPT_UNBUNDLED } @@ -59,30 +59,30 @@ class CompatibilityCloseMonitor { static void init(); - private: - // C API: Not available on Android P and below. Maintains pointers to the C - // create and destroy methods, which will be null on non-Android platforms. - // The handle returned by the create method is stored in monitor. - typedef void* (*acm_create_func)(int); - typedef void (*acm_destroy_func)(void*); +private: + // C API: Not available on Android P and below. Maintains pointers to the C + // create and destroy methods, which will be null on non-Android platforms. + // The handle returned by the create method is stored in monitor. + typedef void* (*acm_create_func)(int); + typedef void (*acm_destroy_func)(void*); - static acm_create_func asyncCloseMonitorCreate; - static acm_destroy_func asyncCloseMonitorDestroy; - void* monitor; + static acm_create_func asyncCloseMonitorCreate; + static acm_destroy_func asyncCloseMonitorDestroy; + void* monitor; #ifdef CONSCRYPT_UNBUNDLED - // C++ API: Only available on Android P and below. Maintains pointers to - // the C++ constructor and destructor methods, which will be null on - // non-Android platforms. Calls them directly, passing in a pointer to - // objBuffer, which is large enough to fit an AsynchronousCloseMonitor object on - // Android versions where this class will be using this API. - // This is equivalent to placement new and explicit destruction. - typedef void (*acm_ctor_func)(void*, int); - typedef void (*acm_dtor_func)(void*); + // C++ API: Only available on Android P and below. Maintains pointers to + // the C++ constructor and destructor methods, which will be null on + // non-Android platforms. Calls them directly, passing in a pointer to + // objBuffer, which is large enough to fit an AsynchronousCloseMonitor object on + // Android versions where this class will be using this API. + // This is equivalent to placement new and explicit destruction. + typedef void (*acm_ctor_func)(void*, int); + typedef void (*acm_dtor_func)(void*); - static acm_ctor_func asyncCloseMonitorConstructor; - static acm_dtor_func asyncCloseMonitorDestructor; - char objBuffer[256]; + static acm_ctor_func asyncCloseMonitorConstructor; + static acm_dtor_func asyncCloseMonitorDestructor; + char objBuffer[256]; #endif // CONSCRYPT_UNBUNDLED }; diff --git a/common/src/jni/main/include/conscrypt/jniutil.h b/common/src/jni/main/include/conscrypt/jniutil.h index 7ae567dbc..70ae3965e 100644 --- a/common/src/jni/main/include/conscrypt/jniutil.h +++ b/common/src/jni/main/include/conscrypt/jniutil.h @@ -17,12 +17,11 @@ #ifndef CONSCRYPT_JNIUTIL_H_ #define CONSCRYPT_JNIUTIL_H_ -#include -#include - #include #include +#include #include +#include namespace conscrypt { namespace jniutil { @@ -308,7 +307,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 +325,7 @@ class ErrorQueueChecker { } } - private: +private: JNIEnv* env; }; diff --git a/common/src/jni/main/include/conscrypt/logging.h b/common/src/jni/main/include/conscrypt/logging.h index be1b373ce..2dda3075b 100644 --- a/common/src/jni/main/include/conscrypt/logging.h +++ b/common/src/jni/main/include/conscrypt/logging.h @@ -61,21 +61,24 @@ #define CONSCRYPT_LOG(priority, tag, ...) CONSCRYPT_##priority(__VA_ARGS__) -#define CONSCRYPT_LOG_ERROR(...) { \ - fprintf(stderr, __VA_ARGS__); \ - fprintf(stderr, "\n"); \ -} -#define CONSCRYPT_LOG_INFO(...) { \ - fprintf(stderr, __VA_ARGS__); \ - fprintf(stderr, "\n"); \ -} +#define CONSCRYPT_LOG_ERROR(...) \ + { \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, "\n"); \ + } +#define CONSCRYPT_LOG_INFO(...) \ + { \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, "\n"); \ + } #if LOG_NDEBUG #define CONSCRYPT_LOG_VERBOSE(...) ((void)0) #else -#define CONSCRYPT_LOG_VERBOSE(...) { \ - fprintf(stderr, __VA_ARGS__); \ - fprintf(stderr, "\n"); \ -} +#define CONSCRYPT_LOG_VERBOSE(...) \ + { \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, "\n"); \ + } #endif // LOG_NDEBUG #endif // !ANDROID diff --git a/common/src/jni/main/include/conscrypt/native_crypto.h b/common/src/jni/main/include/conscrypt/native_crypto.h index a74cb7f64..e1df6b3dc 100644 --- a/common/src/jni/main/include/conscrypt/native_crypto.h +++ b/common/src/jni/main/include/conscrypt/native_crypto.h @@ -25,13 +25,13 @@ namespace conscrypt { * Provides registration support for all native methods exported by Conscrypt. */ class NativeCrypto { - public: +public: /** * Register all native JNI methods exported by Conscrypt. */ static void registerNativeMethods(JNIEnv* env); - private: +private: NativeCrypto() {} ~NativeCrypto() {} }; diff --git a/common/src/jni/main/include/conscrypt/scoped_ssl_bio.h b/common/src/jni/main/include/conscrypt/scoped_ssl_bio.h index 32658791e..ecf7abd5c 100644 --- a/common/src/jni/main/include/conscrypt/scoped_ssl_bio.h +++ b/common/src/jni/main/include/conscrypt/scoped_ssl_bio.h @@ -26,7 +26,7 @@ namespace conscrypt { * We hang on to BIO with a JNI GlobalRef and we want to remove them as soon as possible. */ class ScopedSslBio { - public: +public: ScopedSslBio(SSL* ssl, BIO* rbio, BIO* wbio) : ssl_(ssl) { SSL_set_bio(ssl_, rbio, wbio); BIO_up_ref(rbio); @@ -37,7 +37,7 @@ class ScopedSslBio { SSL_set_bio(ssl_, nullptr, nullptr); } - private: +private: SSL* const ssl_; }; diff --git a/common/src/jni/main/include/conscrypt/ssl_error.h b/common/src/jni/main/include/conscrypt/ssl_error.h index 1fe73adcf..85ab30e09 100644 --- a/common/src/jni/main/include/conscrypt/ssl_error.h +++ b/common/src/jni/main/include/conscrypt/ssl_error.h @@ -30,7 +30,7 @@ namespace conscrypt { * argument to things that free the error stack state as a side-effect. */ class SslError { - public: +public: SslError() : sslError_(SSL_ERROR_NONE), released_(false) {} SslError(SSL* ssl, int returnCode) : sslError_(SSL_ERROR_NONE), released_(false) { @@ -60,7 +60,7 @@ class SslError { return sslError_; } - private: +private: int sslError_; bool released_; }; diff --git a/common/src/jni/main/include/conscrypt/trace.h b/common/src/jni/main/include/conscrypt/trace.h index 1a3fcebcb..738f19c7e 100644 --- a/common/src/jni/main/include/conscrypt/trace.h +++ b/common/src/jni/main/include/conscrypt/trace.h @@ -17,9 +17,10 @@ #ifndef CONSCRYPT_TRACE_H_ #define CONSCRYPT_TRACE_H_ +#include #include + #include -#include namespace conscrypt { namespace trace { @@ -59,7 +60,7 @@ constexpr bool kWithJniTracePackets = false; * 4. Follow the stream that corresponds to the desired "Session-ID" in * the Server Hello. */ - constexpr bool kWithJniTraceKeys = false; +constexpr bool kWithJniTraceKeys = false; } // namespace trace } // namespace conscrypt diff --git a/common/src/jni/unbundled/include/nativehelper/scoped_local_ref.h b/common/src/jni/unbundled/include/nativehelper/scoped_local_ref.h index 15a3618d2..8d72bd4fd 100644 --- a/common/src/jni/unbundled/include/nativehelper/scoped_local_ref.h +++ b/common/src/jni/unbundled/include/nativehelper/scoped_local_ref.h @@ -19,13 +19,12 @@ #include #include - #include // A smart pointer that deletes a JNI local reference when it goes out of scope. template class ScopedLocalRef { - public: +public: ScopedLocalRef(JNIEnv* env, T localRef) : mEnv(env), mLocalRef(localRef) {} ~ScopedLocalRef() { @@ -52,7 +51,7 @@ class ScopedLocalRef { return mLocalRef; } - private: +private: JNIEnv* mEnv; T mLocalRef; diff --git a/common/src/jni/unbundled/include/nativehelper/scoped_primitive_array.h b/common/src/jni/unbundled/include/nativehelper/scoped_primitive_array.h index 466c269e8..71e3733d2 100644 --- a/common/src/jni/unbundled/include/nativehelper/scoped_primitive_array.h +++ b/common/src/jni/unbundled/include/nativehelper/scoped_primitive_array.h @@ -25,7 +25,7 @@ // access and should be used by default. #define INSTANTIATE_SCOPED_PRIMITIVE_ARRAY_RO(PRIMITIVE_TYPE, NAME) \ class Scoped##NAME##ArrayRO { \ - public: \ + public: \ explicit Scoped##NAME##ArrayRO(JNIEnv* env) \ : mEnv(env), mJavaArray(nullptr), mRawArray(nullptr) {} \ Scoped##NAME##ArrayRO(JNIEnv* env, PRIMITIVE_TYPE##Array javaArray) \ @@ -58,7 +58,7 @@ return static_cast(mEnv->GetArrayLength(mJavaArray)); \ } \ \ - private: \ + private: \ JNIEnv* mEnv; \ PRIMITIVE_TYPE##Array mJavaArray; \ PRIMITIVE_TYPE* mRawArray; \ @@ -83,7 +83,7 @@ INSTANTIATE_SCOPED_PRIMITIVE_ARRAY_RO(jshort, Short); // since they entail a copy back onto the Java heap, and should only be used when necessary. #define INSTANTIATE_SCOPED_PRIMITIVE_ARRAY_RW(PRIMITIVE_TYPE, NAME) \ class Scoped##NAME##ArrayRW { \ - public: \ + public: \ explicit Scoped##NAME##ArrayRW(JNIEnv* env) \ : mEnv(env), mJavaArray(nullptr), mRawArray(nullptr) {} \ Scoped##NAME##ArrayRW(JNIEnv* env, PRIMITIVE_TYPE##Array javaArray) \ @@ -122,7 +122,7 @@ INSTANTIATE_SCOPED_PRIMITIVE_ARRAY_RO(jshort, Short); return static_cast(mEnv->GetArrayLength(mJavaArray)); \ } \ \ - private: \ + private: \ JNIEnv* mEnv; \ PRIMITIVE_TYPE##Array mJavaArray; \ PRIMITIVE_TYPE* mRawArray; \ diff --git a/common/src/jni/unbundled/include/nativehelper/scoped_utf_chars.h b/common/src/jni/unbundled/include/nativehelper/scoped_utf_chars.h index 016828568..ffd20417f 100644 --- a/common/src/jni/unbundled/include/nativehelper/scoped_utf_chars.h +++ b/common/src/jni/unbundled/include/nativehelper/scoped_utf_chars.h @@ -30,7 +30,7 @@ // return nullptr; // } class ScopedUtfChars { - public: +public: ScopedUtfChars(JNIEnv* env, jstring s) : env_(env), string_(s) { if (s == nullptr) { utf_chars_ = nullptr; @@ -58,7 +58,7 @@ class ScopedUtfChars { return utf_chars_[n]; } - private: +private: JNIEnv* env_; jstring string_; const char* utf_chars_; diff --git a/common/src/main/java/org/conscrypt/AbstractConscryptEngine.java b/common/src/main/java/org/conscrypt/AbstractConscryptEngine.java index 0f1354a93..3f0ac2914 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. diff --git a/common/src/main/java/org/conscrypt/AbstractConscryptSocket.java b/common/src/main/java/org/conscrypt/AbstractConscryptSocket.java index d9848681d..b917fb405 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; @@ -668,8 +669,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 +678,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 +688,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/AbstractSessionContext.java b/common/src/main/java/org/conscrypt/AbstractSessionContext.java index b9ef3a08e..04ff91843 100644 --- a/common/src/main/java/org/conscrypt/AbstractSessionContext.java +++ b/common/src/main/java/org/conscrypt/AbstractSessionContext.java @@ -33,7 +33,6 @@ * Supports SSL session caches. */ abstract class AbstractSessionContext implements SSLSessionContext { - /** * Maximum lifetime of a session (in seconds) after which it's considered invalid and should not * be used to for new connections. @@ -50,8 +49,7 @@ abstract class AbstractSessionContext implements SSLSessionContext { private final Map sessions = new LinkedHashMap() { @Override - protected boolean removeEldestEntry( - Map.Entry eldest) { + protected boolean removeEldestEntry(Map.Entry eldest) { // NOTE: does not take into account any session that may have become // invalid. if (maximumSize > 0 && size() > maximumSize) { @@ -81,8 +79,7 @@ public final Enumeration getIds() { // Make a copy of the IDs. final Iterator iter; synchronized (sessions) { - iter = Arrays.asList(sessions.values().toArray(new NativeSslSession[0])) - .iterator(); + iter = Arrays.asList(sessions.values().toArray(new NativeSslSession[0])).iterator(); } return new Enumeration() { private NativeSslSession next; @@ -217,7 +214,8 @@ void initSpake(SSLParametersImpl parameters) throws SSLException { try { if (isValid()) { NativeCrypto.SSL_CTX_set_spake_credential(context, pwArray, idProverArray, - idVerifierArray, isClient, handshakeLimit, sslCtxNativePointer, this); + idVerifierArray, isClient, handshakeLimit, + sslCtxNativePointer, this); } } finally { lock.writeLock().unlock(); diff --git a/common/src/main/java/org/conscrypt/ActiveSession.java b/common/src/main/java/org/conscrypt/ActiveSession.java index 4e3a4e8f6..0997b79b1 100644 --- a/common/src/main/java/org/conscrypt/ActiveSession.java +++ b/common/src/main/java/org/conscrypt/ActiveSession.java @@ -24,6 +24,7 @@ import java.security.cert.X509Certificate; import java.util.Collections; import java.util.List; + import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSessionContext; @@ -297,8 +298,8 @@ public String getApplicationProtocol() { /** * Configures the peer information once it has been received by the handshake. */ - void onPeerCertificatesReceived( - String peerHost, int peerPort, X509Certificate[] peerCertificates) { + void onPeerCertificatesReceived(String peerHost, int peerPort, + X509Certificate[] peerCertificates) { configurePeer(peerHost, peerPort, peerCertificates); } diff --git a/common/src/main/java/org/conscrypt/AddressUtils.java b/common/src/main/java/org/conscrypt/AddressUtils.java index 70287ea46..759a2fcbf 100644 --- a/common/src/main/java/org/conscrypt/AddressUtils.java +++ b/common/src/main/java/org/conscrypt/AddressUtils.java @@ -25,8 +25,25 @@ final class AddressUtils { /* * Regex that matches valid IPv4 and IPv6 addresses. */ - private static final String IP_PATTERN = "^(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9]))|" - + "(?i:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(?:\\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(?:\\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(?:\\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(?:\\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(?:\\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(?:\\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(?:\\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:)))(?:%.+)?$"; + private static final String IP_PATTERN = "^(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\\.){" + + "3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9]))|" + + "(?i:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-" + + "f]{1,4}|(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(?:\\.(?:25[0-5]|2[0-4][" + + "0-9]|1[0-9][0-9]|[1-9]?[0-9])){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{" + + "1,4}){1,2})|:(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(?:\\.(?:25[0-5]|2[" + + "0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-" + + "9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-" + + "9]?[0-9])(?:\\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:))|(?:(?:[0-" + + "9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[" + + "0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(?:\\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|" + + "[1-9]?[0-9])){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(" + + "?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(?:\\.(?:" + + "25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:" + + "(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4][0-9]|" + + "1[0-9][0-9]|[1-9]?[0-9])(?:\\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3})" + + ")|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|" + + "2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(?:\\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]" + + "?[0-9])){3}))|:)))(?:%.+)?$"; private static Pattern ipPattern; @@ -41,10 +58,8 @@ static boolean isValidSniHostname(String sniHostname) { } // Must be a FQDN that does not have a trailing dot. - return (sniHostname.equalsIgnoreCase("localhost") - || sniHostname.indexOf('.') != -1) - && !isLiteralIpAddress(sniHostname) - && !sniHostname.endsWith(".") + return (sniHostname.equalsIgnoreCase("localhost") || sniHostname.indexOf('.') != -1) + && !isLiteralIpAddress(sniHostname) && !sniHostname.endsWith(".") && sniHostname.indexOf('\0') == -1; } diff --git a/common/src/main/java/org/conscrypt/AllocatedBuffer.java b/common/src/main/java/org/conscrypt/AllocatedBuffer.java index c4d5ac6c9..39796f804 100644 --- a/common/src/main/java/org/conscrypt/AllocatedBuffer.java +++ b/common/src/main/java/org/conscrypt/AllocatedBuffer.java @@ -71,7 +71,6 @@ public static AllocatedBuffer wrap(final ByteBuffer buffer) { checkNotNull(buffer, "buffer"); return new AllocatedBuffer() { - @Override public ByteBuffer nioBuffer() { return buffer; diff --git a/common/src/main/java/org/conscrypt/ApplicationProtocolSelector.java b/common/src/main/java/org/conscrypt/ApplicationProtocolSelector.java index 739199796..cbb35d731 100644 --- a/common/src/main/java/org/conscrypt/ApplicationProtocolSelector.java +++ b/common/src/main/java/org/conscrypt/ApplicationProtocolSelector.java @@ -17,6 +17,7 @@ package org.conscrypt; import java.util.List; + import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLSocket; diff --git a/common/src/main/java/org/conscrypt/ApplicationProtocolSelectorAdapter.java b/common/src/main/java/org/conscrypt/ApplicationProtocolSelectorAdapter.java index d30bc7c4a..36c534f6b 100644 --- a/common/src/main/java/org/conscrypt/ApplicationProtocolSelectorAdapter.java +++ b/common/src/main/java/org/conscrypt/ApplicationProtocolSelectorAdapter.java @@ -20,6 +20,7 @@ import java.util.Arrays; import java.util.List; + import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLSocket; @@ -62,7 +63,7 @@ int selectApplicationProtocol(byte[] encodedProtocols) { // Select the protocol. final String selected; - if (engine != null ) { + if (engine != null) { selected = selector.selectApplicationProtocol(engine, protocols); } else { selected = selector.selectApplicationProtocol(socket, protocols); diff --git a/common/src/main/java/org/conscrypt/ArrayUtils.java b/common/src/main/java/org/conscrypt/ArrayUtils.java index 113be7893..df5ada006 100644 --- a/common/src/main/java/org/conscrypt/ArrayUtils.java +++ b/common/src/main/java/org/conscrypt/ArrayUtils.java @@ -32,14 +32,14 @@ private ArrayUtils() {} 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..3c5ee965a 100644 --- a/common/src/main/java/org/conscrypt/BufferUtils.java +++ b/common/src/main/java/org/conscrypt/BufferUtils.java @@ -16,9 +16,10 @@ 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 { @@ -100,10 +101,10 @@ static ByteBuffer getBufferLargerThan(ByteBuffer[] buffers, int minSize) { * */ static ByteBuffer copyNoConsume(ByteBuffer[] buffers, ByteBuffer destination, int maxAmount) { - checkArgument(destination.remaining() >= maxAmount, "Destination buffer too small"); - int needed = 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..0ed68b0ab 100644 --- a/common/src/main/java/org/conscrypt/CertBlocklist.java +++ b/common/src/main/java/org/conscrypt/CertBlocklist.java @@ -23,7 +23,6 @@ * A set of certificates that are blacklisted from trust. */ public interface CertBlocklist { - /** * Returns whether the given public key is in the blacklist. */ diff --git a/common/src/main/java/org/conscrypt/CertificatePriorityComparator.java b/common/src/main/java/org/conscrypt/CertificatePriorityComparator.java index 831306e1e..c47c5f190 100644 --- a/common/src/main/java/org/conscrypt/CertificatePriorityComparator.java +++ b/common/src/main/java/org/conscrypt/CertificatePriorityComparator.java @@ -40,7 +40,6 @@ */ @Internal public final class CertificatePriorityComparator implements Comparator { - /** * Map of signature algorithm OIDs to priorities. OIDs with a lower priority will be sorted * before those with higher. @@ -75,7 +74,7 @@ public final class CertificatePriorityComparator implements Comparator chain) throws CertificateEx try { checkCert(cert); } catch (CertificateException e) { - throw new CertificateException("Unacceptable certificate: " - + cert.getSubjectX500Principal(), e); + throw new CertificateException( + "Unacceptable certificate: " + cert.getSubjectX500Principal(), e); } } } @@ -77,32 +76,31 @@ private static void checkKeyLength(X509Certificate cert) throws CertificateExcep if (pubkey instanceof RSAPublicKey) { int modulusLength = ((RSAPublicKey) pubkey).getModulus().bitLength(); if (modulusLength < MIN_RSA_MODULUS_LEN_BITS) { - throw new CertificateException( - "RSA modulus is < " + MIN_RSA_MODULUS_LEN_BITS + " bits"); + throw new CertificateException("RSA modulus is < " + MIN_RSA_MODULUS_LEN_BITS + + " bits"); } } else if (pubkey instanceof ECPublicKey) { int fieldSizeBits = ((ECPublicKey) pubkey).getParams().getCurve().getField().getFieldSize(); if (fieldSizeBits < MIN_EC_FIELD_SIZE_BITS) { - throw new CertificateException( - "EC key field size is < " + MIN_EC_FIELD_SIZE_BITS + " bits"); + throw new CertificateException("EC key field size is < " + MIN_EC_FIELD_SIZE_BITS + + " bits"); } } else if (pubkey instanceof DSAPublicKey) { int pLength = ((DSAPublicKey) pubkey).getParams().getP().bitLength(); int qLength = ((DSAPublicKey) pubkey).getParams().getQ().bitLength(); if ((pLength < MIN_DSA_P_LEN_BITS) || (qLength < MIN_DSA_Q_LEN_BITS)) { - throw new CertificateException( - "DSA key length is < (" + MIN_DSA_P_LEN_BITS + ", " + MIN_DSA_Q_LEN_BITS - + ") bits"); + throw new CertificateException("DSA key length is < (" + MIN_DSA_P_LEN_BITS + ", " + + MIN_DSA_Q_LEN_BITS + ") bits"); } } else { // Unknown keys will be of type X509PublicKey. - throw new CertificateException("Rejecting unknown key class " + pubkey.getClass().getName()); + throw new CertificateException("Rejecting unknown key class " + + pubkey.getClass().getName()); } } - private static void checkSignatureAlgorithm( - X509Certificate cert) throws CertificateException { + private static void checkSignatureAlgorithm(X509Certificate cert) throws CertificateException { String oid = cert.getSigAlgOID(); for (String blacklisted : SIGNATURE_ALGORITHM_OID_BLACKLIST) { if (oid.equals(blacklisted)) { @@ -111,4 +109,3 @@ private static void checkSignatureAlgorithm( } } } - diff --git a/common/src/main/java/org/conscrypt/ClientSessionContext.java b/common/src/main/java/org/conscrypt/ClientSessionContext.java index ae8ca593b..11e6f077f 100644 --- a/common/src/main/java/org/conscrypt/ClientSessionContext.java +++ b/common/src/main/java/org/conscrypt/ClientSessionContext.java @@ -20,6 +20,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; + import javax.net.ssl.SSLContext; /** @@ -37,7 +38,8 @@ public final class ClientSessionContext extends AbstractSessionContext { * a session of one kind will remove all sessions of the other kind. */ @SuppressWarnings("serial") - private final Map> sessionsByHostAndPort = new HashMap>(); + private final Map> sessionsByHostAndPort = + new HashMap>(); private SSLClientSessionCache persistentCache; @@ -57,7 +59,7 @@ public void setPersistentCache(SSLClientSessionCache persistentCache) { * Gets the suitable session reference from the session cache container. */ synchronized NativeSslSession getCachedSession(String hostName, int port, - SSLParametersImpl sslParameters) { + SSLParametersImpl sslParameters) { if (hostName == null) { return null; } diff --git a/common/src/main/java/org/conscrypt/Conscrypt.java b/common/src/main/java/org/conscrypt/Conscrypt.java index 90c8d6c1e..b868d6959 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; } @@ -458,8 +458,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 +471,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 +522,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 +536,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 +664,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 +682,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); } /** @@ -729,8 +730,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 +747,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 +775,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 +790,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 +825,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 +848,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/ConscryptCertStore.java b/common/src/main/java/org/conscrypt/ConscryptCertStore.java index 22ce851c7..2b0bbc019 100644 --- a/common/src/main/java/org/conscrypt/ConscryptCertStore.java +++ b/common/src/main/java/org/conscrypt/ConscryptCertStore.java @@ -26,7 +26,6 @@ */ @Internal public interface ConscryptCertStore { - /** * Returns a stored CA certificate with the same name and public key as the * provided {@link X509Certificate}. diff --git a/common/src/main/java/org/conscrypt/ConscryptEngine.java b/common/src/main/java/org/conscrypt/ConscryptEngine.java index 70c39fea6..8dd220e0d 100644 --- a/common/src/main/java/org/conscrypt/ConscryptEngine.java +++ b/common/src/main/java/org/conscrypt/ConscryptEngine.java @@ -196,15 +196,15 @@ public ConscryptSession provideSession() { } ConscryptEngine(SSLParametersImpl sslParameters, PeerInfoProvider peerInfoProvider, - AliasChooser aliasChooser) { + AliasChooser aliasChooser) { this.sslParameters = sslParameters; this.peerInfoProvider = checkNotNull(peerInfoProvider, "peerInfoProvider"); this.ssl = newSsl(sslParameters, this, aliasChooser); this.networkBio = ssl.newBio(); } - private static NativeSsl newSsl( - SSLParametersImpl sslParameters, ConscryptEngine engine, AliasChooser aliasChooser) { + private static NativeSsl newSsl(SSLParametersImpl sslParameters, ConscryptEngine engine, + AliasChooser aliasChooser) { try { return NativeSsl.newInstance(sslParameters, engine, aliasChooser, engine); } catch (SSLException e) { @@ -267,7 +267,7 @@ void setChannelIdEnabled(boolean enabled) { } if (isHandshakeStarted()) { throw new IllegalStateException("Could not enable/disable Channel ID after the " - + "initial handshake has begun."); + + "initial handshake has begun."); } sslParameters.channelIdEnabled = enabled; } @@ -319,7 +319,7 @@ void setChannelIdPrivateKey(PrivateKey privateKey) { synchronized (ssl) { if (isHandshakeStarted()) { throw new IllegalStateException("Could not change Channel ID private key " - + "after the initial handshake has begun."); + + "after the initial handshake has begun."); } if (privateKey == null) { @@ -654,7 +654,7 @@ public boolean getWantClientAuth() { public boolean isInboundDone() { synchronized (ssl) { return (state == STATE_CLOSED || state == STATE_CLOSED_INBOUND - || ssl.wasShutdownReceived()) + || ssl.wasShutdownReceived()) && (pendingInboundCleartextBytes() == 0); } } @@ -663,7 +663,7 @@ public boolean isInboundDone() { public boolean isOutboundDone() { synchronized (ssl) { return (state == STATE_CLOSED || state == STATE_CLOSED_OUTBOUND - || ssl.wasShutdownSent()) + || ssl.wasShutdownSent()) && (pendingOutboundEncryptedBytes() == 0); } } @@ -692,8 +692,8 @@ public void setNeedClientAuth(boolean need) { public void setUseClientMode(boolean mode) { synchronized (ssl) { if (isHandshakeStarted()) { - throw new IllegalArgumentException( - "Can not change mode after handshake: state == " + state); + throw new IllegalArgumentException("Can not change mode after handshake: state == " + + state); } transitionTo(STATE_MODE_SET); sslParameters.setUseClientMode(mode); @@ -730,7 +730,7 @@ public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dsts) throws SSLExcep @Override public SSLEngineResult unwrap(final ByteBuffer src, final ByteBuffer[] dsts, final int offset, - final int length) throws SSLException { + final int length) throws SSLException { synchronized (ssl) { try { return unwrap(singleSrcBuffer(src), 0, 1, dsts, offset, length); @@ -749,7 +749,7 @@ SSLEngineResult unwrap(final ByteBuffer[] srcs, final ByteBuffer[] dsts) throws @Override SSLEngineResult unwrap(final ByteBuffer[] srcs, int srcsOffset, final int srcsLength, - final ByteBuffer[] dsts, final int dstsOffset, final int dstsLength) + final ByteBuffer[] dsts, final int dstsOffset, final int dstsLength) throws SSLException { checkArgument(srcs != null, "srcs is null"); checkArgument(dsts != null, "dsts is null"); @@ -892,9 +892,10 @@ SSLEngineResult unwrap(final ByteBuffer[] srcs, int srcsOffset, final int srcsLe // inbound direction as closed and shut down the SSL object closeAll(); return new SSLEngineResult(Status.CLOSED, - pendingOutboundEncryptedBytes() > 0 ? NEED_WRAP - : NOT_HANDSHAKING, - bytesConsumed, bytesProduced); + pendingOutboundEncryptedBytes() > 0 + ? NEED_WRAP + : NOT_HANDSHAKING, + bytesConsumed, bytesProduced); } default: { // Should never get here. @@ -926,10 +927,11 @@ SSLEngineResult unwrap(final ByteBuffer[] srcs, int srcsOffset, final int srcsLe if (pendingCleartextBytes > 0) { // We filled all buffers but there is still some data pending in the BIO buffer, // return BUFFER_OVERFLOW. - return new SSLEngineResult(BUFFER_OVERFLOW, + return new SSLEngineResult( + BUFFER_OVERFLOW, mayFinishHandshake(handshakeStatus == FINISHED - ? handshakeStatus - : getHandshakeStatusInternal()), + ? handshakeStatus + : getHandshakeStatusInternal()), bytesConsumed, bytesProduced); } @@ -1216,7 +1218,9 @@ private long directByteBufferAddress(ByteBuffer directBuffer, int pos) { } private SSLEngineResult readPendingBytesFromBIO(ByteBuffer dst, int bytesConsumed, - int bytesProduced, SSLEngineResult.HandshakeStatus status) throws SSLException { + int bytesProduced, + SSLEngineResult.HandshakeStatus status) + throws SSLException { try { // Check to see if the engine wrote data into the network BIO int pendingNet = pendingOutboundEncryptedBytes(); @@ -1224,9 +1228,10 @@ private SSLEngineResult readPendingBytesFromBIO(ByteBuffer dst, int bytesConsume // Do we have enough room in dst to write encrypted data? int capacity = dst.remaining(); if (capacity < pendingNet) { - return new SSLEngineResult(BUFFER_OVERFLOW, - mayFinishHandshake( - status == FINISHED ? status : getHandshakeStatus(pendingNet)), + return new SSLEngineResult( + BUFFER_OVERFLOW, + mayFinishHandshake(status == FINISHED ? status + : getHandshakeStatus(pendingNet)), bytesConsumed, bytesProduced); } @@ -1243,9 +1248,10 @@ private SSLEngineResult readPendingBytesFromBIO(ByteBuffer dst, int bytesConsume pendingNet -= produced; } - return new SSLEngineResult(getEngineStatus(), - mayFinishHandshake( - status == FINISHED ? status : getHandshakeStatus(pendingNet)), + return new SSLEngineResult( + getEngineStatus(), + mayFinishHandshake(status == FINISHED ? status + : getHandshakeStatus(pendingNet)), bytesConsumed, bytesProduced); } return null; @@ -1362,8 +1368,9 @@ private SSLException newSslExceptionWithMessage(String err) { } private SSLEngineResult newResult(int bytesConsumed, int bytesProduced, - SSLEngineResult.HandshakeStatus status) throws SSLException { - return new SSLEngineResult(getEngineStatus(), + SSLEngineResult.HandshakeStatus status) throws SSLException { + return new SSLEngineResult( + getEngineStatus(), mayFinishHandshake(status == FINISHED ? status : getHandshakeStatusInternal()), bytesConsumed, bytesProduced); } @@ -1435,8 +1442,8 @@ public SSLEngineResult wrap(ByteBuffer[] srcs, int srcsOffset, int srcsLength, B int dataLength = (int) min(BufferUtils.remaining(srcs), SSL3_RT_MAX_PLAIN_LENGTH); if (dst.remaining() < calculateOutNetBufSize(dataLength)) { - return new SSLEngineResult( - Status.BUFFER_OVERFLOW, getHandshakeStatusInternal(), 0, 0); + return new SSLEngineResult(Status.BUFFER_OVERFLOW, getHandshakeStatusInternal(), 0, + 0); } int bytesProduced = 0; @@ -1457,8 +1464,8 @@ public SSLEngineResult wrap(ByteBuffer[] srcs, int srcsOffset, int srcsLength, B // direct one. // TODO(): use bufferAllocator if set. // https://github.com/google/conscrypt/issues/974 - outputBuffer = BufferUtils.copyNoConsume( - srcs, getOrCreateLazyDirectBuffer(), SSL3_RT_MAX_PLAIN_LENGTH); + outputBuffer = BufferUtils.copyNoConsume(srcs, getOrCreateLazyDirectBuffer(), + SSL3_RT_MAX_PLAIN_LENGTH); isCopy = true; } final SSLEngineResult pendingNetResult; @@ -1472,8 +1479,8 @@ public SSLEngineResult wrap(ByteBuffer[] srcs, int srcsOffset, int srcsLength, B BufferUtils.consume(srcs, bytesConsumed); } - pendingNetResult = readPendingBytesFromBIO( - dst, bytesConsumed, bytesProduced, handshakeStatus); + pendingNetResult = readPendingBytesFromBIO(dst, bytesConsumed, bytesProduced, + handshakeStatus); if (pendingNetResult != null) { if (pendingNetResult.getStatus() != OK) { return pendingNetResult; @@ -1503,7 +1510,7 @@ public SSLEngineResult wrap(ByteBuffer[] srcs, int srcsOffset, int srcsLength, B return pendingNetResult != null ? pendingNetResult : new SSLEngineResult(getEngineStatus(), NEED_UNWRAP, - bytesConsumed, bytesProduced); + bytesConsumed, bytesProduced); case SSL_ERROR_WANT_WRITE: // SSL_ERROR_WANT_WRITE typically means that the underlying // transport is not writable @@ -1570,9 +1577,9 @@ public void onSSLStateChange(int type, int val) { } case SSL_CB_HANDSHAKE_DONE: { if (state != STATE_HANDSHAKE_STARTED - && state != STATE_READY_HANDSHAKE_CUT_THROUGH) { - throw new IllegalStateException( - "Completed handshake while in mode " + state); + && state != STATE_READY_HANDSHAKE_CUT_THROUGH) { + throw new IllegalStateException("Completed handshake while in mode " + + state); } transitionTo(STATE_HANDSHAKE_COMPLETED); break; @@ -1649,7 +1656,8 @@ public void verifyCertificateChain(byte[][] certChain, String authMethod) @Override public void clientCertificateRequested(byte[] keyTypeBytes, int[] signatureAlgs, - byte[][] asn1DerEncodedPrincipals) throws CertificateEncodingException, SSLException { + byte[][] asn1DerEncodedPrincipals) + throws CertificateEncodingException, SSLException { ssl.chooseClientCertificate(keyTypeBytes, signatureAlgs, asn1DerEncodedPrincipals); } @@ -1699,8 +1707,8 @@ public String chooseServerAlias(X509KeyManager keyManager, String keyType) { } @Override - public String chooseClientAlias( - X509KeyManager keyManager, X500Principal[] issuers, String[] keyTypes) { + public String chooseClientAlias(X509KeyManager keyManager, X500Principal[] issuers, + String[] keyTypes) { if (keyManager instanceof X509ExtendedKeyManager) { X509ExtendedKeyManager ekm = (X509ExtendedKeyManager) keyManager; return ekm.chooseEngineClientAlias(keyTypes, issuers, this); diff --git a/common/src/main/java/org/conscrypt/ConscryptEngineSocket.java b/common/src/main/java/org/conscrypt/ConscryptEngineSocket.java index db1376d68..c46a2cf7c 100644 --- a/common/src/main/java/org/conscrypt/ConscryptEngineSocket.java +++ b/common/src/main/java/org/conscrypt/ConscryptEngineSocket.java @@ -90,36 +90,36 @@ class ConscryptEngineSocket extends OpenSSLSocketImpl implements SSLParametersIm } ConscryptEngineSocket(String hostname, int port, InetAddress clientAddress, int clientPort, - SSLParametersImpl sslParameters) throws IOException { + SSLParametersImpl sslParameters) throws IOException { super(hostname, port, clientAddress, clientPort); engine = newEngine(sslParameters, this); } ConscryptEngineSocket(InetAddress address, int port, InetAddress clientAddress, int clientPort, - SSLParametersImpl sslParameters) throws IOException { + SSLParametersImpl sslParameters) throws IOException { super(address, port, clientAddress, clientPort); engine = newEngine(sslParameters, this); } ConscryptEngineSocket(Socket socket, String hostname, int port, boolean autoClose, - SSLParametersImpl sslParameters) throws IOException { + SSLParametersImpl sslParameters) throws IOException { super(socket, hostname, port, autoClose); engine = newEngine(sslParameters, this); } - private static ConscryptEngine newEngine( - SSLParametersImpl sslParameters, final ConscryptEngineSocket socket) { + private static ConscryptEngine newEngine(SSLParametersImpl sslParameters, + final ConscryptEngineSocket socket) { SSLParametersImpl modifiedParams; if (sslParameters.isSpake()) { modifiedParams = sslParameters.cloneWithSpake(); } else if (Platform.supportsX509ExtendedTrustManager()) { modifiedParams = sslParameters.cloneWithTrustManager( - getDelegatingTrustManager(sslParameters.getX509TrustManager(), socket)); + getDelegatingTrustManager(sslParameters.getX509TrustManager(), socket)); } else { modifiedParams = sslParameters; } ConscryptEngine engine = - new ConscryptEngine(modifiedParams, socket.peerInfoProvider(), socket); + new ConscryptEngine(modifiedParams, socket.peerInfoProvider(), socket); // When the handshake completes, notify any listeners. engine.setHandshakeListener(new HandshakeListener() { @@ -143,35 +143,42 @@ public void onHandshakeFinished() { // the SSLEngine-receiving methods, but our callers expect the SSLSocket-receiving // methods to get called. private static X509TrustManager getDelegatingTrustManager(final X509TrustManager delegate, - final ConscryptEngineSocket socket) { + final ConscryptEngineSocket socket) { if (delegate instanceof X509ExtendedTrustManager) { final X509ExtendedTrustManager extendedDelegate = (X509ExtendedTrustManager) delegate; return new X509ExtendedTrustManager() { - @Override public void checkClientTrusted(X509Certificate[] x509Certificates, - String s, Socket socket) throws CertificateException { + @Override + public void checkClientTrusted(X509Certificate[] x509Certificates, String s, + Socket socket) throws CertificateException { throw new AssertionError("Should not be called"); } - @Override public void checkServerTrusted(X509Certificate[] x509Certificates, - String s, Socket socket) throws CertificateException { + @Override + public void checkServerTrusted(X509Certificate[] x509Certificates, String s, + Socket socket) throws CertificateException { throw new AssertionError("Should not be called"); } - @Override public void checkClientTrusted(X509Certificate[] x509Certificates, - String s, SSLEngine sslEngine) throws CertificateException { + @Override + public void checkClientTrusted(X509Certificate[] x509Certificates, String s, + SSLEngine sslEngine) throws CertificateException { extendedDelegate.checkClientTrusted(x509Certificates, s, socket); } - @Override public void checkServerTrusted(X509Certificate[] x509Certificates, - String s, SSLEngine sslEngine) throws CertificateException { + @Override + public void checkServerTrusted(X509Certificate[] x509Certificates, String s, + SSLEngine sslEngine) throws CertificateException { extendedDelegate.checkServerTrusted(x509Certificates, s, socket); } - @Override public void checkClientTrusted(X509Certificate[] x509Certificates, - String s) throws CertificateException { + @Override + public void checkClientTrusted(X509Certificate[] x509Certificates, String s) + throws CertificateException { extendedDelegate.checkClientTrusted(x509Certificates, s); } - @Override public void checkServerTrusted(X509Certificate[] x509Certificates, - String s) throws CertificateException { + @Override + public void checkServerTrusted(X509Certificate[] x509Certificates, String s) + throws CertificateException { extendedDelegate.checkServerTrusted(x509Certificates, s); } - @Override public X509Certificate[] getAcceptedIssuers() { + @Override + public X509Certificate[] getAcceptedIssuers() { return extendedDelegate.getAcceptedIssuers(); } }; @@ -256,8 +263,8 @@ private void doHandshake() throws IOException { break; } default: { - throw new IllegalStateException( - "Unknown handshake status: " + engine.getHandshakeStatus()); + throw new IllegalStateException("Unknown handshake status: " + + engine.getHandshakeStatus()); } } } @@ -304,7 +311,8 @@ private int transitionTo(int newState) { case STATE_READY_HANDSHAKE_CUT_THROUGH: if (handshakeStartedMillis > 0) { StatsLog statsLog = Platform.getStatsLog(); - statsLog.countTlsHandshake(true, engine.getSession().getProtocol(), + statsLog.countTlsHandshake( + true, engine.getSession().getProtocol(), engine.getSession().getCipherSuite(), Platform.getMillisSinceBoot() - handshakeStartedMillis); handshakeStartedMillis = 0; @@ -320,7 +328,8 @@ private int transitionTo(int newState) { if (handshakeStartedMillis > 0) { StatsLog statsLog = Platform.getStatsLog(); // Handshake was in progress and so must have failed. - statsLog.countTlsHandshake(false, "TLS_PROTO_FAILED", "TLS_CIPHER_FAILED", + statsLog.countTlsHandshake( + false, "TLS_PROTO_FAILED", "TLS_CIPHER_FAILED", Platform.getMillisSinceBoot() - handshakeStartedMillis); handshakeStartedMillis = 0; } @@ -606,9 +615,8 @@ private void waitForHandshake() throws IOException { synchronized (stateLock) { while (state != STATE_READY - // Waiting threads are allowed to compete with handshake listeners for access. - && state != STATE_READY_HANDSHAKE_CUT_THROUGH - && state != STATE_CLOSED) { + // Waiting threads are allowed to compete with handshake listeners for access. + && state != STATE_READY_HANDSHAKE_CUT_THROUGH && state != STATE_CLOSED) { try { stateLock.wait(); } catch (InterruptedException e) { @@ -714,7 +722,8 @@ private void writeInternal(ByteBuffer buffer) throws IOException { } if (target.position() != engineResult.bytesProduced()) { throw new SSLException("Engine bytesProduced " + engineResult.bytesProduced() - + " does not match bytes written " + target.position()); + + " does not match bytes written " + + target.position()); } len -= engineResult.bytesConsumed(); if (len != buffer.remaining()) { @@ -779,7 +788,8 @@ private final class SSLInputStream extends InputStream { fromEngine = allocatedBuffer.nioBuffer(); } else { allocatedBuffer = null; - fromEngine = ByteBuffer.allocateDirect(engine.getSession().getApplicationBufferSize()); + fromEngine = + ByteBuffer.allocateDirect(engine.getSession().getApplicationBufferSize()); } // Initially fromEngine.remaining() == 0. fromEngine.flip(); @@ -846,7 +856,7 @@ public int available() throws IOException { } private boolean isHandshaking(HandshakeStatus status) { - switch(status) { + switch (status) { case NEED_TASK: case NEED_WRAP: case NEED_UNWRAP: @@ -932,8 +942,8 @@ && isHandshakeFinished()) { } default: { // Anything else is an error. - throw new SSLException( - "Unexpected engine result " + engineResult.getStatus()); + throw new SSLException("Unexpected engine result " + + engineResult.getStatus()); } } @@ -980,8 +990,8 @@ private int readFromSocket() throws IOException { // appropriate. int pos = fromSocket.position(); int lim = fromSocket.limit(); - int read = socketInputStream.read( - fromSocket.array(), fromSocketArrayOffset + pos, lim - pos); + int read = socketInputStream.read(fromSocket.array(), fromSocketArrayOffset + pos, + lim - pos); if (read > 0) { fromSocket.position(pos + read); diff --git a/common/src/main/java/org/conscrypt/ConscryptFileDescriptorSocket.java b/common/src/main/java/org/conscrypt/ConscryptFileDescriptorSocket.java index c457a1636..ba5a525cb 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(); } } @@ -805,7 +803,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 +856,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 +1131,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 +1163,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 +1202,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 +1215,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/ConscryptHostnameVerifier.java b/common/src/main/java/org/conscrypt/ConscryptHostnameVerifier.java index 277226934..d4d288fa9 100644 --- a/common/src/main/java/org/conscrypt/ConscryptHostnameVerifier.java +++ b/common/src/main/java/org/conscrypt/ConscryptHostnameVerifier.java @@ -17,6 +17,7 @@ package org.conscrypt; import java.security.cert.X509Certificate; + import javax.net.ssl.SSLSession; /** @@ -25,11 +26,9 @@ * verification is needed, without any use of default rules. */ public interface ConscryptHostnameVerifier { - - /** - * Returns whether the given hostname is allowable given the peer's authentication information - * from the given session. - */ - boolean verify(X509Certificate[] certs, String hostname, SSLSession session); - + /** + * Returns whether the given hostname is allowable given the peer's authentication information + * from the given session. + */ + boolean verify(X509Certificate[] certs, String hostname, SSLSession session); } diff --git a/common/src/main/java/org/conscrypt/ConscryptServerSocket.java b/common/src/main/java/org/conscrypt/ConscryptServerSocket.java index 97588359e..09fa31e92 100644 --- a/common/src/main/java/org/conscrypt/ConscryptServerSocket.java +++ b/common/src/main/java/org/conscrypt/ConscryptServerSocket.java @@ -19,6 +19,7 @@ import java.io.IOException; import java.net.InetAddress; import java.net.Socket; + import javax.net.ssl.SSLServerSocket; /** @@ -33,23 +34,19 @@ final class ConscryptServerSocket extends SSLServerSocket { this.sslParameters = sslParameters; } - ConscryptServerSocket(int port, SSLParametersImpl sslParameters) - throws IOException { + ConscryptServerSocket(int port, SSLParametersImpl sslParameters) throws IOException { super(port); this.sslParameters = sslParameters; } ConscryptServerSocket(int port, int backlog, SSLParametersImpl sslParameters) - throws IOException { + throws IOException { super(port, backlog); this.sslParameters = sslParameters; } - ConscryptServerSocket(int port, - int backlog, - InetAddress iAddress, - SSLParametersImpl sslParameters) - throws IOException { + ConscryptServerSocket(int port, int backlog, InetAddress iAddress, + SSLParametersImpl sslParameters) throws IOException { super(port, backlog, iAddress); this.sslParameters = sslParameters; } @@ -120,14 +117,14 @@ public String[] getEnabledCipherSuites() { * Enables/disables the TLS Channel ID extension for this server socket. */ void setChannelIdEnabled(boolean enabled) { - channelIdEnabled = enabled; + channelIdEnabled = enabled; } /** * Checks whether the TLS Channel ID extension is enabled for this server socket. */ boolean isChannelIdEnabled() { - return channelIdEnabled; + return channelIdEnabled; } /** diff --git a/common/src/main/java/org/conscrypt/ConscryptSession.java b/common/src/main/java/org/conscrypt/ConscryptSession.java index ce89b418b..e25140598 100644 --- a/common/src/main/java/org/conscrypt/ConscryptSession.java +++ b/common/src/main/java/org/conscrypt/ConscryptSession.java @@ -18,6 +18,7 @@ import java.security.cert.X509Certificate; import java.util.List; + import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSession; @@ -26,32 +27,30 @@ * by Conscrypt. */ interface ConscryptSession extends SSLSession { - - String getRequestedServerName(); - - /** - * Returns the OCSP stapled response. Returns a copy of the internal arrays. - * - * The method signature matches - * Java - * 9. - * - * @see RFC 6066 - * @see RFC 6961 - */ - List getStatusResponses(); - - /** - * Returns the signed certificate timestamp (SCT) received from the peer. Returns a - * copy of the internal array. - * - * @see RFC 6962 - */ - byte[] getPeerSignedCertificateTimestamp(); - - @Override - X509Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException; - - String getApplicationProtocol(); + String getRequestedServerName(); + + /** + * Returns the OCSP stapled response. Returns a copy of the internal arrays. + * + * The method signature matches + * Java + * 9. + * + * @see RFC 6066 + * @see RFC 6961 + */ + List getStatusResponses(); + + /** + * Returns the signed certificate timestamp (SCT) received from the peer. Returns a + * copy of the internal array. + * + * @see RFC 6962 + */ + byte[] getPeerSignedCertificateTimestamp(); + + @Override X509Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException; + + String getApplicationProtocol(); } diff --git a/common/src/main/java/org/conscrypt/CryptoUpcalls.java b/common/src/main/java/org/conscrypt/CryptoUpcalls.java index 530618249..f568260a3 100644 --- a/common/src/main/java/org/conscrypt/CryptoUpcalls.java +++ b/common/src/main/java/org/conscrypt/CryptoUpcalls.java @@ -26,6 +26,7 @@ import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; + import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; @@ -69,7 +70,7 @@ static byte[] ecSignDigestWithPrivateKey(PrivateKey javaKey, byte[] message) { } private static byte[] signDigestWithPrivateKey(PrivateKey javaKey, byte[] message, - String algorithm) { + String algorithm) { Signature signature; // Since this is a delegated key, we cannot handle providing a signature using this key. @@ -126,15 +127,15 @@ private static byte[] signDigestWithPrivateKey(PrivateKey javaKey, byte[] messag return signature.sign(); } catch (Exception e) { logger.log(Level.WARNING, - "Exception while signing message with " + javaKey.getAlgorithm() - + " private key:", - e); + "Exception while signing message with " + javaKey.getAlgorithm() + + " private key:", + e); return null; } } static byte[] rsaSignDigestWithPrivateKey(PrivateKey javaKey, int openSSLPadding, - byte[] message) { + byte[] message) { // An RSA cipher + ENCRYPT_MODE produces a standard RSA signature return rsaOpWithPrivateKey(javaKey, openSSLPadding, Cipher.ENCRYPT_MODE, message); } @@ -144,7 +145,7 @@ static byte[] rsaDecryptWithPrivateKey(PrivateKey javaKey, int openSSLPadding, b } private static byte[] rsaOpWithPrivateKey(PrivateKey javaKey, int openSSLPadding, - int cipherMode, byte[] input) { + int cipherMode, byte[] input) { String keyAlgorithm = javaKey.getAlgorithm(); if (!"RSA".equals(keyAlgorithm)) { logger.warning("Unexpected key type: " + keyAlgorithm); @@ -200,7 +201,8 @@ private static byte[] rsaOpWithPrivateKey(PrivateKey javaKey, int openSSLPadding c = Cipher.getInstance(transformation, p); c.init(cipherMode, javaKey); break; - } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) { + } catch (NoSuchAlgorithmException | NoSuchPaddingException + | InvalidKeyException e) { c = null; } } @@ -214,9 +216,9 @@ private static byte[] rsaOpWithPrivateKey(PrivateKey javaKey, int openSSLPadding return c.doFinal(input); } catch (Exception e) { logger.log(Level.WARNING, - "Exception while decrypting message with " + javaKey.getAlgorithm() - + " private key using " + transformation + ":", - e); + "Exception while decrypting message with " + javaKey.getAlgorithm() + + " private key using " + transformation + ":", + e); return null; } } diff --git a/common/src/main/java/org/conscrypt/DESEDESecretKeyFactory.java b/common/src/main/java/org/conscrypt/DESEDESecretKeyFactory.java index 199f516c3..71a2fb547 100644 --- a/common/src/main/java/org/conscrypt/DESEDESecretKeyFactory.java +++ b/common/src/main/java/org/conscrypt/DESEDESecretKeyFactory.java @@ -19,6 +19,7 @@ import java.security.InvalidKeyException; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; + import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactorySpi; import javax.crypto.spec.DESedeKeySpec; @@ -30,7 +31,6 @@ */ @Internal public class DESEDESecretKeyFactory extends SecretKeyFactorySpi { - public DESEDESecretKeyFactory() {} @Override @@ -53,21 +53,23 @@ protected SecretKey engineGenerateSecret(KeySpec keySpec) throws InvalidKeySpecE DESedeKeySpec desKeySpec = (DESedeKeySpec) keySpec; return new SecretKeySpec(desKeySpec.getKey(), "DESEDE"); } else { - throw new InvalidKeySpecException( - "Unsupported KeySpec class: " + keySpec.getClass().getName()); + throw new InvalidKeySpecException("Unsupported KeySpec class: " + + keySpec.getClass().getName()); } } @Override protected KeySpec engineGetKeySpec(SecretKey secretKey, - @SuppressWarnings("rawtypes") Class aClass) throws InvalidKeySpecException { + @SuppressWarnings("rawtypes") Class aClass) + throws InvalidKeySpecException { if (secretKey == null) { throw new InvalidKeySpecException("Null SecretKey"); } if (aClass == SecretKeySpec.class) { try { if (!DESedeKeySpec.isParityAdjusted(secretKey.getEncoded(), 0)) { - throw new InvalidKeySpecException("SecretKey is not a parity-adjusted DESEDE key"); + throw new InvalidKeySpecException( + "SecretKey is not a parity-adjusted DESEDE key"); } } catch (InvalidKeyException e) { throw new InvalidKeySpecException(e); diff --git a/common/src/main/java/org/conscrypt/DefaultSSLContextImpl.java b/common/src/main/java/org/conscrypt/DefaultSSLContextImpl.java index 0fa2a30aa..733735bd6 100644 --- a/common/src/main/java/org/conscrypt/DefaultSSLContextImpl.java +++ b/common/src/main/java/org/conscrypt/DefaultSSLContextImpl.java @@ -25,6 +25,7 @@ import java.security.KeyManagementException; import java.security.KeyStore; import java.security.SecureRandom; + import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.TrustManager; @@ -35,7 +36,6 @@ */ @Internal public class DefaultSSLContextImpl extends OpenSSLContextImpl { - /** * Accessed by SSLContextImpl(DefaultSSLContextImpl) holding the * DefaultSSLContextImpl.class monitor @@ -110,8 +110,8 @@ TrustManager[] getTrustManagers() throws GeneralSecurityException, IOException { } @Override - public void engineInit(KeyManager[] kms, TrustManager[] tms, - SecureRandom sr) throws KeyManagementException { + public void engineInit(KeyManager[] kms, TrustManager[] tms, SecureRandom sr) + throws KeyManagementException { throw new KeyManagementException("Do not init() the default SSLContext "); } diff --git a/common/src/main/java/org/conscrypt/DuckTypedHpkeSpi.java b/common/src/main/java/org/conscrypt/DuckTypedHpkeSpi.java index a46dc9dd7..be98b49b0 100644 --- a/common/src/main/java/org/conscrypt/DuckTypedHpkeSpi.java +++ b/common/src/main/java/org/conscrypt/DuckTypedHpkeSpi.java @@ -33,140 +33,142 @@ */ @Internal public class DuckTypedHpkeSpi implements HpkeSpi { - private final Object delegate; - private final Map methods = new HashMap<>(); - - private DuckTypedHpkeSpi(Object delegate) throws NoSuchMethodException { - this.delegate = delegate; - - Class sourceClass = delegate.getClass(); - for (Method targetMethod : HpkeSpi.class.getMethods()) { - if (targetMethod.isSynthetic()) { - continue; - } - if (targetMethod.getName().equals("engineInitSenderForTesting")) { - continue; - } - - Method sourceMethod = - sourceClass.getMethod(targetMethod.getName(), targetMethod.getParameterTypes()); - // Check that the return types match too. - Class sourceReturnType = sourceMethod.getReturnType(); - Class targetReturnType = targetMethod.getReturnType(); - if (!targetReturnType.isAssignableFrom(sourceReturnType)) { - throw new NoSuchMethodException(sourceMethod + " return value (" + sourceReturnType - + ") incompatible with target return value (" + targetReturnType + ")"); - } - methods.put(sourceMethod.getName(), sourceMethod); + private final Object delegate; + private final Map methods = new HashMap<>(); + + private DuckTypedHpkeSpi(Object delegate) throws NoSuchMethodException { + this.delegate = delegate; + + Class sourceClass = delegate.getClass(); + for (Method targetMethod : HpkeSpi.class.getMethods()) { + if (targetMethod.isSynthetic()) { + continue; + } + if (targetMethod.getName().equals("engineInitSenderForTesting")) { + continue; + } + + Method sourceMethod = + sourceClass.getMethod(targetMethod.getName(), targetMethod.getParameterTypes()); + // Check that the return types match too. + Class sourceReturnType = sourceMethod.getReturnType(); + Class targetReturnType = targetMethod.getReturnType(); + if (!targetReturnType.isAssignableFrom(sourceReturnType)) { + throw new NoSuchMethodException(sourceMethod + " return value (" + sourceReturnType + + ") incompatible with target return value (" + + targetReturnType + ")"); + } + methods.put(sourceMethod.getName(), sourceMethod); + } } - } - public static DuckTypedHpkeSpi newInstance(Object delegate) { - try { - return new DuckTypedHpkeSpi(delegate); - } catch (Exception ignored) { - return null; + public static DuckTypedHpkeSpi newInstance(Object delegate) { + try { + return new DuckTypedHpkeSpi(delegate); + } catch (Exception ignored) { + return null; + } } - } - private Object invoke(String methodName, Object... args) throws InvocationTargetException { - Method method = methods.get(methodName); - if (method == null) { - throw new IllegalStateException("DuckTypedHpkSpi internal error"); + private Object invoke(String methodName, Object... args) throws InvocationTargetException { + Method method = methods.get(methodName); + if (method == null) { + throw new IllegalStateException("DuckTypedHpkSpi internal error"); + } + try { + return method.invoke(delegate, args); + } catch (IllegalAccessException e) { + throw new IllegalStateException("DuckTypedHpkSpi internal error", e); + } catch (InvocationTargetException e) { + if (e.getCause() instanceof RuntimeException) { + throw (RuntimeException) e.getCause(); + } + throw e; + } } - try { - return method.invoke(delegate, args); - } catch (IllegalAccessException e) { - throw new IllegalStateException("DuckTypedHpkSpi internal error", e); - } catch (InvocationTargetException e) { - if (e.getCause() instanceof RuntimeException){ - throw (RuntimeException) e.getCause(); - } - throw e; + + private void invokeWithPossibleInvalidKey(String methodName, Object... args) + throws InvalidKeyException { + try { + invoke(methodName, args); + } catch (InvocationTargetException e) { + Throwable cause = e.getCause(); + if (cause instanceof InvalidKeyException) { + throw (InvalidKeyException) cause; + } + throw new IllegalStateException(cause); + } } - } - - private void invokeWithPossibleInvalidKey(String methodName, Object... args) - throws InvalidKeyException { - try { - invoke(methodName, args); - } catch (InvocationTargetException e) { - Throwable cause = e.getCause(); - if (cause instanceof InvalidKeyException){ - throw (InvalidKeyException) cause; - } - throw new IllegalStateException(cause); + + private Object invokeWithPossibleGeneralSecurity(String methodName, Object... args) + throws GeneralSecurityException { + try { + return invoke(methodName, args); + } catch (InvocationTargetException e) { + Throwable cause = e.getCause(); + if (cause instanceof GeneralSecurityException) { + throw (GeneralSecurityException) cause; + } + throw new IllegalStateException(cause); + } } - } - - private Object invokeWithPossibleGeneralSecurity(String methodName, Object... args) - throws GeneralSecurityException { - try { - return invoke(methodName, args); - } catch (InvocationTargetException e) { - Throwable cause = e.getCause(); - if (cause instanceof GeneralSecurityException){ - throw (GeneralSecurityException) cause; - } - throw new IllegalStateException(cause); + + private Object invokeNoChecked(String methodName, Object... args) { + try { + return invoke(methodName, args); + } catch (InvocationTargetException e) { + throw new IllegalStateException(e.getCause()); + } + } + + // Visible for testing + public Object getDelegate() { + return delegate; + } + + @Override + public void engineInitSender(PublicKey recipientKey, byte[] info, PrivateKey senderKey, + byte[] psk, byte[] pskId) throws InvalidKeyException { + invokeWithPossibleInvalidKey("engineInitSender", recipientKey, info, senderKey, psk, pskId); + } + + @Override + public void engineInitSenderForTesting(PublicKey recipientKey, byte[] info, + PrivateKey senderKey, byte[] psk, byte[] pskId, + byte[] sKe) throws InvalidKeyException { + if (!methods.containsKey("engineInitSenderForTesting")) { + throw new UnsupportedOperationException( + "engineInitSenderForTesting is not supported by the delegate"); + } + invokeWithPossibleInvalidKey("engineInitSenderForTesting", recipientKey, info, senderKey, + psk, pskId, sKe); + } + + @Override + public void engineInitRecipient(byte[] encapsulated, PrivateKey key, byte[] info, + PublicKey senderKey, byte[] psk, byte[] psk_id) + throws InvalidKeyException { + invokeWithPossibleInvalidKey("engineInitRecipient", encapsulated, key, info, senderKey, psk, + psk_id); + } + + @Override + public byte[] engineSeal(byte[] plaintext, byte[] aad) { + return (byte[]) invokeNoChecked("engineSeal", plaintext, aad); + } + + @Override + public byte[] engineExport(int length, byte[] exporterContext) { + return (byte[]) invokeNoChecked("engineExport", length, exporterContext); + } + + @Override + public byte[] engineOpen(byte[] ciphertext, byte[] aad) throws GeneralSecurityException { + return (byte[]) invokeWithPossibleGeneralSecurity("engineOpen", ciphertext, aad); } - } - private Object invokeNoChecked(String methodName, Object... args) { - try { - return invoke(methodName, args); - } catch (InvocationTargetException e) { - throw new IllegalStateException(e.getCause()); + @Override + public byte[] getEncapsulated() { + return (byte[]) invokeNoChecked("getEncapsulated"); } - } - - // Visible for testing - public Object getDelegate() { - return delegate; - } - - @Override - public void engineInitSender( - PublicKey recipientKey, byte[] info, PrivateKey senderKey, byte[] psk, byte[] pskId) - throws InvalidKeyException { - invokeWithPossibleInvalidKey("engineInitSender", recipientKey, info, senderKey, psk, pskId); - } - - @Override - public void engineInitSenderForTesting(PublicKey recipientKey, byte[] info, PrivateKey senderKey, - byte[] psk, byte[] pskId, byte[] sKe) throws InvalidKeyException { - if (!methods.containsKey("engineInitSenderForTesting")) { - throw new UnsupportedOperationException( - "engineInitSenderForTesting is not supported by the delegate"); - } - invokeWithPossibleInvalidKey("engineInitSenderForTesting", - recipientKey, info, senderKey, psk, pskId, sKe); - } - - @Override - public void engineInitRecipient(byte[] encapsulated, PrivateKey key, byte[] info, - PublicKey senderKey, byte[] psk, byte[] psk_id) throws InvalidKeyException { - invokeWithPossibleInvalidKey( - "engineInitRecipient", encapsulated, key, info, senderKey, psk, psk_id); - } - - @Override - public byte[] engineSeal(byte[] plaintext, byte[] aad) { - return (byte[]) invokeNoChecked("engineSeal", plaintext, aad); - } - - @Override - public byte[] engineExport(int length, byte[] exporterContext) { - return (byte[]) invokeNoChecked("engineExport", length, exporterContext); - } - - @Override - public byte[] engineOpen(byte[] ciphertext, byte[] aad) throws GeneralSecurityException { - return (byte[]) invokeWithPossibleGeneralSecurity("engineOpen", ciphertext, aad); - } - - @Override - public byte[] getEncapsulated() { - return (byte[]) invokeNoChecked("getEncapsulated"); - } } diff --git a/common/src/main/java/org/conscrypt/DuckTypedPSKKeyManager.java b/common/src/main/java/org/conscrypt/DuckTypedPSKKeyManager.java index c6e1ae99e..7c21bbf00 100644 --- a/common/src/main/java/org/conscrypt/DuckTypedPSKKeyManager.java +++ b/common/src/main/java/org/conscrypt/DuckTypedPSKKeyManager.java @@ -18,6 +18,7 @@ import java.lang.reflect.Method; import java.net.Socket; + import javax.crypto.SecretKey; import javax.net.ssl.SSLEngine; @@ -34,7 +35,6 @@ */ @Deprecated final class DuckTypedPSKKeyManager implements PSKKeyManager { - private final Object mDelegate; private DuckTypedPSKKeyManager(Object delegate) { @@ -62,7 +62,8 @@ static DuckTypedPSKKeyManager getInstance(Object obj) throws NoSuchMethodExcepti Class targetReturnType = targetMethod.getReturnType(); if (!targetReturnType.isAssignableFrom(sourceReturnType)) { throw new NoSuchMethodException(sourceMethod + " return value (" + sourceReturnType - + ") incompatible with target return value (" + targetReturnType + ")"); + + ") incompatible with target return value (" + + targetReturnType + ")"); } } diff --git a/common/src/main/java/org/conscrypt/ECParameters.java b/common/src/main/java/org/conscrypt/ECParameters.java index 1688404b8..31033f8c6 100644 --- a/common/src/main/java/org/conscrypt/ECParameters.java +++ b/common/src/main/java/org/conscrypt/ECParameters.java @@ -30,7 +30,6 @@ */ @Internal public class ECParameters extends AlgorithmParametersSpi { - private OpenSSLECGroupContext curve; public ECParameters() {} diff --git a/common/src/main/java/org/conscrypt/EmptyArray.java b/common/src/main/java/org/conscrypt/EmptyArray.java index 16cae35af..3bde84313 100644 --- a/common/src/main/java/org/conscrypt/EmptyArray.java +++ b/common/src/main/java/org/conscrypt/EmptyArray.java @@ -27,7 +27,7 @@ private EmptyArray() {} static final double[] DOUBLE = new double[0]; static final int[] INT = new int[0]; - static final Class[] CLASS = new Class[ 0 ]; + static final Class[] CLASS = new Class[0]; static final Object[] OBJECT = new Object[0]; static final String[] STRING = new String[0]; static final Throwable[] THROWABLE = new Throwable[0]; diff --git a/common/src/main/java/org/conscrypt/EvpMdRef.java b/common/src/main/java/org/conscrypt/EvpMdRef.java index 7dab3575e..349157a97 100644 --- a/common/src/main/java/org/conscrypt/EvpMdRef.java +++ b/common/src/main/java/org/conscrypt/EvpMdRef.java @@ -32,20 +32,15 @@ final class EvpMdRef { */ static String getJcaDigestAlgorithmStandardName(String algorithm) { String algorithmUpper = algorithm.toUpperCase(Locale.US); - if (SHA256.JCA_NAME.equals(algorithmUpper) - || SHA256.OID.equals(algorithmUpper)) { + if (SHA256.JCA_NAME.equals(algorithmUpper) || SHA256.OID.equals(algorithmUpper)) { return SHA256.JCA_NAME; - } else if (SHA512.JCA_NAME.equals(algorithmUpper) - || SHA512.OID.equals(algorithmUpper)) { + } else if (SHA512.JCA_NAME.equals(algorithmUpper) || SHA512.OID.equals(algorithmUpper)) { return SHA512.JCA_NAME; - } else if (SHA1.JCA_NAME.equals(algorithmUpper) - || SHA1.OID.equals(algorithmUpper)) { + } else if (SHA1.JCA_NAME.equals(algorithmUpper) || SHA1.OID.equals(algorithmUpper)) { return SHA1.JCA_NAME; - } else if (SHA384.JCA_NAME.equals(algorithmUpper) - || SHA384.OID.equals(algorithmUpper)) { + } else if (SHA384.JCA_NAME.equals(algorithmUpper) || SHA384.OID.equals(algorithmUpper)) { return SHA384.JCA_NAME; - } else if (SHA224.JCA_NAME.equals(algorithmUpper) - || SHA224.OID.equals(algorithmUpper)) { + } else if (SHA224.JCA_NAME.equals(algorithmUpper) || SHA224.OID.equals(algorithmUpper)) { return SHA224.JCA_NAME; } else { return null; diff --git a/common/src/main/java/org/conscrypt/ExperimentalApi.java b/common/src/main/java/org/conscrypt/ExperimentalApi.java index 5a0cd0a11..08d6eaf0f 100644 --- a/common/src/main/java/org/conscrypt/ExperimentalApi.java +++ b/common/src/main/java/org/conscrypt/ExperimentalApi.java @@ -35,13 +35,8 @@ */ @Internal @Retention(RetentionPolicy.SOURCE) -@Target({ - ElementType.ANNOTATION_TYPE, - ElementType.CONSTRUCTOR, - ElementType.FIELD, - ElementType.METHOD, - ElementType.PACKAGE, - ElementType.TYPE}) +@Target({ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.FIELD, + ElementType.METHOD, ElementType.PACKAGE, ElementType.TYPE}) @Documented public @interface ExperimentalApi { /** diff --git a/common/src/main/java/org/conscrypt/ExternalSession.java b/common/src/main/java/org/conscrypt/ExternalSession.java index 0d6057a34..1641a7f14 100644 --- a/common/src/main/java/org/conscrypt/ExternalSession.java +++ b/common/src/main/java/org/conscrypt/ExternalSession.java @@ -20,6 +20,7 @@ import java.security.cert.Certificate; import java.util.HashMap; import java.util.List; + import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSessionBindingEvent; @@ -45,173 +46,175 @@ * underlying sessions, so they need not be implemented. */ final class ExternalSession implements ConscryptSession { + // Use an initial capacity of 2 to keep it small in the average case. + private final HashMap values = new HashMap<>(2); + private final Provider provider; + + public ExternalSession(Provider provider) { + this.provider = provider; + } + + @Override + public String getRequestedServerName() { + return provider.provideSession().getRequestedServerName(); + } + + @Override + public List getStatusResponses() { + return provider.provideSession().getStatusResponses(); + } + + @Override + public byte[] getPeerSignedCertificateTimestamp() { + return provider.provideSession().getPeerSignedCertificateTimestamp(); + } + + @Override + public byte[] getId() { + return provider.provideSession().getId(); + } + + @Override + public SSLSessionContext getSessionContext() { + return provider.provideSession().getSessionContext(); + } + + @Override + public long getCreationTime() { + return provider.provideSession().getCreationTime(); + } + + @Override + public long getLastAccessedTime() { + return provider.provideSession().getLastAccessedTime(); + } + + @Override + public void invalidate() { + provider.provideSession().invalidate(); + } + + @Override + public boolean isValid() { + return provider.provideSession().isValid(); + } + + @Override + public java.security.cert.X509Certificate[] getPeerCertificates() + throws SSLPeerUnverifiedException { + return provider.provideSession().getPeerCertificates(); + } + + @Override + public Certificate[] getLocalCertificates() { + return provider.provideSession().getLocalCertificates(); + } + + @Override + @SuppressWarnings("deprecation") // Public API + public javax.security.cert.X509Certificate[] getPeerCertificateChain() + throws SSLPeerUnverifiedException { + return provider.provideSession().getPeerCertificateChain(); + } + + @Override + public Principal getPeerPrincipal() throws SSLPeerUnverifiedException { + return provider.provideSession().getPeerPrincipal(); + } - // Use an initial capacity of 2 to keep it small in the average case. - private final HashMap values = new HashMap<>(2); - private final Provider provider; - - public ExternalSession(Provider provider) { - this.provider = provider; - } - - @Override - public String getRequestedServerName() { - return provider.provideSession().getRequestedServerName(); - } - - @Override - public List getStatusResponses() { - return provider.provideSession().getStatusResponses(); - } - - @Override - public byte[] getPeerSignedCertificateTimestamp() { - return provider.provideSession().getPeerSignedCertificateTimestamp(); - } - - @Override - public byte[] getId() { - return provider.provideSession().getId(); - } - - @Override - public SSLSessionContext getSessionContext() { - return provider.provideSession().getSessionContext(); - } - - @Override - public long getCreationTime() { - return provider.provideSession().getCreationTime(); - } - - @Override - public long getLastAccessedTime() { - return provider.provideSession().getLastAccessedTime(); - } - - @Override - public void invalidate() { - provider.provideSession().invalidate(); - } - - @Override - public boolean isValid() { - return provider.provideSession().isValid(); - } - - @Override - public java.security.cert.X509Certificate[] getPeerCertificates() - throws SSLPeerUnverifiedException { - return provider.provideSession().getPeerCertificates(); - } - - @Override - public Certificate[] getLocalCertificates() { - return provider.provideSession().getLocalCertificates(); - } - - @Override - @SuppressWarnings("deprecation") // Public API - public javax.security.cert.X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException { - return provider.provideSession().getPeerCertificateChain(); - } - - @Override - public Principal getPeerPrincipal() throws SSLPeerUnverifiedException { - return provider.provideSession().getPeerPrincipal(); - } - - @Override - public Principal getLocalPrincipal() { - return provider.provideSession().getLocalPrincipal(); - } - - @Override - public String getCipherSuite() { - return provider.provideSession().getCipherSuite(); - } - - @Override - public String getProtocol() { - return provider.provideSession().getProtocol(); - } - - @Override - public String getPeerHost() { - return provider.provideSession().getPeerHost(); - } - - @Override - public int getPeerPort() { - return provider.provideSession().getPeerPort(); - } - - @Override - public int getPacketBufferSize() { - return provider.provideSession().getPacketBufferSize(); - } - - @Override - public int getApplicationBufferSize() { - return provider.provideSession().getApplicationBufferSize(); - } - - @Override - public String getApplicationProtocol() { - return provider.provideSession().getApplicationProtocol(); - } - - @Override - public Object getValue(String name) { - if (name == null) { - throw new IllegalArgumentException("name == null"); - } - return values.get(name); - } - - @Override - public String[] getValueNames() { - return values.keySet().toArray(new String[0]); - } - - @Override - public void putValue(String name, Object value) { - putValue(this, name, value); - } - - void putValue(SSLSession session, String name, Object value) { - if (name == null || value == null) { - throw new IllegalArgumentException("name == null || value == null"); - } - Object old = values.put(name, value); - if (value instanceof SSLSessionBindingListener) { - ((SSLSessionBindingListener) value).valueBound(new SSLSessionBindingEvent(session, name)); - } - if (old instanceof SSLSessionBindingListener) { - ((SSLSessionBindingListener) old).valueUnbound(new SSLSessionBindingEvent(session, name)); - } - } - - @Override - public void removeValue(String name) { - removeValue(this, name); - } - - void removeValue(SSLSession session, String name) { - if (name == null) { - throw new IllegalArgumentException("name == null"); - } - Object old = values.remove(name); - if (old instanceof SSLSessionBindingListener) { - SSLSessionBindingListener listener = (SSLSessionBindingListener) old; - listener.valueUnbound(new SSLSessionBindingEvent(session, name)); - } - } - - /** - * The provider of the current delegate session. - */ - interface Provider { - ConscryptSession provideSession(); - } + @Override + public Principal getLocalPrincipal() { + return provider.provideSession().getLocalPrincipal(); + } + + @Override + public String getCipherSuite() { + return provider.provideSession().getCipherSuite(); + } + + @Override + public String getProtocol() { + return provider.provideSession().getProtocol(); + } + + @Override + public String getPeerHost() { + return provider.provideSession().getPeerHost(); + } + + @Override + public int getPeerPort() { + return provider.provideSession().getPeerPort(); + } + + @Override + public int getPacketBufferSize() { + return provider.provideSession().getPacketBufferSize(); + } + + @Override + public int getApplicationBufferSize() { + return provider.provideSession().getApplicationBufferSize(); + } + + @Override + public String getApplicationProtocol() { + return provider.provideSession().getApplicationProtocol(); + } + + @Override + public Object getValue(String name) { + if (name == null) { + throw new IllegalArgumentException("name == null"); + } + return values.get(name); + } + + @Override + public String[] getValueNames() { + return values.keySet().toArray(new String[0]); + } + + @Override + public void putValue(String name, Object value) { + putValue(this, name, value); + } + + void putValue(SSLSession session, String name, Object value) { + if (name == null || value == null) { + throw new IllegalArgumentException("name == null || value == null"); + } + Object old = values.put(name, value); + if (value instanceof SSLSessionBindingListener) { + ((SSLSessionBindingListener) value) + .valueBound(new SSLSessionBindingEvent(session, name)); + } + if (old instanceof SSLSessionBindingListener) { + ((SSLSessionBindingListener) old) + .valueUnbound(new SSLSessionBindingEvent(session, name)); + } + } + + @Override + public void removeValue(String name) { + removeValue(this, name); + } + + void removeValue(SSLSession session, String name) { + if (name == null) { + throw new IllegalArgumentException("name == null"); + } + Object old = values.remove(name); + if (old instanceof SSLSessionBindingListener) { + SSLSessionBindingListener listener = (SSLSessionBindingListener) old; + listener.valueUnbound(new SSLSessionBindingEvent(session, name)); + } + } + + /** + * The provider of the current delegate session. + */ + interface Provider { + ConscryptSession provideSession(); + } } diff --git a/common/src/main/java/org/conscrypt/FileClientSessionCache.java b/common/src/main/java/org/conscrypt/FileClientSessionCache.java index 651b552aa..a6d484462 100644 --- a/common/src/main/java/org/conscrypt/FileClientSessionCache.java +++ b/common/src/main/java/org/conscrypt/FileClientSessionCache.java @@ -16,6 +16,8 @@ package org.conscrypt; +import org.conscrypt.io.IoUtils; + import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; @@ -31,8 +33,8 @@ import java.util.TreeSet; import java.util.logging.Level; import java.util.logging.Logger; + import javax.net.ssl.SSLSession; -import org.conscrypt.io.IoUtils; /** * File-based cache implementation. Only one process should access the @@ -179,9 +181,9 @@ public synchronized byte[] getSessionData(String host, int port) { static void logReadError(String host, File file, Throwable t) { logger.log(Level.WARNING, - "FileClientSessionCache: Error reading session data for " + host + " from " - + file + ".", - t); + "FileClientSessionCache: Error reading session data for " + host + " from " + + file + ".", + t); } @Override @@ -303,9 +305,9 @@ private void delete(File file) { static void logWriteError(String host, File file, Throwable t) { logger.log(Level.WARNING, - "FileClientSessionCache: Error writing session data for " + host + " to " + file - + ".", - t); + "FileClientSessionCache: Error writing session data for " + host + " to " + + file + ".", + t); } } diff --git a/common/src/main/java/org/conscrypt/GCMParameters.java b/common/src/main/java/org/conscrypt/GCMParameters.java index 190db9c8e..7c65d594d 100644 --- a/common/src/main/java/org/conscrypt/GCMParameters.java +++ b/common/src/main/java/org/conscrypt/GCMParameters.java @@ -31,7 +31,6 @@ */ @Internal public final class GCMParameters extends AlgorithmParametersSpi { - // The default value (in bits) for TLEN in the GCM ASN.1 module private static final int DEFAULT_TLEN = 96; @@ -41,7 +40,7 @@ public final class GCMParameters extends AlgorithmParametersSpi { /** Actually the nonce value for the GCM operation. */ private byte[] iv; - public GCMParameters() { } + public GCMParameters() {} GCMParameters(int tLen, byte[] iv) { this.tLen = tLen; @@ -86,7 +85,7 @@ protected void engineInit(byte[] bytes) throws IOException { newTlen = 8 * (int) NativeCrypto.asn1_read_uint64(seqRef); } if (!NativeCrypto.asn1_read_is_empty(seqRef) - || !NativeCrypto.asn1_read_is_empty(readRef)) { + || !NativeCrypto.asn1_read_is_empty(readRef)) { throw new IOException("Error reading ASN.1 encoding"); } this.iv = newIv; diff --git a/common/src/main/java/org/conscrypt/HandshakeListener.java b/common/src/main/java/org/conscrypt/HandshakeListener.java index 82bfa5b28..77983e735 100644 --- a/common/src/main/java/org/conscrypt/HandshakeListener.java +++ b/common/src/main/java/org/conscrypt/HandshakeListener.java @@ -19,11 +19,11 @@ import javax.net.ssl.SSLException; /** - * Similar in concept to {@link javax.net.ssl.HandshakeCompletedListener}, but used for listening directly - * to the engine. Allows the caller to be notified immediately upon completion of the TLS handshake. + * Similar in concept to {@link javax.net.ssl.HandshakeCompletedListener}, but used for listening + * directly to the engine. Allows the caller to be notified immediately upon completion of the TLS + * handshake. */ public abstract class HandshakeListener { - /** * Called by the engine when the TLS handshake has completed. */ diff --git a/common/src/main/java/org/conscrypt/Hkdf.java b/common/src/main/java/org/conscrypt/Hkdf.java index b84ba071b..cc125067b 100644 --- a/common/src/main/java/org/conscrypt/Hkdf.java +++ b/common/src/main/java/org/conscrypt/Hkdf.java @@ -43,7 +43,7 @@ public final class Hkdf { * @param hmacName the name of the HMAC algorithm to use * @throws NoSuchAlgorithmException if hmacName is not a valid HMAC name */ - public Hkdf(String hmacName) throws NoSuchAlgorithmException { + public Hkdf(String hmacName) throws NoSuchAlgorithmException { Objects.requireNonNull(hmacName); this.hmacName = hmacName; @@ -67,7 +67,7 @@ public int getMacLength() { */ public byte[] extract(byte[] salt, byte[] ikm) - throws InvalidKeyException, NoSuchAlgorithmException { + throws InvalidKeyException, NoSuchAlgorithmException { Objects.requireNonNull(salt); Objects.requireNonNull(ikm); Preconditions.checkArgument(ikm.length > 0, "Empty keying material"); @@ -90,7 +90,7 @@ public byte[] extract(byte[] salt, byte[] ikm) * @throws NoSuchAlgorithmException if the Mac algorithm is no longer available */ public byte[] expand(byte[] prk, byte[] info, int length) - throws InvalidKeyException, NoSuchAlgorithmException { + throws InvalidKeyException, NoSuchAlgorithmException { Objects.requireNonNull(prk); Objects.requireNonNull(info); Preconditions.checkArgument(length >= 0, "Negative length"); @@ -101,7 +101,7 @@ public byte[] expand(byte[] prk, byte[] info, int length) byte[] t = new byte[0]; byte[] output = new byte[length]; int outputOffset = 0; - byte[] counter = new byte[] { 0x00 }; + byte[] counter = new byte[] {0x00}; while (outputOffset < length) { counter[0]++; mac.update(t); diff --git a/common/src/main/java/org/conscrypt/HpkeContext.java b/common/src/main/java/org/conscrypt/HpkeContext.java index 355997f04..d31269656 100644 --- a/common/src/main/java/org/conscrypt/HpkeContext.java +++ b/common/src/main/java/org/conscrypt/HpkeContext.java @@ -37,82 +37,82 @@ * @see RFC 9180 (HPKE) */ public abstract class HpkeContext { - protected final HpkeSpi spi; + protected final HpkeSpi spi; - protected HpkeContext(HpkeSpi spi) { - this.spi = spi; - } - - /** - * Exports secret key material from this HpkeContext as described in RFC 9180. - * - * @param length expected output length - * @param context optional context string, may be null or empty - * @return exported value - * @throws IllegalArgumentException if the length is not valid for the KDF in use - * @throws IllegalStateException if this HpkeContext has not been initialised - * - */ - public byte[] export(int length, byte[] context) { - return spi.engineExport(length, context); - } - - /** - * Returns the {@link HpkeSpi} being used by this HpkeContext. - * - * @return the SPI - */ - public HpkeSpi getSpi() { - return spi; - } - - protected static HpkeSpi findSpi(String algorithm) throws NoSuchAlgorithmException { - if (algorithm == null) { - // Same behaviour as Cipher.getInstance - throw new NoSuchAlgorithmException("null algorithm"); + protected HpkeContext(HpkeSpi spi) { + this.spi = spi; } - return findSpi(algorithm, findFirstProvider(algorithm)); - } - private static Provider findFirstProvider(String algorithm) throws NoSuchAlgorithmException { - for (Provider p : Security.getProviders()) { - Provider.Service service = p.getService("ConscryptHpke", algorithm); - if (service != null) { - return service.getProvider(); - } + /** + * Exports secret key material from this HpkeContext as described in RFC 9180. + * + * @param length expected output length + * @param context optional context string, may be null or empty + * @return exported value + * @throws IllegalArgumentException if the length is not valid for the KDF in use + * @throws IllegalStateException if this HpkeContext has not been initialised + * + */ + public byte[] export(int length, byte[] context) { + return spi.engineExport(length, context); } - throw new NoSuchAlgorithmException("No Provider found for: " + algorithm); - } - protected static HpkeSpi findSpi(String algorithm, String providerName) throws - NoSuchAlgorithmException, IllegalArgumentException, NoSuchProviderException { - if (providerName == null || providerName.isEmpty()) { - // Same behaviour as Cipher.getInstance - throw new IllegalArgumentException("Invalid provider name"); + /** + * Returns the {@link HpkeSpi} being used by this HpkeContext. + * + * @return the SPI + */ + public HpkeSpi getSpi() { + return spi; } - Provider provider = Security.getProvider(providerName); - if (provider == null) { - throw new NoSuchProviderException("Unknown Provider: " + providerName); + + protected static HpkeSpi findSpi(String algorithm) throws NoSuchAlgorithmException { + if (algorithm == null) { + // Same behaviour as Cipher.getInstance + throw new NoSuchAlgorithmException("null algorithm"); + } + return findSpi(algorithm, findFirstProvider(algorithm)); } - return findSpi(algorithm, provider); - } - protected static HpkeSpi findSpi(String algorithm, Provider provider) throws - NoSuchAlgorithmException, IllegalArgumentException { - if (provider == null) { - throw new IllegalArgumentException("null Provider"); + private static Provider findFirstProvider(String algorithm) throws NoSuchAlgorithmException { + for (Provider p : Security.getProviders()) { + Provider.Service service = p.getService("ConscryptHpke", algorithm); + if (service != null) { + return service.getProvider(); + } + } + throw new NoSuchAlgorithmException("No Provider found for: " + algorithm); } - Provider.Service service = provider.getService("ConscryptHpke", algorithm); - if (service == null) { - throw new NoSuchAlgorithmException("Unknown algorithm"); + + protected static HpkeSpi findSpi(String algorithm, String providerName) + throws NoSuchAlgorithmException, IllegalArgumentException, NoSuchProviderException { + if (providerName == null || providerName.isEmpty()) { + // Same behaviour as Cipher.getInstance + throw new IllegalArgumentException("Invalid provider name"); + } + Provider provider = Security.getProvider(providerName); + if (provider == null) { + throw new NoSuchProviderException("Unknown Provider: " + providerName); + } + return findSpi(algorithm, provider); } - Object instance = service.newInstance(null); - HpkeSpi spi = (instance instanceof HpkeSpi) ? (HpkeSpi) instance - : DuckTypedHpkeSpi.newInstance(instance); - if (spi != null) { - return spi; + + protected static HpkeSpi findSpi(String algorithm, Provider provider) + throws NoSuchAlgorithmException, IllegalArgumentException { + if (provider == null) { + throw new IllegalArgumentException("null Provider"); + } + Provider.Service service = provider.getService("ConscryptHpke", algorithm); + if (service == null) { + throw new NoSuchAlgorithmException("Unknown algorithm"); + } + Object instance = service.newInstance(null); + HpkeSpi spi = (instance instanceof HpkeSpi) ? (HpkeSpi) instance + : DuckTypedHpkeSpi.newInstance(instance); + if (spi != null) { + return spi; + } + throw new IllegalStateException( + String.format("Provider %s is providing incorrect instances", provider.getName())); } - throw new IllegalStateException( - String.format("Provider %s is providing incorrect instances", provider.getName())); - } } diff --git a/common/src/main/java/org/conscrypt/HpkeContextRecipient.java b/common/src/main/java/org/conscrypt/HpkeContextRecipient.java index 29cdde956..809c8485a 100644 --- a/common/src/main/java/org/conscrypt/HpkeContextRecipient.java +++ b/common/src/main/java/org/conscrypt/HpkeContextRecipient.java @@ -70,7 +70,7 @@ public static HpkeContextRecipient getInstance(String suite) throws NoSuchAlgori * @throws NoSuchProviderException if providerName is null or no such Provider exists */ public static HpkeContextRecipient getInstance(String suite, String providerName) - throws NoSuchAlgorithmException, NoSuchProviderException { + throws NoSuchAlgorithmException, NoSuchProviderException { return new HpkeContextRecipient(findSpi(suite, providerName)); } @@ -84,7 +84,7 @@ public static HpkeContextRecipient getInstance(String suite, String providerName * @throws NoSuchProviderException if providerName is null or no such Provider exists */ public static HpkeContextRecipient getInstance(String suite, Provider provider) - throws NoSuchAlgorithmException, NoSuchProviderException { + throws NoSuchAlgorithmException, NoSuchProviderException { return new HpkeContextRecipient(findSpi(suite, provider)); } @@ -100,8 +100,8 @@ public static HpkeContextRecipient getInstance(String suite, Provider provider) */ public void init(byte[] encapsulated, PrivateKey recipientKey, byte[] info) throws InvalidKeyException { - spi.engineInitRecipient(encapsulated, recipientKey, info, null, - HpkeSpi.DEFAULT_PSK, HpkeSpi.DEFAULT_PSK_ID); + spi.engineInitRecipient(encapsulated, recipientKey, info, null, HpkeSpi.DEFAULT_PSK, + HpkeSpi.DEFAULT_PSK_ID); } /** @@ -118,13 +118,13 @@ public void init(byte[] encapsulated, PrivateKey recipientKey, byte[] info) * @throws IllegalStateException if this HpkeContextRecipient has already been initialised */ public void init(byte[] encapsulated, PrivateKey recipientKey, byte[] info, PublicKey senderKey) - throws InvalidKeyException { + throws InvalidKeyException { if (senderKey == null) { throw new InvalidKeyException("null sender key"); } // Remaining argument checks are performed by the SPI - spi.engineInitRecipient(encapsulated, recipientKey, info, senderKey, - HpkeSpi.DEFAULT_PSK, HpkeSpi.DEFAULT_PSK_ID); + spi.engineInitRecipient(encapsulated, recipientKey, info, senderKey, HpkeSpi.DEFAULT_PSK, + HpkeSpi.DEFAULT_PSK_ID); } /** @@ -141,8 +141,8 @@ public void init(byte[] encapsulated, PrivateKey recipientKey, byte[] info, Publ * @throws UnsupportedOperationException if mode is not a supported HPKE mode * @throws IllegalStateException if this HpkeContextRecipient has already been initialised */ - public void init(byte[] encapsulated, PrivateKey recipientKey, byte[] info, - byte[] psk, byte[] psk_id) throws InvalidKeyException { + public void init(byte[] encapsulated, PrivateKey recipientKey, byte[] info, byte[] psk, + byte[] psk_id) throws InvalidKeyException { spi.engineInitRecipient(encapsulated, recipientKey, info, null, psk, psk_id); } @@ -163,7 +163,7 @@ public void init(byte[] encapsulated, PrivateKey recipientKey, byte[] info, * @throws IllegalStateException if this HpkeContextRecipient has already been initialised */ public void init(byte[] encapsulated, PrivateKey recipientKey, byte[] info, PublicKey senderKey, - byte[] psk, byte[] psk_id) throws InvalidKeyException { + byte[] psk, byte[] psk_id) throws InvalidKeyException { if (senderKey == null) { throw new InvalidKeyException("null sender key"); } diff --git a/common/src/main/java/org/conscrypt/HpkeContextSender.java b/common/src/main/java/org/conscrypt/HpkeContextSender.java index abde31d03..6eee65c00 100644 --- a/common/src/main/java/org/conscrypt/HpkeContextSender.java +++ b/common/src/main/java/org/conscrypt/HpkeContextSender.java @@ -79,7 +79,7 @@ public static HpkeContextSender getInstance(String suite) throws NoSuchAlgorithm * @throws NoSuchProviderException if providerName is null or no such Provider exists */ public static HpkeContextSender getInstance(String suite, String providerName) - throws NoSuchAlgorithmException, NoSuchProviderException { + throws NoSuchAlgorithmException, NoSuchProviderException { return new HpkeContextSender(findSpi(suite, providerName)); } @@ -93,7 +93,7 @@ public static HpkeContextSender getInstance(String suite, String providerName) * @throws NoSuchProviderException if provider is null */ public static HpkeContextSender getInstance(String suite, Provider provider) - throws NoSuchAlgorithmException, NoSuchProviderException { + throws NoSuchAlgorithmException, NoSuchProviderException { return new HpkeContextSender(findSpi(suite, provider)); } @@ -107,8 +107,7 @@ public static HpkeContextSender getInstance(String suite, Provider provider) * @throws IllegalStateException if this HpkeContextSender has already been initialised */ public void init(PublicKey recipientKey, byte[] info) throws InvalidKeyException { - spi.engineInitSender( - recipientKey, info, null, HpkeSpi.DEFAULT_PSK, HpkeSpi.DEFAULT_PSK_ID); + spi.engineInitSender(recipientKey, info, null, HpkeSpi.DEFAULT_PSK, HpkeSpi.DEFAULT_PSK_ID); } /** @@ -129,8 +128,8 @@ public void init(PublicKey recipientKey, byte[] info, PrivateKey senderKey) throw new InvalidKeyException("Sender private key is null"); } // Remaining argument checks are performed by the SPI - spi.engineInitSender( - recipientKey, info, senderKey, HpkeSpi.DEFAULT_PSK, HpkeSpi.DEFAULT_PSK_ID); + spi.engineInitSender(recipientKey, info, senderKey, HpkeSpi.DEFAULT_PSK, + HpkeSpi.DEFAULT_PSK_ID); } /** @@ -166,8 +165,8 @@ public void init(PublicKey recipientKey, byte[] info, byte[] psk, byte[] psk_id) * @throws UnsupportedOperationException if mode is not a supported HPKE mode * @throws IllegalStateException if this HpkeContextSender has already been initialised */ - public void init(PublicKey recipientKey, byte[] info, PrivateKey senderKey, - byte[] psk, byte[] psk_id) throws InvalidKeyException { + public void init(PublicKey recipientKey, byte[] info, PrivateKey senderKey, byte[] psk, + byte[] psk_id) throws InvalidKeyException { if (senderKey == null) { throw new InvalidKeyException("Sender private key is null"); } @@ -188,11 +187,11 @@ public void init(PublicKey recipientKey, byte[] info, PrivateKey senderKey, */ @Internal public void initForTesting(PublicKey recipientKey, byte[] info, byte[] sKe) - throws InvalidKeyException { + throws InvalidKeyException { if (sKe == null) { throw new IllegalArgumentException("null seed"); } - spi.engineInitSenderForTesting( - recipientKey, info, null, HpkeSpi.DEFAULT_PSK, HpkeSpi.DEFAULT_PSK, sKe); + spi.engineInitSenderForTesting(recipientKey, info, null, HpkeSpi.DEFAULT_PSK, + HpkeSpi.DEFAULT_PSK, sKe); } } diff --git a/common/src/main/java/org/conscrypt/HpkeImpl.java b/common/src/main/java/org/conscrypt/HpkeImpl.java index ac50d1804..5c7e19fae 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,8 +216,8 @@ 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)); } } diff --git a/common/src/main/java/org/conscrypt/HpkeSpi.java b/common/src/main/java/org/conscrypt/HpkeSpi.java index f257ec63c..38d17f5a3 100644 --- a/common/src/main/java/org/conscrypt/HpkeSpi.java +++ b/common/src/main/java/org/conscrypt/HpkeSpi.java @@ -10,118 +10,103 @@ * implementation which implements this interface, by duck-typing if necessary. */ public interface HpkeSpi { - byte[] DEFAULT_PSK = new byte[0]; - byte[] DEFAULT_PSK_ID = DEFAULT_PSK; + byte[] DEFAULT_PSK = new byte[0]; + byte[] DEFAULT_PSK_ID = DEFAULT_PSK; - /** - * Initialises an HPKE sender SPI. - * - * @param recipientKey public key of the recipient - * @param info application-supplied information, may be null or empty - * @param senderKey private key of the sender, for symmetric auth modes only, else null - * @param psk pre-shared key, for PSK auth modes only, else null - * @param psk_id pre-shared key ID, for PSK auth modes only, else null - * @throws InvalidKeyException if recipientKey is null or an unsupported key format - * @throws UnsupportedOperationException if mode is not a supported HPKE mode - * @throws IllegalStateException if this SPI has already been initialised - */ - void engineInitSender( - PublicKey recipientKey, - byte[] info, - PrivateKey senderKey, - byte[] psk, - byte[] psk_id) - throws InvalidKeyException; + /** + * Initialises an HPKE sender SPI. + * + * @param recipientKey public key of the recipient + * @param info application-supplied information, may be null or empty + * @param senderKey private key of the sender, for symmetric auth modes only, else null + * @param psk pre-shared key, for PSK auth modes only, else null + * @param psk_id pre-shared key ID, for PSK auth modes only, else null + * @throws InvalidKeyException if recipientKey is null or an unsupported key format + * @throws UnsupportedOperationException if mode is not a supported HPKE mode + * @throws IllegalStateException if this SPI has already been initialised + */ + void engineInitSender(PublicKey recipientKey, byte[] info, PrivateKey senderKey, byte[] psk, + byte[] psk_id) throws InvalidKeyException; - /** - * Initialises an HPKE sender SPI. - * - * @param recipientKey public key of the recipient - * @param info application-supplied information, may be null or empty - * @param senderKey private key of the sender, for symmetric auth modes only, else null - * @param psk pre-shared key, for PSK auth modes only, else null - * @param psk_id pre-shared key ID, for PSK auth modes only, else null - * @param sKe optional random seed, should be null for all uses except for validation against - * known test vectors - * @throws InvalidKeyException if recipientKey is null or an unsupported key format or senderKey - * is an unsupported key format - * @throws UnsupportedOperationException if mode is not a supported HPKE mode - * @throws IllegalStateException if this SPI has already been initialised - */ - void engineInitSenderForTesting( - PublicKey recipientKey, - byte[] info, - PrivateKey senderKey, - byte[] psk, - byte[] psk_id, - byte[] sKe) - throws InvalidKeyException; + /** + * Initialises an HPKE sender SPI. + * + * @param recipientKey public key of the recipient + * @param info application-supplied information, may be null or empty + * @param senderKey private key of the sender, for symmetric auth modes only, else null + * @param psk pre-shared key, for PSK auth modes only, else null + * @param psk_id pre-shared key ID, for PSK auth modes only, else null + * @param sKe optional random seed, should be null for all uses except for validation against + * known test vectors + * @throws InvalidKeyException if recipientKey is null or an unsupported key format or senderKey + * is an unsupported key format + * @throws UnsupportedOperationException if mode is not a supported HPKE mode + * @throws IllegalStateException if this SPI has already been initialised + */ + void engineInitSenderForTesting(PublicKey recipientKey, byte[] info, PrivateKey senderKey, + byte[] psk, byte[] psk_id, byte[] sKe) + throws InvalidKeyException; - /** - * Initialises an HPKE recipient SPI. - * - * @param encapsulated encapsulated ephemeral key from a sender - * @param recipientKey private key of the recipient - * @param info application-supplied information, may be null or empty - * @param senderKey public key of sender, for asymmetric auth modes only, else null - * @param psk pre-shared key, for PSK auth modes only, else null - * @param psk_id pre-shared key ID, for PSK auth modes only, else null - * @throws InvalidKeyException if recipientKey is null or an unsupported key format or senderKey - * is an unsupported key format - * @throws UnsupportedOperationException if mode is not a supported HPKE mode - * @throws IllegalStateException if this SPI has already been initialised - */ - void engineInitRecipient( - byte[] encapsulated, - PrivateKey recipientKey, - byte[] info, - PublicKey senderKey, - byte[] psk, - byte[] psk_id) - throws InvalidKeyException; + /** + * Initialises an HPKE recipient SPI. + * + * @param encapsulated encapsulated ephemeral key from a sender + * @param recipientKey private key of the recipient + * @param info application-supplied information, may be null or empty + * @param senderKey public key of sender, for asymmetric auth modes only, else null + * @param psk pre-shared key, for PSK auth modes only, else null + * @param psk_id pre-shared key ID, for PSK auth modes only, else null + * @throws InvalidKeyException if recipientKey is null or an unsupported key format or senderKey + * is an unsupported key format + * @throws UnsupportedOperationException if mode is not a supported HPKE mode + * @throws IllegalStateException if this SPI has already been initialised + */ + void engineInitRecipient(byte[] encapsulated, PrivateKey recipientKey, byte[] info, + PublicKey senderKey, byte[] psk, byte[] psk_id) + throws InvalidKeyException; - /** - * Seals a message, using the internal key schedule maintained by an HPKE sender. - * - * @param plaintext the plaintext - * @param aad optional associated data, may be null or empty - * @return the ciphertext - * @throws NullPointerException if the plaintext is null - * @throws IllegalStateException if this SPI has not been initialised or if it was initialised - * as a recipient - */ - byte[] engineSeal(byte[] plaintext, byte[] aad); + /** + * Seals a message, using the internal key schedule maintained by an HPKE sender. + * + * @param plaintext the plaintext + * @param aad optional associated data, may be null or empty + * @return the ciphertext + * @throws NullPointerException if the plaintext is null + * @throws IllegalStateException if this SPI has not been initialised or if it was initialised + * as a recipient + */ + byte[] engineSeal(byte[] plaintext, byte[] aad); - /** - * Opens a message, using the internal key schedule maintained by an HPKE recipient. - * - * @param ciphertext the ciphertext - * @param aad optional associated data, may be null or empty - * @return the plaintext - * @throws IllegalStateException if this SPI has not been initialised or if it was initialised - * as a sender - * @throws GeneralSecurityException on decryption failures - */ - byte[] engineOpen(byte[] ciphertext, byte[] aad) throws GeneralSecurityException; + /** + * Opens a message, using the internal key schedule maintained by an HPKE recipient. + * + * @param ciphertext the ciphertext + * @param aad optional associated data, may be null or empty + * @return the plaintext + * @throws IllegalStateException if this SPI has not been initialised or if it was initialised + * as a sender + * @throws GeneralSecurityException on decryption failures + */ + byte[] engineOpen(byte[] ciphertext, byte[] aad) throws GeneralSecurityException; - /** - * Exports secret key material from this SPI as described in RFC 9180. - * - * @param length expected output length - * @param context optional context string, may be null or empty - * @return exported value - * @throws IllegalArgumentException if the length is not valid for the KDF in use - * @throws IllegalStateException if this SPI has not been initialised - * - */ - byte[] engineExport(int length, byte[] context); + /** + * Exports secret key material from this SPI as described in RFC 9180. + * + * @param length expected output length + * @param context optional context string, may be null or empty + * @return exported value + * @throws IllegalArgumentException if the length is not valid for the KDF in use + * @throws IllegalStateException if this SPI has not been initialised + * + */ + byte[] engineExport(int length, byte[] context); - /** - * Returns the encapsulated key material for an HPKE sender. - * - * @return the key material - * @throws IllegalStateException if this SPI has not been initialised or if it was initialised - * as a recipient - */ - byte[] getEncapsulated(); + /** + * Returns the encapsulated key material for an HPKE sender. + * + * @return the key material + * @throws IllegalStateException if this SPI has not been initialised or if it was initialised + * as a recipient + */ + byte[] getEncapsulated(); } diff --git a/common/src/main/java/org/conscrypt/HpkeSuite.java b/common/src/main/java/org/conscrypt/HpkeSuite.java index 488110684..95bb6742b 100644 --- a/common/src/main/java/org/conscrypt/HpkeSuite.java +++ b/common/src/main/java/org/conscrypt/HpkeSuite.java @@ -71,8 +71,7 @@ public HpkeSuite(int kem, int kdf, int aead) { } public String name() { - return String.format("%s/%s/%s", - mKem.name(), mKdf.name(), mAead.name()); + return String.format("%s/%s/%s", mKem.name(), mKdf.name(), mAead.name()); } /** @@ -146,7 +145,7 @@ public enum KEM { DHKEM_X25519_HKDF_SHA256( /* id= */ 0x20, /* nSecret= */ 32, /* nEnc= */ 32, /* nPk= */ 32, /* nSk= */ 32), XWING(/* id= */ 0x647a, /* nSecret= */ 32, /* nEnc= */ 1120, /* nPk= */ 1216, - /* nSk= */ 32); + /* nSk= */ 32); private final int id; private final int nSecret; @@ -338,7 +337,8 @@ public int getId() { * Returns the length in bytes of a key for this algorithm. * * @return AEAD Nk - * @see + * @see * AEAD ids */ @Deprecated // Use getKeyLength() @@ -353,7 +353,8 @@ public int getKeyLength() { * Returns the length in bytes of a nonce for this algorithm. * * @return AEAD Nn - * @see + * @see * AEAD ids */ @Deprecated // Use getNonceLength() @@ -368,7 +369,8 @@ public int getNonceLength() { * Returns the length in bytes of the AEAD authentication tag for this algorithm. * * @return AEAD Nt - * @see + * @see * AEAD ids */ @Deprecated // Use getTagLength() diff --git a/common/src/main/java/org/conscrypt/Internal.java b/common/src/main/java/org/conscrypt/Internal.java index 0bc3998ef..e01894cde 100644 --- a/common/src/main/java/org/conscrypt/Internal.java +++ b/common/src/main/java/org/conscrypt/Internal.java @@ -30,6 +30,6 @@ @Internal @Retention(RetentionPolicy.SOURCE) @Target({ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.FIELD, - ElementType.METHOD, ElementType.PACKAGE, ElementType.TYPE}) + ElementType.METHOD, ElementType.PACKAGE, ElementType.TYPE}) @Documented public @interface Internal {} diff --git a/common/src/main/java/org/conscrypt/IvParameters.java b/common/src/main/java/org/conscrypt/IvParameters.java index 9a73cc420..36dff4c54 100644 --- a/common/src/main/java/org/conscrypt/IvParameters.java +++ b/common/src/main/java/org/conscrypt/IvParameters.java @@ -20,6 +20,7 @@ import java.security.AlgorithmParametersSpi; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.InvalidParameterSpecException; + import javax.crypto.spec.IvParameterSpec; /** @@ -70,8 +71,8 @@ protected void engineInit(byte[] bytes, String format) throws IOException { protected T engineGetParameterSpec(Class aClass) throws InvalidParameterSpecException { if (aClass != IvParameterSpec.class) { - throw new InvalidParameterSpecException( - "Incompatible AlgorithmParametersSpec class: " + aClass); + throw new InvalidParameterSpecException("Incompatible AlgorithmParametersSpec class: " + + aClass); } return (T) new IvParameterSpec(iv); } diff --git a/common/src/main/java/org/conscrypt/Java7ExtendedSSLSession.java b/common/src/main/java/org/conscrypt/Java7ExtendedSSLSession.java index aae280066..431108790 100644 --- a/common/src/main/java/org/conscrypt/Java7ExtendedSSLSession.java +++ b/common/src/main/java/org/conscrypt/Java7ExtendedSSLSession.java @@ -18,6 +18,7 @@ import java.security.Principal; import java.security.cert.Certificate; import java.util.List; + import javax.net.ssl.ExtendedSSLSession; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSessionContext; @@ -29,8 +30,9 @@ class Java7ExtendedSSLSession extends ExtendedSSLSession implements ConscryptSession { // TODO: use BoringSSL API to actually fetch the real data private static final String[] LOCAL_SUPPORTED_SIGNATURE_ALGORITHMS = new String[] { - "SHA512withRSA", "SHA512withECDSA", "SHA384withRSA", "SHA384withECDSA", "SHA256withRSA", - "SHA256withECDSA", "SHA224withRSA", "SHA224withECDSA", "SHA1withRSA", "SHA1withECDSA", + "SHA512withRSA", "SHA512withECDSA", "SHA384withRSA", "SHA384withECDSA", + "SHA256withRSA", "SHA256withECDSA", "SHA224withRSA", "SHA224withECDSA", + "SHA1withRSA", "SHA1withECDSA", }; // TODO: use BoringSSL API to actually fetch the real data private static final String[] PEER_SUPPORTED_SIGNATURE_ALGORITHMS = @@ -123,7 +125,7 @@ public final String[] getValueNames() { @Override public java.security.cert.X509Certificate[] getPeerCertificates() - throws SSLPeerUnverifiedException { + throws SSLPeerUnverifiedException { return delegate.getPeerCertificates(); } @@ -134,7 +136,8 @@ public final Certificate[] getLocalCertificates() { @Override @SuppressWarnings("deprecation") // Public API - public final javax.security.cert.X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException { + public final javax.security.cert.X509Certificate[] getPeerCertificateChain() + throws SSLPeerUnverifiedException { return delegate.getPeerCertificateChain(); } diff --git a/common/src/main/java/org/conscrypt/Java8EngineSocket.java b/common/src/main/java/org/conscrypt/Java8EngineSocket.java index d66b9427b..14a65c441 100644 --- a/common/src/main/java/org/conscrypt/Java8EngineSocket.java +++ b/common/src/main/java/org/conscrypt/Java8EngineSocket.java @@ -21,6 +21,7 @@ import java.net.Socket; import java.util.List; import java.util.function.BiFunction; + import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLSocket; @@ -47,17 +48,17 @@ final class Java8EngineSocket extends ConscryptEngineSocket { } Java8EngineSocket(String hostname, int port, InetAddress clientAddress, int clientPort, - SSLParametersImpl sslParameters) throws IOException { + SSLParametersImpl sslParameters) throws IOException { super(hostname, port, clientAddress, clientPort, sslParameters); } Java8EngineSocket(InetAddress address, int port, InetAddress clientAddress, int clientPort, - SSLParametersImpl sslParameters) throws IOException { + SSLParametersImpl sslParameters) throws IOException { super(address, port, clientAddress, clientPort, sslParameters); } Java8EngineSocket(Socket socket, String hostname, int port, boolean autoClose, - SSLParametersImpl sslParameters) throws IOException { + SSLParametersImpl sslParameters) throws IOException { super(socket, hostname, port, autoClose, sslParameters); } @@ -76,7 +77,7 @@ public BiFunction, String> getHandshakeApplicationProtoc } private static ApplicationProtocolSelector toApplicationProtocolSelector( - final BiFunction, String> selector) { + final BiFunction, String> selector) { return selector == null ? null : new ApplicationProtocolSelector() { @Override public String selectApplicationProtocol(SSLEngine socket, List protocols) { diff --git a/common/src/main/java/org/conscrypt/Java8EngineWrapper.java b/common/src/main/java/org/conscrypt/Java8EngineWrapper.java index 5cf135d4f..62f89d264 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); } diff --git a/common/src/main/java/org/conscrypt/Java8ExtendedSSLSession.java b/common/src/main/java/org/conscrypt/Java8ExtendedSSLSession.java index 6330d3bbb..31bd5e08d 100644 --- a/common/src/main/java/org/conscrypt/Java8ExtendedSSLSession.java +++ b/common/src/main/java/org/conscrypt/Java8ExtendedSSLSession.java @@ -18,6 +18,7 @@ import java.util.Collections; import java.util.List; + import javax.net.ssl.ExtendedSSLSession; import javax.net.ssl.SNIHostName; import javax.net.ssl.SNIServerName; @@ -27,18 +28,17 @@ * on Java 8+. */ class Java8ExtendedSSLSession extends Java7ExtendedSSLSession { + public Java8ExtendedSSLSession(ExternalSession delegate) { + super(delegate); + } - public Java8ExtendedSSLSession(ExternalSession delegate) { - super(delegate); - } - - @Override - public final List getRequestedServerNames() { - String requestedServerName = delegate.getRequestedServerName(); - if (requestedServerName == null) { - return Collections.emptyList(); - } + @Override + public final List getRequestedServerNames() { + String requestedServerName = delegate.getRequestedServerName(); + if (requestedServerName == null) { + return Collections.emptyList(); + } - return Collections.singletonList((SNIServerName) new SNIHostName(requestedServerName)); - } + return Collections.singletonList((SNIServerName) new SNIHostName(requestedServerName)); + } } diff --git a/common/src/main/java/org/conscrypt/Java8FileDescriptorSocket.java b/common/src/main/java/org/conscrypt/Java8FileDescriptorSocket.java index 5cc35fa27..f69338fa2 100644 --- a/common/src/main/java/org/conscrypt/Java8FileDescriptorSocket.java +++ b/common/src/main/java/org/conscrypt/Java8FileDescriptorSocket.java @@ -21,6 +21,7 @@ import java.net.Socket; import java.util.List; import java.util.function.BiFunction; + import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLSocket; @@ -47,17 +48,17 @@ final class Java8FileDescriptorSocket extends ConscryptFileDescriptorSocket { } Java8FileDescriptorSocket(String hostname, int port, InetAddress clientAddress, int clientPort, - SSLParametersImpl sslParameters) throws IOException { + SSLParametersImpl sslParameters) throws IOException { super(hostname, port, clientAddress, clientPort, sslParameters); } - Java8FileDescriptorSocket(InetAddress address, int port, InetAddress clientAddress, int clientPort, - SSLParametersImpl sslParameters) throws IOException { + Java8FileDescriptorSocket(InetAddress address, int port, InetAddress clientAddress, + int clientPort, SSLParametersImpl sslParameters) throws IOException { super(address, port, clientAddress, clientPort, sslParameters); } Java8FileDescriptorSocket(Socket socket, String hostname, int port, boolean autoClose, - SSLParametersImpl sslParameters) throws IOException { + SSLParametersImpl sslParameters) throws IOException { super(socket, hostname, port, autoClose, sslParameters); } @@ -76,7 +77,7 @@ public BiFunction, String> getHandshakeApplicationProtoc } private static ApplicationProtocolSelector toApplicationProtocolSelector( - final BiFunction, String> selector) { + final BiFunction, String> selector) { return selector == null ? null : new ApplicationProtocolSelector() { @Override public String selectApplicationProtocol(SSLEngine socket, List protocols) { diff --git a/common/src/main/java/org/conscrypt/KeyGeneratorImpl.java b/common/src/main/java/org/conscrypt/KeyGeneratorImpl.java index e7b6b3329..0701a5211 100644 --- a/common/src/main/java/org/conscrypt/KeyGeneratorImpl.java +++ b/common/src/main/java/org/conscrypt/KeyGeneratorImpl.java @@ -19,6 +19,7 @@ import java.security.InvalidParameterException; import java.security.SecureRandom; import java.security.spec.AlgorithmParameterSpec; + import javax.crypto.KeyGeneratorSpi; import javax.crypto.SecretKey; import javax.crypto.spec.DESedeKeySpec; @@ -56,8 +57,8 @@ protected void engineInit(AlgorithmParameterSpec params, SecureRandom secureRand if (params == null) { throw new InvalidAlgorithmParameterException("No params provided"); } else { - throw new InvalidAlgorithmParameterException( - "Unknown param type: " + params.getClass().getName()); + throw new InvalidAlgorithmParameterException("Unknown param type: " + + params.getClass().getName()); } } diff --git a/common/src/main/java/org/conscrypt/KeyManagerFactoryImpl.java b/common/src/main/java/org/conscrypt/KeyManagerFactoryImpl.java index 0b83d0bfd..a6ba3b8b3 100644 --- a/common/src/main/java/org/conscrypt/KeyManagerFactoryImpl.java +++ b/common/src/main/java/org/conscrypt/KeyManagerFactoryImpl.java @@ -16,6 +16,8 @@ */ package org.conscrypt; +import org.conscrypt.io.IoUtils; + import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -26,10 +28,10 @@ import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; + import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactorySpi; import javax.net.ssl.ManagerFactoryParameters; -import org.conscrypt.io.IoUtils; /** * KeyManagerFactory implementation. @@ -37,11 +39,10 @@ */ @Internal public class KeyManagerFactoryImpl extends KeyManagerFactorySpi { - // source of key material private KeyStore keyStore; - //password + // password private char[] pwd; /** @@ -49,8 +50,7 @@ public class KeyManagerFactoryImpl extends KeyManagerFactorySpi { */ @Override protected void engineInit(KeyStore ks, char[] password) - throws KeyStoreException, NoSuchAlgorithmException, - UnrecoverableKeyException { + throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException { if (ks != null) { keyStore = ks; if (password != null) { @@ -62,7 +62,8 @@ protected void engineInit(KeyStore ks, char[] password) keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); String keyStoreName = System.getProperty("javax.net.ssl.keyStore"); String keyStorePwd = null; - if (keyStoreName == null || keyStoreName.equalsIgnoreCase("NONE") || keyStoreName.isEmpty()) { + if (keyStoreName == null || keyStoreName.equalsIgnoreCase("NONE") + || keyStoreName.isEmpty()) { try { keyStore.load(null, null); } catch (IOException e) { @@ -91,9 +92,7 @@ protected void engineInit(KeyStore ks, char[] password) IoUtils.closeQuietly(fis); } } - } - } /** @@ -102,9 +101,7 @@ protected void engineInit(KeyStore ks, char[] password) @Override protected void engineInit(ManagerFactoryParameters spec) throws InvalidAlgorithmParameterException { - throw new InvalidAlgorithmParameterException( - "ManagerFactoryParameters not supported"); - + throw new InvalidAlgorithmParameterException("ManagerFactoryParameters not supported"); } /** @@ -115,6 +112,6 @@ protected KeyManager[] engineGetKeyManagers() { if (keyStore == null) { throw new IllegalStateException("KeyManagerFactory is not initialized"); } - return new KeyManager[] { new KeyManagerImpl(keyStore, pwd) }; + return new KeyManager[] {new KeyManagerImpl(keyStore, pwd)}; } } diff --git a/common/src/main/java/org/conscrypt/KeyManagerImpl.java b/common/src/main/java/org/conscrypt/KeyManagerImpl.java index afd957dcf..6879c3fc8 100644 --- a/common/src/main/java/org/conscrypt/KeyManagerImpl.java +++ b/common/src/main/java/org/conscrypt/KeyManagerImpl.java @@ -33,6 +33,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; + import javax.net.ssl.SSLEngine; import javax.net.ssl.X509ExtendedKeyManager; import javax.security.auth.x500.X500Principal; @@ -48,14 +49,13 @@ * @see javax.net.ssl.KeyManager */ class KeyManagerImpl extends X509ExtendedKeyManager { - // hashed key store information private final HashMap hash; /** * Creates Key manager */ - @SuppressWarnings("JdkObsolete") // KeyStore#aliases is the only way of enumerating all entries + @SuppressWarnings("JdkObsolete") // KeyStore#aliases is the only way of enumerating all entries KeyManagerImpl(KeyStore keyStore, char[] pwd) { this.hash = new HashMap<>(); final Enumeration aliases; @@ -70,8 +70,8 @@ class KeyManagerImpl extends X509ExtendedKeyManager { if (keyStore.entryInstanceOf(alias, PrivateKeyEntry.class)) { PrivateKeyEntry entry; try { - entry = (PrivateKeyEntry) keyStore - .getEntry(alias, new KeyStore.PasswordProtection(pwd)); + entry = (PrivateKeyEntry) keyStore.getEntry( + alias, new KeyStore.PasswordProtection(pwd)); } catch (UnsupportedOperationException e) { // If the KeyStore doesn't support getEntry(), as Android Keystore // doesn't, fall back to reading the two values separately. @@ -81,7 +81,8 @@ class KeyManagerImpl extends X509ExtendedKeyManager { } hash.put(alias, entry); } - } catch (KeyStoreException | UnrecoverableEntryException | NoSuchAlgorithmException ignored) { + } catch (KeyStoreException | UnrecoverableEntryException + | NoSuchAlgorithmException ignored) { // Ignored. } } @@ -95,7 +96,7 @@ public String chooseClientAlias(String[] keyTypes, Principal[] issuers, Socket s @Override public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { - final String[] al = chooseAlias(new String[] { keyType }, issuers); + final String[] al = chooseAlias(new String[] {keyType}, issuers); return (al == null ? null : al[0]); } @@ -115,17 +116,16 @@ public X509Certificate[] getCertificateChain(String alias) { } } return null; - } @Override public String[] getClientAliases(String keyType, Principal[] issuers) { - return chooseAlias(new String[] { keyType }, issuers); + return chooseAlias(new String[] {keyType}, issuers); } @Override public String[] getServerAliases(String keyType, Principal[] issuers) { - return chooseAlias(new String[] { keyType }, issuers); + return chooseAlias(new String[] {keyType}, issuers); } @Override @@ -140,14 +140,15 @@ public PrivateKey getPrivateKey(String alias) { } @Override - public String chooseEngineClientAlias(String[] keyTypes, Principal[] issuers, SSLEngine engine) { + public String chooseEngineClientAlias(String[] keyTypes, Principal[] issuers, + SSLEngine engine) { final String[] al = chooseAlias(keyTypes, issuers); return (al == null ? null : al[0]); } @Override public String chooseEngineServerAlias(String keyType, Principal[] issuers, SSLEngine engine) { - final String[] al = chooseAlias(new String[] { keyType }, issuers); + final String[] al = chooseAlias(new String[] {keyType}, issuers); return (al == null ? null : al[0]); } @@ -162,9 +163,10 @@ private String[] chooseAlias(String[] keyTypes, Principal[] issuers) { final Certificate[] chain = entry.getValue().getCertificateChain(); final Certificate cert = chain[0]; final String certKeyAlg = cert.getPublicKey().getAlgorithm(); - final String certSigAlg = (cert instanceof X509Certificate - ? ((X509Certificate) cert).getSigAlgName().toUpperCase(Locale.US) - : null); + final String certSigAlg = + (cert instanceof X509Certificate + ? ((X509Certificate) cert).getSigAlgName().toUpperCase(Locale.US) + : null); for (String keyAlgorithm : keyTypes) { if (keyAlgorithm == null) { continue; @@ -190,7 +192,7 @@ private String[] chooseAlias(String[] keyTypes, Principal[] issuers) { */ // sig algorithm does not match if (sigAlgorithm != null && certSigAlg != null - && !certSigAlg.contains(sigAlgorithm)) { + && !certSigAlg.contains(sigAlgorithm)) { continue; } // no issuers to match, just add to return list and continue diff --git a/common/src/main/java/org/conscrypt/KeySpecUtil.java b/common/src/main/java/org/conscrypt/KeySpecUtil.java index 9727b5467..75a752a55 100644 --- a/common/src/main/java/org/conscrypt/KeySpecUtil.java +++ b/common/src/main/java/org/conscrypt/KeySpecUtil.java @@ -40,7 +40,7 @@ public static T makeRawKeySpec(byte[] bytes, Class keySpe } return instance; } catch (NoSuchMethodException | InvocationTargetException | InstantiationException - | IllegalAccessException e) { + | IllegalAccessException e) { throw new InvalidKeySpecException( "Can't process KeySpec class " + keySpecClass.getName(), e); } diff --git a/common/src/main/java/org/conscrypt/NativeCrypto.java b/common/src/main/java/org/conscrypt/NativeCrypto.java index 9269ba708..e939f43b7 100644 --- a/common/src/main/java/org/conscrypt/NativeCrypto.java +++ b/common/src/main/java/org/conscrypt/NativeCrypto.java @@ -87,7 +87,7 @@ static void checkAvailability() { // --- DSA/RSA public/private key handling functions ----------------------- 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); static native int EVP_PKEY_type(NativeRef.EVP_PKEY pkey); @@ -140,17 +140,19 @@ static native byte[] EVP_raw_X25519_private_key(byte[] data) 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); + static native int RSA_private_encrypt(int flen, byte[] from, byte[] to, NativeRef.EVP_PKEY pkey, + int padding); 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); + static native int RSA_public_encrypt(int flen, byte[] from, byte[] to, NativeRef.EVP_PKEY pkey, + int padding); 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} @@ -168,17 +170,18 @@ static native int RSA_private_decrypt(int flen, byte[] from, byte[] to, NativeRe * Returns the encrypted or decrypted version of the data. */ 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); + static native long EVP_PKEY_new_EC_KEY(NativeRef.EC_GROUP groupRef, + NativeRef.EC_POINT pubkeyRef, byte[] privkey); 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); + static native long EC_GROUP_new_arbitrary(byte[] p, byte[] a, byte[] b, byte[] x, byte[] y, + byte[] order, int cofactor); static native String EC_GROUP_get_curve_name(NativeRef.EC_GROUP groupRef); @@ -198,11 +201,12 @@ static native long EC_GROUP_new_arbitrary( 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); + 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); + 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); @@ -217,7 +221,8 @@ static native void EC_POINT_set_affine_coordinates( static native long EC_KEY_parse_curve_name(byte[] encoded) throws IOException; 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; static native int ECDSA_size(NativeRef.EVP_PKEY pkey); @@ -239,8 +244,8 @@ static native int ECDH_compute_key(byte[] out, int outOffset, NativeRef.EVP_PKEY 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); + static native int SLHDSA_SHA2_128S_verify(byte[] data, int dataLen, byte[] sig, + byte[] publicKey); // --- Curve25519 -------------- @@ -270,15 +275,15 @@ static native boolean X25519(byte[] out, byte[] privateKey, byte[] publicKey) 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); + static native int EVP_MD_CTX_copy_ex(NativeRef.EVP_MD_CTX dst_ctx, + NativeRef.EVP_MD_CTX src_ctx); // --- Digest handling functions ------------------------------------------- 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); + static native void EVP_DigestUpdate(NativeRef.EVP_MD_CTX ctx, byte[] buffer, int offset, + int length); static native void EVP_DigestUpdateDirect(NativeRef.EVP_MD_CTX ctx, long ptr, int length); @@ -286,43 +291,45 @@ static native void EVP_DigestUpdate( // --- Signature handling functions ---------------------------------------- - static native long EVP_DigestSignInit( - NativeRef.EVP_MD_CTX ctx, long evpMdRef, NativeRef.EVP_PKEY key); + 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); + 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); + static native void EVP_DigestSignUpdate(NativeRef.EVP_MD_CTX ctx, byte[] buffer, int offset, + int length); 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); + static native void EVP_DigestVerifyUpdate(NativeRef.EVP_MD_CTX ctx, byte[] buffer, int offset, + int length); static native void EVP_DigestVerifyUpdateDirect(NativeRef.EVP_MD_CTX ctx, long ptr, int length); static native byte[] EVP_DigestSignFinal(NativeRef.EVP_MD_CTX ctx); 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); + static native byte[] EVP_DigestSign(NativeRef.EVP_MD_CTX ctx, byte[] buffer, int offset, + int length); 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); static native long EVP_PKEY_encrypt_init(NativeRef.EVP_PKEY pkey) throws InvalidKeyException; 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; static native long EVP_PKEY_decrypt_init(NativeRef.EVP_PKEY pkey) throws InvalidKeyException; 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; static native void EVP_PKEY_CTX_free(long pkeyCtx); @@ -348,10 +355,11 @@ static native void EVP_PKEY_CTX_set_rsa_oaep_label(long ctx, byte[] label) static native long EVP_get_cipherbyname(String string); static native void EVP_CipherInit_ex(NativeRef.EVP_CIPHER_CTX ctx, long evpCipher, byte[] key, - byte[] iv, boolean encrypting); + byte[] iv, boolean encrypting); 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; static native int EVP_CipherFinal_ex(NativeRef.EVP_CIPHER_CTX ctx, byte[] out, int outOffset) throws BadPaddingException, IllegalBlockSizeException; @@ -366,8 +374,8 @@ static native int EVP_CipherFinal_ex(NativeRef.EVP_CIPHER_CTX ctx, byte[] out, i 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); + static native void EVP_CIPHER_CTX_set_padding(NativeRef.EVP_CIPHER_CTX ctx, + boolean enablePadding); static native void EVP_CIPHER_CTX_set_key_length(NativeRef.EVP_CIPHER_CTX ctx, int keyBitSize); @@ -389,19 +397,23 @@ static native void EVP_CIPHER_CTX_set_padding( static native int EVP_AEAD_nonce_length(long evpAead); 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; 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; 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; 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 ------------------------------------------------------ @@ -437,41 +449,46 @@ static native int EVP_AEAD_CTX_open_buf(long evpAead, byte[] key, int tagLengthI 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); + 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; + 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); + 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); + 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); + 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); } 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 ---------------------------------------------------------------- @@ -537,10 +554,10 @@ private static int X509_NAME_hash(X500Principal principal, String algorithm) { static native void X509_free(long x509ctx, OpenSSLX509Certificate holder); 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); + static native void X509_print_ex(long bioCtx, long x509ctx, OpenSSLX509Certificate holder, + long nmflag, long certflag); static native byte[] X509_get_issuer_name(long x509ctx, OpenSSLX509Certificate holder); @@ -561,11 +578,12 @@ static native long X509_get_pubkey(long x509ctx, OpenSSLX509Certificate holder) 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); + static native String[] get_X509_ext_oids(long x509ctx, OpenSSLX509Certificate holder, + int critical); static native Object[][] get_X509_GENERAL_NAME_stack(long x509ctx, - OpenSSLX509Certificate holder, int type) throws CertificateParsingException; + OpenSSLX509Certificate holder, int type) + throws CertificateParsingException; static native boolean[] get_X509_ex_kusage(long x509ctx, OpenSSLX509Certificate holder); @@ -584,12 +602,13 @@ static native long X509_get_notAfter(long x509ctx, OpenSSLX509Certificate holder static native byte[] X509_get_serialNumber(long x509ctx, OpenSSLX509Certificate holder); static native void X509_verify(long x509ctx, OpenSSLX509Certificate holder, - NativeRef.EVP_PKEY pkeyCtx) throws BadPaddingException, IllegalBlockSizeException; + NativeRef.EVP_PKEY pkeyCtx) + throws BadPaddingException, IllegalBlockSizeException; 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); + static native byte[] get_X509_tbs_cert_without_ext(long x509ctx, OpenSSLX509Certificate holder, + String oid); static native byte[] get_X509_signature(long x509ctx, OpenSSLX509Certificate holder); @@ -597,8 +616,8 @@ static native byte[] get_X509_tbs_cert_without_ext( // Used by Android platform TrustedCertificateStore. @SuppressWarnings("unused") - static native int X509_check_issued( - long ctx, OpenSSLX509Certificate holder, long ctx2, OpenSSLX509Certificate holder2); + static native int X509_check_issued(long ctx, OpenSSLX509Certificate holder, long ctx2, + OpenSSLX509Certificate holder2); // --- PKCS7 --------------------------------------------------------------- @@ -636,18 +655,18 @@ static native int X509_check_issued( 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); + 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); + 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. */ 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); + static native String[] get_X509_CRL_ext_oids(long x509Crlctx, OpenSSLX509CRL holder, + int critical); static native byte[] X509_CRL_get_ext_oid(long x509CrlCtx, OpenSSLX509CRL holder, String oid); @@ -658,9 +677,9 @@ static native String[] get_X509_CRL_ext_oids( static native byte[] get_X509_CRL_signature(long x509ctx, OpenSSLX509CRL holder); 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; static native byte[] get_X509_CRL_crl_enc(long x509CrlCtx, OpenSSLX509CRL holder); @@ -676,24 +695,24 @@ static native long X509_CRL_get_nextUpdate(long x509CrlCtx, OpenSSLX509CRL holde static native byte[] i2d_X509_REVOKED(long x509RevokedCtx, OpenSSLX509CRLEntry holder); - static native String[] get_X509_REVOKED_ext_oids( - long x509ctx, int critical, OpenSSLX509CRLEntry holder); + 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); + 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); + static native byte[] X509_REVOKED_get_serialNumber(long x509RevokedCtx, + OpenSSLX509CRLEntry holder); - static native long X509_REVOKED_get_ext( - long x509RevokedCtx, String oid, OpenSSLX509CRLEntry holder); + 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); + static native long get_X509_REVOKED_revocationDate(long x509RevokedCtx, + OpenSSLX509CRLEntry holder); - static native void X509_REVOKED_print( - long bioRef, long x509RevokedCtx, OpenSSLX509CRLEntry holder); + static native void X509_REVOKED_print(long bioRef, long x509RevokedCtx, + OpenSSLX509CRLEntry holder); static native void X509_REVOKED_free(long x509RevokedCtx, OpenSSLX509CRLEntry holder); @@ -708,8 +727,11 @@ static native void X509_REVOKED_print( * Used for both client and server. */ 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 ----------------------------------------------------------- @@ -1040,17 +1062,17 @@ 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()); } 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); + 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); + static native long SSL_CTX_set_timeout(long ssl_ctx, AbstractSessionContext holder, + long seconds); static native long SSL_new(long ssl_ctx, AbstractSessionContext holder) throws SSLException; @@ -1059,8 +1081,8 @@ static native void SSL_enable_tls_channel_id(long ssl, NativeSsl ssl_holder) 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); + static native void SSL_set1_tls_channel_id(long ssl, NativeSsl ssl_holder, + NativeRef.EVP_PKEY pkey); /** * Sets the local certificates and private key. @@ -1071,10 +1093,12 @@ static native void SSL_set1_tls_channel_id( * @throws SSLException if a problem occurs setting the cert/key. */ 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; static native void SSL_set_client_CA_list(long ssl, NativeSsl ssl_holder, - byte[][] asn1DerEncodedX500Principals) throws SSLException; + byte[][] asn1DerEncodedX500Principals) + throws SSLException; static native long SSL_set_mode(long ssl, NativeSsl ssl_holder, long mode); @@ -1082,15 +1106,15 @@ static native void SSL_set_client_CA_list(long ssl, NativeSsl ssl_holder, 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); + static native int SSL_set_protocol_versions(long ssl, NativeSsl ssl_holder, int min_version, + int max_version); static native void SSL_enable_signed_cert_timestamps(long ssl, NativeSsl ssl_holder); 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); + static native void SSL_set_signed_cert_timestamp_list(long ssl, NativeSsl ssl_holder, + byte[] list); static native void SSL_enable_ocsp_stapling(long ssl, NativeSsl ssl_holder); @@ -1101,16 +1125,17 @@ static native void SSL_set_signed_cert_timestamp_list( static native byte[] SSL_get_tls_unique(long ssl, NativeSsl ssl_holder); 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; + 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); + 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); + 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) { @@ -1215,8 +1240,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) { @@ -1257,8 +1282,8 @@ static String[] checkEnabledProtocols(String[] protocols) { */ 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 +1296,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 +1317,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,8 +1335,8 @@ 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; } @@ -1325,8 +1350,9 @@ static String[] checkEnabledCipherSuites(String[] cipherSuites) { 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; + static native void SSL_set_session_creation_enabled(long ssl, NativeSsl ssl_holder, + boolean creationEnabled) + throws SSLException; static native boolean SSL_session_reused(long ssl, NativeSsl ssl_holder); @@ -1338,7 +1364,7 @@ static native void SSL_set_tlsext_host_name(long ssl, NativeSsl ssl_holder, Stri 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; public static native String SSL_get_current_cipher(long ssl, NativeSsl ssl_holder); @@ -1359,19 +1385,19 @@ static native void SSL_do_handshake(long ssl, NativeSsl ssl_holder, FileDescript * @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. */ 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; 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; static native int SSL_get_shutdown(long ssl, NativeSsl ssl_holder); @@ -1433,8 +1459,8 @@ 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; /** @@ -1515,8 +1541,10 @@ void clientCertificateRequested( static native String[] get_cipher_names(String selection); 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 @@ -1546,8 +1574,8 @@ public static native byte[] get_ocsp_single_extension(byte[] ocspResponse, Strin * 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; + 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 @@ -1555,8 +1583,8 @@ static native void setApplicationProtocols( * 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; + 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 @@ -1574,8 +1602,8 @@ static native void setHasApplicationProtocolSelector( * 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 @@ -1592,45 +1620,49 @@ static native int ENGINE_SSL_do_handshake( * @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. @@ -1660,8 +1692,8 @@ 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. diff --git a/common/src/main/java/org/conscrypt/NativeRef.java b/common/src/main/java/org/conscrypt/NativeRef.java index c1f27dcf0..e45faff5e 100644 --- a/common/src/main/java/org/conscrypt/NativeRef.java +++ b/common/src/main/java/org/conscrypt/NativeRef.java @@ -61,7 +61,6 @@ public boolean isNull() { return address == 0; } - abstract void doFree(long context); static final class CMAC_CTX extends NativeRef { diff --git a/common/src/main/java/org/conscrypt/NativeSsl.java b/common/src/main/java/org/conscrypt/NativeSsl.java index ebf915ed9..7fe7c49d7 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); @@ -373,17 +373,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 +408,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 +521,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 +536,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(); } @@ -589,8 +590,8 @@ private void setCertificateValidation() throws SSLException { // 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 +659,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 +669,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 +765,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/NativeSslSession.java b/common/src/main/java/org/conscrypt/NativeSslSession.java index ff8aba475..078830004 100644 --- a/common/src/main/java/org/conscrypt/NativeSslSession.java +++ b/common/src/main/java/org/conscrypt/NativeSslSession.java @@ -31,6 +31,7 @@ import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; + import javax.net.ssl.SSLException; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSession; @@ -54,8 +55,8 @@ static NativeSslSession newInstance(NativeRef.SSL_SESSION ref, ConscryptSession AbstractSessionContext context = (AbstractSessionContext) session.getSessionContext(); if (context instanceof ClientSessionContext) { return new Impl(context, ref, session.getPeerHost(), session.getPeerPort(), - session.getPeerCertificates(), getOcspResponse(session), - session.getPeerSignedCertificateTimestamp()); + session.getPeerCertificates(), getOcspResponse(session), + session.getPeerSignedCertificateTimestamp()); } // Server's will be cached by ID and won't have any of the extra fields. @@ -77,8 +78,8 @@ private static byte[] getOcspResponse(ConscryptSession session) { * @return The new instance if successful. If unable to parse the bytes for any reason, returns * {@code null}. */ - static NativeSslSession newInstance( - AbstractSessionContext context, byte[] data, String host, int port) { + static NativeSslSession newInstance(AbstractSessionContext context, byte[] data, String host, + int port) { ByteBuffer buf = ByteBuffer.wrap(data); try { int type = buf.getInt(); @@ -224,8 +225,8 @@ private static final class Impl extends NativeSslSession { private final byte[] peerSignedCertificateTimestamp; private Impl(AbstractSessionContext context, NativeRef.SSL_SESSION ref, String host, - int port, java.security.cert.X509Certificate[] peerCertificates, - byte[] peerOcspStapledResponse, byte[] peerSignedCertificateTimestamp) { + int port, java.security.cert.X509Certificate[] peerCertificates, + byte[] peerOcspStapledResponse, byte[] peerSignedCertificateTimestamp) { this.context = context; this.host = host; this.port = port; @@ -251,9 +252,10 @@ private long getCreationTime() { boolean isValid() { long creationTimeMillis = getCreationTime(); // Use the minimum of the timeout from the context and the session. - long timeoutMillis = Math.max(0, - Math.min(context.getSessionTimeout(), - NativeCrypto.SSL_SESSION_get_timeout(ref.address))) + long timeoutMillis = + Math.max(0, + Math.min(context.getSessionTimeout(), + NativeCrypto.SSL_SESSION_get_timeout(ref.address))) * 1000; return (System.currentTimeMillis() - timeoutMillis) < creationTimeMillis; } @@ -465,7 +467,7 @@ public int getApplicationBufferSize() { private static void log(Throwable t) { // TODO(nathanmittler): Better error handling? logger.log(Level.FINE, "Error inflating SSL session: {0}", - (t.getMessage() != null ? t.getMessage() : t.getClass().getName())); + (t.getMessage() != null ? t.getMessage() : t.getClass().getName())); } private static void checkRemaining(ByteBuffer buf, int length) throws IOException { @@ -473,8 +475,8 @@ private static void checkRemaining(ByteBuffer buf, int length) throws IOExceptio throw new IOException("Length is negative: " + length); } if (length > buf.remaining()) { - throw new IOException( - "Length of blob is longer than available: " + length + " > " + buf.remaining()); + throw new IOException("Length of blob is longer than available: " + length + " > " + + buf.remaining()); } } } diff --git a/common/src/main/java/org/conscrypt/OAEPParameters.java b/common/src/main/java/org/conscrypt/OAEPParameters.java index a4484a39f..9e5b7a601 100644 --- a/common/src/main/java/org/conscrypt/OAEPParameters.java +++ b/common/src/main/java/org/conscrypt/OAEPParameters.java @@ -23,6 +23,7 @@ import java.security.spec.MGF1ParameterSpec; import java.util.HashMap; import java.util.Map; + import javax.crypto.spec.OAEPParameterSpec; import javax.crypto.spec.PSource; @@ -32,7 +33,6 @@ */ @Internal public class OAEPParameters extends AlgorithmParametersSpi { - private static final Map OID_TO_NAME = new HashMap(); private static final Map NAME_TO_OID = new HashMap(); static { @@ -94,11 +94,11 @@ protected void engineInit(byte[] bytes) throws IOException { } if (!NativeCrypto.asn1_read_is_empty(seqRef) - || !NativeCrypto.asn1_read_is_empty(readRef)) { + || !NativeCrypto.asn1_read_is_empty(readRef)) { throw new IOException("Error reading ASN.1 encoding"); } - this.spec = new OAEPParameterSpec(hash, "MGF1", new MGF1ParameterSpec(mgfHash), - pSpecified); + this.spec = + new OAEPParameterSpec(hash, "MGF1", new MGF1ParameterSpec(mgfHash), pSpecified); } finally { NativeCrypto.asn1_read_free(seqRef); NativeCrypto.asn1_read_free(readRef); @@ -161,8 +161,7 @@ private static String getHashName(long hashRef) throws IOException { if (!NativeCrypto.asn1_read_is_empty(hashSeqRef)) { NativeCrypto.asn1_read_null(hashSeqRef); } - if (!NativeCrypto.asn1_read_is_empty(hashSeqRef) - || !OID_TO_NAME.containsKey(hashOid)) { + if (!NativeCrypto.asn1_read_is_empty(hashSeqRef) || !OID_TO_NAME.containsKey(hashOid)) { throw new IOException("Error reading ASN.1 encoding"); } return OID_TO_NAME.get(hashOid); @@ -190,7 +189,7 @@ protected byte[] engineGetEncoded() throws IOException { cbbRef = NativeCrypto.asn1_write_init(); seqRef = NativeCrypto.asn1_write_sequence(cbbRef); writeHashAndMgfHash(seqRef, spec.getDigestAlgorithm(), - (MGF1ParameterSpec) spec.getMGFParameters()); + (MGF1ParameterSpec) spec.getMGFParameters()); PSource.PSpecified pSource = (PSource.PSpecified) spec.getPSource(); // Implementations are prohibited from writing the default value for any of the fields if (pSource.getValue().length != 0) { @@ -225,15 +224,15 @@ protected byte[] engineGetEncoded(String format) throws IOException { } // Shared with PSSParameters, since they share some of their encoded form - static void writeHashAndMgfHash(long seqRef, String hash, MGF1ParameterSpec mgfSpec) throws IOException { + static void writeHashAndMgfHash(long seqRef, String hash, MGF1ParameterSpec mgfSpec) + throws IOException { // Implementations are prohibited from writing the default value for any of the fields if (!hash.equals("SHA-1")) { long hashRef = 0; long hashParamsRef = 0; try { hashRef = NativeCrypto.asn1_write_tag(seqRef, 0); - hashParamsRef = writeAlgorithmIdentifier( - hashRef, NAME_TO_OID.get(hash)); + hashParamsRef = writeAlgorithmIdentifier(hashRef, NAME_TO_OID.get(hash)); NativeCrypto.asn1_write_null(hashParamsRef); } finally { NativeCrypto.asn1_write_flush(seqRef); diff --git a/common/src/main/java/org/conscrypt/OidData.java b/common/src/main/java/org/conscrypt/OidData.java index 87d284b81..2e3010ddf 100644 --- a/common/src/main/java/org/conscrypt/OidData.java +++ b/common/src/main/java/org/conscrypt/OidData.java @@ -23,41 +23,40 @@ * Data about OIDs. */ final class OidData { - - private OidData() {} - - private static final Map OID_TO_NAME_MAP = new HashMap<>(); - - static { - // NOTE: For the time being, we only have X509 signature algorithms here, since we only need - // them for determining the name of signature algorithms in certs and CRLs. We can add more in - // the future if we need them. - - // Signatures - - // RFC 3279 - OID_TO_NAME_MAP.put("1.2.840.113549.1.1.2", "MD2withRSA"); - OID_TO_NAME_MAP.put("1.2.840.113549.1.1.4", "MD5withRSA"); - OID_TO_NAME_MAP.put("1.2.840.113549.1.1.5", "SHA1withRSA"); - OID_TO_NAME_MAP.put("1.2.840.10040.4.3", "SHA1withDSA"); - OID_TO_NAME_MAP.put("1.2.840.10045.4.1", "SHA1withECDSA"); - - // RFC 4055 - OID_TO_NAME_MAP.put("1.2.840.113549.1.1.14", "SHA224withRSA"); - OID_TO_NAME_MAP.put("1.2.840.113549.1.1.11", "SHA256withRSA"); - OID_TO_NAME_MAP.put("1.2.840.113549.1.1.12", "SHA384withRSA"); - OID_TO_NAME_MAP.put("1.2.840.113549.1.1.13", "SHA512withRSA"); - - // RFC 5758 - OID_TO_NAME_MAP.put("2.16.840.1.101.3.4.3.1", "SHA224withDSA"); - OID_TO_NAME_MAP.put("2.16.840.1.101.3.4.3.2", "SHA256withDSA"); - OID_TO_NAME_MAP.put("1.2.840.10045.4.3.1", "SHA224withECDSA"); - OID_TO_NAME_MAP.put("1.2.840.10045.4.3.2", "SHA256withECDSA"); - OID_TO_NAME_MAP.put("1.2.840.10045.4.3.3", "SHA384withECDSA"); - OID_TO_NAME_MAP.put("1.2.840.10045.4.3.4", "SHA512withECDSA"); - } - - public static String oidToAlgorithmName(String oid) { - return OID_TO_NAME_MAP.get(oid); - } + private OidData() {} + + private static final Map OID_TO_NAME_MAP = new HashMap<>(); + + static { + // NOTE: For the time being, we only have X509 signature algorithms here, since we only need + // them for determining the name of signature algorithms in certs and CRLs. We can add more + // in the future if we need them. + + // Signatures + + // RFC 3279 + OID_TO_NAME_MAP.put("1.2.840.113549.1.1.2", "MD2withRSA"); + OID_TO_NAME_MAP.put("1.2.840.113549.1.1.4", "MD5withRSA"); + OID_TO_NAME_MAP.put("1.2.840.113549.1.1.5", "SHA1withRSA"); + OID_TO_NAME_MAP.put("1.2.840.10040.4.3", "SHA1withDSA"); + OID_TO_NAME_MAP.put("1.2.840.10045.4.1", "SHA1withECDSA"); + + // RFC 4055 + OID_TO_NAME_MAP.put("1.2.840.113549.1.1.14", "SHA224withRSA"); + OID_TO_NAME_MAP.put("1.2.840.113549.1.1.11", "SHA256withRSA"); + OID_TO_NAME_MAP.put("1.2.840.113549.1.1.12", "SHA384withRSA"); + OID_TO_NAME_MAP.put("1.2.840.113549.1.1.13", "SHA512withRSA"); + + // RFC 5758 + OID_TO_NAME_MAP.put("2.16.840.1.101.3.4.3.1", "SHA224withDSA"); + OID_TO_NAME_MAP.put("2.16.840.1.101.3.4.3.2", "SHA256withDSA"); + OID_TO_NAME_MAP.put("1.2.840.10045.4.3.1", "SHA224withECDSA"); + OID_TO_NAME_MAP.put("1.2.840.10045.4.3.2", "SHA256withECDSA"); + OID_TO_NAME_MAP.put("1.2.840.10045.4.3.3", "SHA384withECDSA"); + OID_TO_NAME_MAP.put("1.2.840.10045.4.3.4", "SHA512withECDSA"); + } + + public static String oidToAlgorithmName(String oid) { + return OID_TO_NAME_MAP.get(oid); + } } diff --git a/common/src/main/java/org/conscrypt/OkHostnameVerifier.java b/common/src/main/java/org/conscrypt/OkHostnameVerifier.java index c14e3719d..9b3979ec3 100644 --- a/common/src/main/java/org/conscrypt/OkHostnameVerifier.java +++ b/common/src/main/java/org/conscrypt/OkHostnameVerifier.java @@ -26,6 +26,7 @@ import java.util.List; import java.util.Locale; import java.util.regex.Pattern; + import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; @@ -49,8 +50,8 @@ public final class OkHostnameVerifier implements ConscryptHostnameVerifier { * hostnames; they will be verified as IP addresses (which is a more strict * verification). */ - private static final Pattern VERIFY_AS_IP_ADDRESS = Pattern.compile( - "([0-9a-fA-F]*:[0-9a-fA-F:.]*)|([\\d.]+)"); + private static final Pattern VERIFY_AS_IP_ADDRESS = + Pattern.compile("([0-9a-fA-F]*:[0-9a-fA-F:.]*)|([\\d.]+)"); private static final int ALT_DNS_NAME = 2; private static final int ALT_IPA_NAME = 7; @@ -84,9 +85,8 @@ public boolean verify(X509Certificate[] certs, String host, SSLSession session) } public boolean verify(String host, X509Certificate certificate) { - return verifyAsIpAddress(host) - ? verifyIpAddress(host, certificate) - : verifyHostName(host, certificate); + return verifyAsIpAddress(host) ? verifyIpAddress(host, certificate) + : verifyHostName(host, certificate); } static boolean verifyAsIpAddress(String host) { @@ -186,12 +186,12 @@ private boolean verifyHostName(String hostName, String pattern) { // Basic sanity checks // Check length == 0 instead of .isEmpty() to support Java 5. if (hostName == null || hostName.length() == 0 || hostName.startsWith(".") - || hostName.endsWith("..")) { + || hostName.endsWith("..")) { // Invalid domain name return false; } if (pattern == null || pattern.length() == 0 || pattern.startsWith(".") - || pattern.endsWith("..")) { + || pattern.endsWith("..")) { // Invalid pattern/domain name return false; } @@ -231,18 +231,20 @@ private boolean verifyHostName(String hostName, String pattern) { // For example, *.example.com matches test.example.com but does not match // sub.test.example.com. // 3. Wildcard patterns for single-label domain names are not permitted. - // 4. Android-added: if strictWildcardMode is true then wildcards matching top-level domains, + // 4. Android-added: if strictWildcardMode is true then wildcards matching top-level + // domains, // e.g. *.com, are not permitted. if (!pattern.startsWith("*.") || pattern.indexOf('*', 1) != -1) { - // Asterisk (*) is only permitted in the left-most domain name label and must be the only - // character in that label + // Asterisk (*) is only permitted in the left-most domain name label and must be the + // only character in that label return false; } - // Optimization: check whether hostName is too short to match the pattern. hostName must be at - // least as long as the pattern because asterisk must match the whole left-most label and - // hostName starts with a non-empty label. Thus, asterisk has to match one or more characters. + // Optimization: check whether hostName is too short to match the pattern. hostName must be + // at least as long as the pattern because asterisk must match the whole left-most label and + // hostName starts with a non-empty label. Thus, asterisk has to match one or more + // characters. if (hostName.length() < pattern.length()) { // hostName too short to match the pattern. return false; @@ -275,7 +277,7 @@ private boolean verifyHostName(String hostName, String pattern) { // Check that asterisk did not match across domain name labels. int suffixStartIndexInHostName = hostName.length() - suffix.length(); if ((suffixStartIndexInHostName > 0) - && (hostName.lastIndexOf('.', suffixStartIndexInHostName - 1) != -1)) { + && (hostName.lastIndexOf('.', suffixStartIndexInHostName - 1) != -1)) { // Asterisk is matching across domain name labels -- not permitted. return false; } diff --git a/common/src/main/java/org/conscrypt/OpenSSLAeadCipher.java b/common/src/main/java/org/conscrypt/OpenSSLAeadCipher.java index 867803af1..a9368fd28 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLAeadCipher.java +++ b/common/src/main/java/org/conscrypt/OpenSSLAeadCipher.java @@ -97,8 +97,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 +132,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 +166,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 +178,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 +202,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 +219,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 +246,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 +286,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 +307,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 +319,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 +334,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 +375,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 +395,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 +413,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/OpenSSLAeadCipherAES.java b/common/src/main/java/org/conscrypt/OpenSSLAeadCipherAES.java index 92d55d138..b7bfb82e9 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLAeadCipherAES.java +++ b/common/src/main/java/org/conscrypt/OpenSSLAeadCipherAES.java @@ -39,7 +39,7 @@ void checkSupportedKeySize(int keyLength) throws InvalidKeyException { return; default: throw new InvalidKeyException("Unsupported key size: " + keyLength - + " bytes (must be 16 or 32)"); + + " bytes (must be 16 or 32)"); } } @@ -55,7 +55,7 @@ int getCipherBlockSize() { @Override protected AlgorithmParameterSpec getParameterSpec(AlgorithmParameters params) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException { if (params != null) { AlgorithmParameterSpec spec = Platform.fromGCMParameters(params); if (spec != null) { @@ -73,8 +73,7 @@ protected AlgorithmParameters engineGetParameters() { return null; } - AlgorithmParameterSpec spec = Platform.toGCMParameterSpec( - tagLengthInBytes * 8, iv); + AlgorithmParameterSpec spec = Platform.toGCMParameterSpec(tagLengthInBytes * 8, iv); if (spec == null) { // The platform doesn't support GCMParameterSpec. Fall back to // the generic AES parameters so at least the caller can get the @@ -88,7 +87,7 @@ protected AlgorithmParameters engineGetParameters() { return params; } catch (NoSuchAlgorithmException e) { // We should not get here. - throw (Error) new AssertionError("GCM not supported").initCause(e); + throw(Error) new AssertionError("GCM not supported").initCause(e); } catch (InvalidParameterSpecException e) { // This may happen since Conscrypt doesn't provide this itself. return null; @@ -108,7 +107,6 @@ int getOutputSizeForFinal(int inputLen) { } public static class GCM extends OpenSSLAeadCipherAES { - public GCM() { super(Mode.GCM); } @@ -137,8 +135,8 @@ public AES_128() {} @Override void checkSupportedKeySize(int keyLength) throws InvalidKeyException { if (keyLength != 16) { // 128 bits - throw new InvalidKeyException( - "Unsupported key size: " + keyLength + " bytes (must be 16)"); + throw new InvalidKeyException("Unsupported key size: " + keyLength + + " bytes (must be 16)"); } } } @@ -149,15 +147,14 @@ public AES_256() {} @Override void checkSupportedKeySize(int keyLength) throws InvalidKeyException { if (keyLength != 32) { // 256 bits - throw new InvalidKeyException( - "Unsupported key size: " + keyLength + " bytes (must be 32)"); + throw new InvalidKeyException("Unsupported key size: " + keyLength + + " bytes (must be 32)"); } } } } public static class GCM_SIV extends OpenSSLAeadCipherAES { - public GCM_SIV() { super(Mode.GCM_SIV); } @@ -176,11 +173,11 @@ boolean allowsNonceReuse() { @Override void checkSupportedTagLength(int tagLengthInBits) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException { // GCM_SIV only supports full-size tags if (tagLengthInBits != DEFAULT_TAG_SIZE_BITS) { - throw new InvalidAlgorithmParameterException( - "Tag length must be " + DEFAULT_TAG_SIZE_BITS + " bits"); + throw new InvalidAlgorithmParameterException("Tag length must be " + + DEFAULT_TAG_SIZE_BITS + " bits"); } } @@ -201,8 +198,8 @@ public AES_128() {} @Override void checkSupportedKeySize(int keyLength) throws InvalidKeyException { if (keyLength != 16) { // 128 bits - throw new InvalidKeyException( - "Unsupported key size: " + keyLength + " bytes (must be 16)"); + throw new InvalidKeyException("Unsupported key size: " + keyLength + + " bytes (must be 16)"); } } } @@ -213,8 +210,8 @@ public AES_256() {} @Override void checkSupportedKeySize(int keyLength) throws InvalidKeyException { if (keyLength != 32) { // 256 bits - throw new InvalidKeyException( - "Unsupported key size: " + keyLength + " bytes (must be 32)"); + throw new InvalidKeyException("Unsupported key size: " + keyLength + + " bytes (must be 32)"); } } } diff --git a/common/src/main/java/org/conscrypt/OpenSSLAeadCipherChaCha20.java b/common/src/main/java/org/conscrypt/OpenSSLAeadCipherChaCha20.java index 4c455efd8..aab1c1e7d 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLAeadCipherChaCha20.java +++ b/common/src/main/java/org/conscrypt/OpenSSLAeadCipherChaCha20.java @@ -29,7 +29,7 @@ public OpenSSLAeadCipherChaCha20() { void checkSupportedKeySize(int keyLength) throws InvalidKeyException { if (keyLength != 32) { throw new InvalidKeyException("Unsupported key size: " + keyLength - + " bytes (must be 32)"); + + " bytes (must be 32)"); } } diff --git a/common/src/main/java/org/conscrypt/OpenSSLBaseDHKeyAgreement.java b/common/src/main/java/org/conscrypt/OpenSSLBaseDHKeyAgreement.java index 2aa26432e..2ad52f6a1 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLBaseDHKeyAgreement.java +++ b/common/src/main/java/org/conscrypt/OpenSSLBaseDHKeyAgreement.java @@ -23,6 +23,7 @@ import java.security.PublicKey; import java.security.SecureRandom; import java.security.spec.AlgorithmParameterSpec; + import javax.crypto.KeyAgreementSpi; import javax.crypto.SecretKey; import javax.crypto.ShortBufferException; @@ -33,7 +34,6 @@ */ @Internal public abstract class OpenSSLBaseDHKeyAgreement extends KeyAgreementSpi { - /** OpenSSL handle of the private key. Only available after the engine has been initialized. */ private T mPrivateKey; @@ -80,7 +80,7 @@ public Key engineDoPhase(Key key, boolean lastPhase) throws InvalidKeyException } else { // The output is longer than expected throw new RuntimeException("Engine produced a longer than expected result. Expected: " - + mExpectedResultLength + ", actual: " + actualResultLength); + + mExpectedResultLength + ", actual: " + actualResultLength); } mResult = result; @@ -92,10 +92,11 @@ public Key engineDoPhase(Key key, boolean lastPhase) throws InvalidKeyException protected abstract T convertPrivateKey(PrivateKey key) throws InvalidKeyException; /** - * Given the public key {@code theirPublicKey} and the private key {@code ourPrivateKey} write the shared secret - * to {@code buffer} and return the actual output size. + * Given the public key {@code theirPublicKey} and the private key {@code ourPrivateKey} write + * the shared secret to {@code buffer} and return the actual output size. */ - protected abstract int computeKey(byte[] buffer, T theirPublicKey, T ourPrivateKey) throws InvalidKeyException; + protected abstract int computeKey(byte[] buffer, T theirPublicKey, T ourPrivateKey) + throws InvalidKeyException; @Override protected int engineGenerateSecret(byte[] sharedSecret, int offset) @@ -103,8 +104,8 @@ protected int engineGenerateSecret(byte[] sharedSecret, int offset) checkCompleted(); int available = sharedSecret.length - offset; if (mResult.length > available) { - throw new ShortBufferWithoutStackTraceException( - "Needed: " + mResult.length + ", available: " + available); + throw new ShortBufferWithoutStackTraceException("Needed: " + mResult.length + + ", available: " + available); } System.arraycopy(mResult, 0, sharedSecret, offset, mResult.length); @@ -141,11 +142,11 @@ protected void engineInit(Key key, SecureRandom random) throws InvalidKeyExcepti protected abstract int getOutputSize(T key); @Override - protected void engineInit(Key key, AlgorithmParameterSpec params, - SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { + protected void engineInit(Key key, AlgorithmParameterSpec params, SecureRandom random) + throws InvalidKeyException, InvalidAlgorithmParameterException { // ECDH doesn't need an AlgorithmParameterSpec if (params != null) { - throw new InvalidAlgorithmParameterException("No algorithm parameters supported"); + throw new InvalidAlgorithmParameterException("No algorithm parameters supported"); } engineInit(key, random); } diff --git a/common/src/main/java/org/conscrypt/OpenSSLCipher.java b/common/src/main/java/org/conscrypt/OpenSSLCipher.java index 8afef92da..155d757bf 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLCipher.java +++ b/common/src/main/java/org/conscrypt/OpenSSLCipher.java @@ -47,7 +47,6 @@ */ @Internal public abstract class OpenSSLCipher extends CipherSpi { - /** * Modes that a block cipher may support. */ @@ -124,8 +123,7 @@ public static Padding getNormalized(String value) { */ private int blockSize; - OpenSSLCipher() { - } + OpenSSLCipher() {} OpenSSLCipher(Mode mode, Padding padding) { this.mode = mode; @@ -140,7 +138,8 @@ public static Padding getNormalized(String value) { * the bytes of a supported key size. */ abstract void engineInitInternal(byte[] encodedKey, AlgorithmParameterSpec params, - SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException; + SecureRandom random) + throws InvalidKeyException, InvalidAlgorithmParameterException; /** * API-specific implementation of updating the cipher. The @@ -149,8 +148,8 @@ abstract void engineInitInternal(byte[] encodedKey, AlgorithmParameterSpec param * number of bytes processed and placed into {@code output}. On error, an * exception must be thrown. */ - abstract int updateInternal(byte[] input, int inputOffset, int inputLen, - byte[] output, int outputOffset, int maximumLen) throws ShortBufferException; + abstract int updateInternal(byte[] input, int inputOffset, int inputLen, byte[] output, + int outputOffset, int maximumLen) throws ShortBufferException; /** * Returns the standard name for the particular algorithm. @@ -191,7 +190,8 @@ protected void engineSetMode(String modeStr) throws NoSuchAlgorithmException { try { mode = Mode.getNormalized(modeStr); } catch (IllegalArgumentException e) { - NoSuchAlgorithmException newE = new NoSuchAlgorithmException("No such mode: " + modeStr); + NoSuchAlgorithmException newE = + new NoSuchAlgorithmException("No such mode: " + modeStr); newE.initCause(e); throw newE; } @@ -205,8 +205,8 @@ protected void engineSetPadding(String paddingStr) throws NoSuchPaddingException try { padding = Padding.getNormalized(paddingStr); } catch (IllegalArgumentException e) { - NoSuchPaddingException newE = new NoSuchPaddingException("No such padding: " - + paddingStr); + NoSuchPaddingException newE = + new NoSuchPaddingException("No such padding: " + paddingStr); newE.initCause(e); throw newE; } @@ -292,7 +292,8 @@ protected void engineInit(int opmode, Key key, SecureRandom random) throws Inval @Override protected void engineInit(int opmode, Key key, AlgorithmParameterSpec params, - SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { + SecureRandom random) + throws InvalidKeyException, InvalidAlgorithmParameterException { checkAndSetEncodedKey(opmode, key); engineInitInternal(this.encodedKey, params, random); } @@ -335,7 +336,7 @@ protected byte[] engineUpdate(byte[] input, int inputOffset, int inputLen) { @Override protected int engineUpdate(byte[] input, int inputOffset, int inputLen, byte[] output, - int outputOffset) throws ShortBufferException { + int outputOffset) throws ShortBufferException { final int maximumLen = getOutputSizeForUpdate(inputLen); return updateInternal(input, inputOffset, inputLen, output, outputOffset, maximumLen); } @@ -416,5 +417,4 @@ private byte[] checkAndSetEncodedKey(int opmode, Key key) throws InvalidKeyExcep boolean isEncrypting() { return encrypting; } - } diff --git a/common/src/main/java/org/conscrypt/OpenSSLCipherChaCha20.java b/common/src/main/java/org/conscrypt/OpenSSLCipherChaCha20.java index ef542fbbe..6d14d145f 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLCipherChaCha20.java +++ b/common/src/main/java/org/conscrypt/OpenSSLCipherChaCha20.java @@ -34,7 +34,6 @@ */ @Internal public class OpenSSLCipherChaCha20 extends OpenSSLCipher { - private static final int BLOCK_SIZE_BYTES = 64; private static final int NONCE_SIZE_BYTES = 12; @@ -71,7 +70,7 @@ void engineInitInternal(byte[] encodedKey, AlgorithmParameterSpec params, Secure @Override int updateInternal(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset, - int maximumLen) throws ShortBufferException { + int maximumLen) throws ShortBufferException { if (inputLen > output.length - outputOffset) { throw new ShortBufferWithoutStackTraceException("Insufficient output space"); } @@ -84,7 +83,7 @@ int updateInternal(byte[] input, int inputOffset, int inputLen, byte[] output, i byte[] singleBlockOut = new byte[BLOCK_SIZE_BYTES]; System.arraycopy(input, inputOffset, singleBlock, currentBlockConsumedBytes, len); NativeCrypto.chacha20_encrypt_decrypt(singleBlock, 0, singleBlockOut, 0, - BLOCK_SIZE_BYTES, encodedKey, iv, blockCounter); + BLOCK_SIZE_BYTES, encodedKey, iv, blockCounter); System.arraycopy(singleBlockOut, currentBlockConsumedBytes, output, outputOffset, len); currentBlockConsumedBytes += len; if (currentBlockConsumedBytes < BLOCK_SIZE_BYTES) { @@ -97,8 +96,8 @@ int updateInternal(byte[] input, int inputOffset, int inputLen, byte[] output, i inputLenRemaining -= len; blockCounter++; } - NativeCrypto.chacha20_encrypt_decrypt(input, inputOffset, output, - outputOffset, inputLenRemaining, encodedKey, iv, blockCounter); + NativeCrypto.chacha20_encrypt_decrypt(input, inputOffset, output, outputOffset, + inputLenRemaining, encodedKey, iv, blockCounter); currentBlockConsumedBytes = inputLenRemaining % BLOCK_SIZE_BYTES; blockCounter += inputLenRemaining / BLOCK_SIZE_BYTES; return inputLen; @@ -136,8 +135,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"); } @@ -146,8 +145,8 @@ protected int engineDoFinal(byte[] input, int inputOffset, int inputLen, byte[] final int bytesWritten; if (inputLen > 0) { - bytesWritten = updateInternal(input, inputOffset, inputLen, output, outputOffset, - maximumLen); + bytesWritten = + updateInternal(input, inputOffset, inputLen, output, outputOffset, maximumLen); outputOffset += bytesWritten; maximumLen -= bytesWritten; } else { @@ -173,7 +172,7 @@ String getBaseCipherName() { void checkSupportedKeySize(int keySize) throws InvalidKeyException { if (keySize != 32) { throw new InvalidKeyException("Unsupported key size: " + keySize - + " bytes (must be 32)"); + + " bytes (must be 32)"); } } @@ -205,5 +204,4 @@ int getOutputSizeForFinal(int inputLen) { int getOutputSizeForUpdate(int inputLen) { return inputLen; } - } diff --git a/common/src/main/java/org/conscrypt/OpenSSLCipherRSA.java b/common/src/main/java/org/conscrypt/OpenSSLCipherRSA.java index 19b387600..6d01e31fa 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLCipherRSA.java +++ b/common/src/main/java/org/conscrypt/OpenSSLCipherRSA.java @@ -135,8 +135,8 @@ protected int engineGetOutputSize(int inputLen) { int paddedBlockSizeBytes() { int paddedBlockSizeBytes = keySizeBytes(); if (padding == NativeConstants.RSA_PKCS1_PADDING) { - paddedBlockSizeBytes--; // for 0 prefix - paddedBlockSizeBytes -= 10; // PKCS1 padding header length + paddedBlockSizeBytes--; // for 0 prefix + paddedBlockSizeBytes -= 10; // PKCS1 padding header length } return paddedBlockSizeBytes; } @@ -166,7 +166,7 @@ protected AlgorithmParameters engineGetParameters() { } void doCryptoInit(AlgorithmParameterSpec spec) - throws InvalidAlgorithmParameterException, InvalidKeyException {} + throws InvalidAlgorithmParameterException, InvalidKeyException {} void engineInitInternal(int opmode, Key key, AlgorithmParameterSpec spec) throws InvalidKeyException, InvalidAlgorithmParameterException { @@ -247,10 +247,11 @@ protected void engineInit(int opmode, Key key, SecureRandom random) throws Inval @Override protected void engineInit(int opmode, Key key, AlgorithmParameterSpec params, - SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { + SecureRandom random) + throws InvalidKeyException, InvalidAlgorithmParameterException { if (params != null) { throw new InvalidAlgorithmParameterException("unknown param type: " - + params.getClass().getName()); + + params.getClass().getName()); } engineInitInternal(opmode, key, params); @@ -261,7 +262,7 @@ protected void engineInit(int opmode, Key key, AlgorithmParameters params, Secur throws InvalidKeyException, InvalidAlgorithmParameterException { if (params != null) { throw new InvalidAlgorithmParameterException("unknown param type: " - + params.getClass().getName()); + + params.getClass().getName()); } engineInitInternal(opmode, key, null); @@ -281,7 +282,7 @@ protected byte[] engineUpdate(byte[] input, int inputOffset, int inputLen) { @Override protected int engineUpdate(byte[] input, int inputOffset, int inputLen, byte[] output, - int outputOffset) throws ShortBufferException { + int outputOffset) throws ShortBufferException { engineUpdate(input, inputOffset, inputLen); return 0; } @@ -324,14 +325,14 @@ abstract int doCryptoOperation(final byte[] tmpBuf, byte[] output) @Override protected int engineDoFinal(byte[] input, int inputOffset, int inputLen, byte[] output, - int outputOffset) throws ShortBufferException, IllegalBlockSizeException, - BadPaddingException { + int outputOffset) + throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { byte[] b = engineDoFinal(input, inputOffset, inputLen); final int lastOffset = outputOffset + b.length; if (lastOffset > output.length) { - throw new ShortBufferWithoutStackTraceException("output buffer is too small " + output.length + " < " - + lastOffset); + throw new ShortBufferWithoutStackTraceException("output buffer is too small " + + output.length + " < " + lastOffset); } System.arraycopy(b, 0, output, outputOffset, b.length); @@ -351,8 +352,8 @@ protected byte[] engineWrap(Key key) throws IllegalBlockSizeException, InvalidKe } @Override - protected Key engineUnwrap(byte[] wrappedKey, String wrappedKeyAlgorithm, - int wrappedKeyType) throws InvalidKeyException, NoSuchAlgorithmException { + protected Key engineUnwrap(byte[] wrappedKey, String wrappedKeyAlgorithm, int wrappedKeyType) + throws InvalidKeyException, NoSuchAlgorithmException { try { byte[] encoded = engineDoFinal(wrappedKey, 0, wrappedKey.length); if (wrappedKeyType == Cipher.PUBLIC_KEY) { @@ -386,20 +387,20 @@ int doCryptoOperation(final byte[] tmpBuf, byte[] output) int resultSize; if (encrypting) { if (usingPrivateKey) { - resultSize = NativeCrypto.RSA_private_encrypt( - tmpBuf.length, tmpBuf, output, key.getNativeRef(), padding); + resultSize = NativeCrypto.RSA_private_encrypt(tmpBuf.length, tmpBuf, output, + key.getNativeRef(), padding); } else { - resultSize = NativeCrypto.RSA_public_encrypt( - tmpBuf.length, tmpBuf, output, key.getNativeRef(), padding); + resultSize = NativeCrypto.RSA_public_encrypt(tmpBuf.length, tmpBuf, output, + key.getNativeRef(), padding); } } else { try { if (usingPrivateKey) { - resultSize = NativeCrypto.RSA_private_decrypt( - tmpBuf.length, tmpBuf, output, key.getNativeRef(), padding); + resultSize = NativeCrypto.RSA_private_decrypt(tmpBuf.length, tmpBuf, output, + key.getNativeRef(), padding); } else { - resultSize = NativeCrypto.RSA_public_decrypt( - tmpBuf.length, tmpBuf, output, key.getNativeRef(), padding); + resultSize = NativeCrypto.RSA_public_decrypt(tmpBuf.length, tmpBuf, output, + key.getNativeRef(), padding); } } catch (SignatureException e) { IllegalBlockSizeException newE = new IllegalBlockSizeException(); @@ -464,7 +465,7 @@ protected AlgorithmParameters engineGetParameters() { return params; } catch (NoSuchAlgorithmException e) { // We should not get here. - throw (Error) new AssertionError("OAEP not supported").initCause(e); + throw(Error) new AssertionError("OAEP not supported").initCause(e); } catch (InvalidParameterSpecException e) { throw new RuntimeException("No providers of AlgorithmParameters.OAEP available"); } @@ -482,8 +483,8 @@ protected void engineSetPadding(String padding) throws NoSuchPaddingException { } @Override - protected void engineInit( - int opmode, Key key, AlgorithmParameterSpec spec, SecureRandom random) + protected void engineInit(int opmode, Key key, AlgorithmParameterSpec spec, + SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { if (spec != null && !(spec instanceof OAEPParameterSpec)) { throw new InvalidAlgorithmParameterException( @@ -494,8 +495,8 @@ protected void engineInit( } @Override - protected void engineInit( - int opmode, Key key, AlgorithmParameters params, SecureRandom random) + protected void engineInit(int opmode, Key key, AlgorithmParameters params, + SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { OAEPParameterSpec spec = null; if (params != null) { @@ -527,17 +528,17 @@ void engineInitInternal(int opmode, Key key, AlgorithmParameterSpec spec) @Override void doCryptoInit(AlgorithmParameterSpec spec) - throws InvalidAlgorithmParameterException, InvalidKeyException { - pkeyCtx = new NativeRef.EVP_PKEY_CTX(encrypting - ? NativeCrypto.EVP_PKEY_encrypt_init(key.getNativeRef()) - : NativeCrypto.EVP_PKEY_decrypt_init(key.getNativeRef())); + throws InvalidAlgorithmParameterException, InvalidKeyException { + pkeyCtx = new NativeRef.EVP_PKEY_CTX( + encrypting ? NativeCrypto.EVP_PKEY_encrypt_init(key.getNativeRef()) + : NativeCrypto.EVP_PKEY_decrypt_init(key.getNativeRef())); if (spec instanceof OAEPParameterSpec) { readOAEPParameters((OAEPParameterSpec) spec); } - NativeCrypto.EVP_PKEY_CTX_set_rsa_padding( - pkeyCtx.address, NativeConstants.RSA_PKCS1_OAEP_PADDING); + NativeCrypto.EVP_PKEY_CTX_set_rsa_padding(pkeyCtx.address, + NativeConstants.RSA_PKCS1_OAEP_PADDING); NativeCrypto.EVP_PKEY_CTX_set_rsa_oaep_md(pkeyCtx.address, oaepMd); NativeCrypto.EVP_PKEY_CTX_set_rsa_mgf1_md(pkeyCtx.address, mgf1Md); if (label != null && label.length > 0) { @@ -559,8 +560,8 @@ private void readOAEPParameters(OAEPParameterSpec spec) String mgfAlgUpper = spec.getMGFAlgorithm().toUpperCase(Locale.US); AlgorithmParameterSpec mgfSpec = spec.getMGFParameters(); if ((!EvpMdRef.MGF1_ALGORITHM_NAME.equals(mgfAlgUpper) - && !EvpMdRef.MGF1_OID.equals(mgfAlgUpper)) - || !(mgfSpec instanceof MGF1ParameterSpec)) { + && !EvpMdRef.MGF1_OID.equals(mgfAlgUpper)) + || !(mgfSpec instanceof MGF1ParameterSpec)) { throw new InvalidAlgorithmParameterException( "Only MGF1 supported as mask generation function"); } @@ -579,7 +580,7 @@ private void readOAEPParameters(OAEPParameterSpec spec) PSource pSource = spec.getPSource(); if (!"PSpecified".equals(pSource.getAlgorithm()) - || !(pSource instanceof PSource.PSpecified)) { + || !(pSource instanceof PSource.PSpecified)) { throw new InvalidAlgorithmParameterException( "Only PSpecified accepted for PSource"); } diff --git a/common/src/main/java/org/conscrypt/OpenSSLContextImpl.java b/common/src/main/java/org/conscrypt/OpenSSLContextImpl.java index 802506603..2b564e7ad 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLContextImpl.java +++ b/common/src/main/java/org/conscrypt/OpenSSLContextImpl.java @@ -92,9 +92,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 +112,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/OpenSSLECDHKeyAgreement.java b/common/src/main/java/org/conscrypt/OpenSSLECDHKeyAgreement.java index 614f20ee1..f7f029466 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLECDHKeyAgreement.java +++ b/common/src/main/java/org/conscrypt/OpenSSLECDHKeyAgreement.java @@ -25,8 +25,7 @@ */ @Internal public final class OpenSSLECDHKeyAgreement extends OpenSSLBaseDHKeyAgreement { - public OpenSSLECDHKeyAgreement() { - } + public OpenSSLECDHKeyAgreement() {} @Override protected OpenSSLKey convertPublicKey(PublicKey key) throws InvalidKeyException { @@ -39,18 +38,16 @@ protected OpenSSLKey convertPrivateKey(PrivateKey key) throws InvalidKeyExceptio } @Override - protected int computeKey(byte[] buffer, OpenSSLKey theirPublicKey, OpenSSLKey ourPrivateKey) throws InvalidKeyException { - return NativeCrypto.ECDH_compute_key( - buffer, - 0, - theirPublicKey.getNativeRef(), - ourPrivateKey.getNativeRef()); + protected int computeKey(byte[] buffer, OpenSSLKey theirPublicKey, OpenSSLKey ourPrivateKey) + throws InvalidKeyException { + return NativeCrypto.ECDH_compute_key(buffer, 0, theirPublicKey.getNativeRef(), + ourPrivateKey.getNativeRef()); } @Override protected int getOutputSize(OpenSSLKey openSslKey) { - int fieldSizeBits = NativeCrypto.EC_GROUP_get_degree(new NativeRef.EC_GROUP( - NativeCrypto.EC_KEY_get1_group(openSslKey.getNativeRef()))); + int fieldSizeBits = NativeCrypto.EC_GROUP_get_degree( + new NativeRef.EC_GROUP(NativeCrypto.EC_KEY_get1_group(openSslKey.getNativeRef()))); return (fieldSizeBits + 7) / 8; } } diff --git a/common/src/main/java/org/conscrypt/OpenSSLECGroupContext.java b/common/src/main/java/org/conscrypt/OpenSSLECGroupContext.java index 21596161f..eed2b4f64 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLECGroupContext.java +++ b/common/src/main/java/org/conscrypt/OpenSSLECGroupContext.java @@ -95,7 +95,7 @@ static OpenSSLECGroupContext getInstance(ECParameterSpec params) p = ((ECFieldFp) field).getP(); } else { throw new InvalidParameterException("unhandled field class " - + field.getClass().getName()); + + field.getClass().getName()); } final ECPoint generator = params.getGenerator(); @@ -107,34 +107,54 @@ static OpenSSLECGroupContext getInstance(ECParameterSpec params) // whether users would set it to -3 or p-3. switch (p.bitLength()) { case 224: - if (p.toString(16).equals("ffffffffffffffffffffffffffffffff000000000000000000000001") && - b.toString(16).equals("b4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4") && - x.toString(16).equals("b70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21") && - y.toString(16).equals("bd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34")) { + if (p.toString(16).equals( + "ffffffffffffffffffffffffffffffff000000000000000000000001") + && b.toString(16).equals( + "b4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4") + && x.toString(16).equals( + "b70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21") + && y.toString(16).equals( + "bd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34")) { curveName = "secp224r1"; } break; case 256: - if (p.toString(16).equals("ffffffff00000001000000000000000000000000ffffffffffffffffffffffff") && - b.toString(16).equals("5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b") && - x.toString(16).equals("6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296") && - y.toString(16).equals("4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")) { + if (p.toString(16).equals( + "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff") + && b.toString(16).equals( + "5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b") + && x.toString(16).equals( + "6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296") + && y.toString(16).equals( + "4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")) { curveName = "prime256v1"; } break; case 384: - if (p.toString(16).equals("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff") && - b.toString(16).equals("b3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef") && - x.toString(16).equals("aa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7") && - y.toString(16).equals("3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")) { + if (p.toString(16).equals("ffffffffffffffffffffffffffffffffffffffffffffffffffffffff" + + "fffffffeffffffff0000000000000000ffffffff") + && b.toString(16).equals("b3312fa7e23ee7e4988e056be3f82d19181d9c6efe81411203140" + + "88f5013875ac656398d8a2ed19d2a85c8edd3ec2aef") + && x.toString(16).equals("aa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f74" + + "1e082542a385502f25dbf55296c3a545e3872760ab7") + && y.toString(16).equals("3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3" + + "113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")) { curveName = "secp384r1"; } break; case 521: - if (p.toString(16).equals("1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff") && - b.toString(16).equals("51953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00") && - x.toString(16).equals("c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66") && - y.toString(16).equals("11839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")) { + if (p.toString(16).equals( + "1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" + + "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff") + && b.toString(16).equals( + "51953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e15619" + + "3951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00") + && x.toString(16).equals( + "c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b" + + "5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66") + && y.toString(16).equals( + "11839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97e" + + "e72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")) { curveName = "secp521r1"; } break; @@ -151,8 +171,8 @@ static OpenSSLECGroupContext getInstance(ECParameterSpec params) long group; try { group = NativeCrypto.EC_GROUP_new_arbitrary( - p.toByteArray(), a.toByteArray(), b.toByteArray(), x.toByteArray(), - y.toByteArray(), order.toByteArray(), cofactor); + p.toByteArray(), a.toByteArray(), b.toByteArray(), x.toByteArray(), + y.toByteArray(), order.toByteArray(), cofactor); } catch (Throwable exception) { throw new InvalidAlgorithmParameterException("EC_GROUP_new_arbitrary failed", exception); @@ -183,8 +203,8 @@ ECParameterSpec getECParameterSpec() { final EllipticCurve curve = new EllipticCurve(field, a, b); - final OpenSSLECPointContext generatorCtx = new OpenSSLECPointContext(this, - new NativeRef.EC_POINT(NativeCrypto.EC_GROUP_get_generator(groupCtx))); + final OpenSSLECPointContext generatorCtx = new OpenSSLECPointContext( + this, new NativeRef.EC_POINT(NativeCrypto.EC_GROUP_get_generator(groupCtx))); final ECPoint generator = generatorCtx.getECPoint(); final BigInteger order = new BigInteger(NativeCrypto.EC_GROUP_get_order(groupCtx)); diff --git a/common/src/main/java/org/conscrypt/OpenSSLECKeyFactory.java b/common/src/main/java/org/conscrypt/OpenSSLECKeyFactory.java index 596e8711d..5dbd9a088 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLECKeyFactory.java +++ b/common/src/main/java/org/conscrypt/OpenSSLECKeyFactory.java @@ -38,7 +38,6 @@ */ @Internal public final class OpenSSLECKeyFactory extends KeyFactorySpi { - public OpenSSLECKeyFactory() {} @Override @@ -50,10 +49,11 @@ protected PublicKey engineGeneratePublic(KeySpec keySpec) throws InvalidKeySpecE if (keySpec instanceof ECPublicKeySpec) { return new OpenSSLECPublicKey((ECPublicKeySpec) keySpec); } else if (keySpec instanceof X509EncodedKeySpec) { - return OpenSSLKey.getPublicKey((X509EncodedKeySpec) keySpec, NativeConstants.EVP_PKEY_EC); + return OpenSSLKey.getPublicKey((X509EncodedKeySpec) keySpec, + NativeConstants.EVP_PKEY_EC); } throw new InvalidKeySpecException("Must use ECPublicKeySpec or X509EncodedKeySpec; was " - + keySpec.getClass().getName()); + + keySpec.getClass().getName()); } @Override @@ -66,10 +66,10 @@ protected PrivateKey engineGeneratePrivate(KeySpec keySpec) throws InvalidKeySpe return new OpenSSLECPrivateKey((ECPrivateKeySpec) keySpec); } else if (keySpec instanceof PKCS8EncodedKeySpec) { return OpenSSLKey.getPrivateKey((PKCS8EncodedKeySpec) keySpec, - NativeConstants.EVP_PKEY_EC); + NativeConstants.EVP_PKEY_EC); } throw new InvalidKeySpecException("Must use ECPrivateKeySpec or PKCS8EncodedKeySpec; was " - + keySpec.getClass().getName()); + + keySpec.getClass().getName()); } @Override @@ -102,7 +102,7 @@ protected T engineGetKeySpec(Key key, Class keySpec) T result = (T) new ECPublicKeySpec(ecKey.getW(), ecKey.getParams()); return result; } else if (key instanceof ECPrivateKey - && ECPrivateKeySpec.class.isAssignableFrom(keySpec)) { + && ECPrivateKeySpec.class.isAssignableFrom(keySpec)) { ECPrivateKey ecKey = (ECPrivateKey) key; @SuppressWarnings("unchecked") T result = (T) new ECPrivateKeySpec(ecKey.getS(), ecKey.getParams()); @@ -118,11 +118,11 @@ protected T engineGetKeySpec(Key key, Class keySpec) T result = (T) new ECPrivateKeySpec(ecKey.getS(), ecKey.getParams()); return result; } else if (key instanceof PrivateKey - && PKCS8EncodedKeySpec.class.isAssignableFrom(keySpec)) { + && PKCS8EncodedKeySpec.class.isAssignableFrom(keySpec)) { final byte[] encoded = key.getEncoded(); if (!"PKCS#8".equals(key.getFormat())) { throw new InvalidKeySpecException("Encoding type must be PKCS#8; was " - + key.getFormat()); + + key.getFormat()); } else if (encoded == null) { throw new InvalidKeySpecException("Key is not encodable"); } @@ -132,7 +132,7 @@ protected T engineGetKeySpec(Key key, Class keySpec) final byte[] encoded = key.getEncoded(); if (!"X.509".equals(key.getFormat())) { throw new InvalidKeySpecException("Encoding type must be X.509; was " - + key.getFormat()); + + key.getFormat()); } else if (encoded == null) { throw new InvalidKeySpecException("Key is not encodable"); } @@ -140,7 +140,8 @@ protected T engineGetKeySpec(Key key, Class keySpec) return result; } else { throw new InvalidKeySpecException("Unsupported key type and key spec combination; key=" - + key.getClass().getName() + ", keySpec=" + keySpec.getName()); + + key.getClass().getName() + + ", keySpec=" + keySpec.getName()); } } @@ -197,7 +198,7 @@ protected Key engineTranslateKey(Key key) throws InvalidKeyException { } } else { throw new InvalidKeyException("Key must be EC public or private key; was " - + key.getClass().getName()); + + key.getClass().getName()); } } } diff --git a/common/src/main/java/org/conscrypt/OpenSSLECKeyPairGenerator.java b/common/src/main/java/org/conscrypt/OpenSSLECKeyPairGenerator.java index df127ac36..b157131ba 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLECKeyPairGenerator.java +++ b/common/src/main/java/org/conscrypt/OpenSSLECKeyPairGenerator.java @@ -65,8 +65,8 @@ public KeyPair generateKeyPair() { } } - final OpenSSLKey key = new OpenSSLKey( - NativeCrypto.EC_KEY_generate_key(group.getNativeRef())); + final OpenSSLKey key = + new OpenSSLKey(NativeCrypto.EC_KEY_generate_key(group.getNativeRef())); return new KeyPair(new OpenSSLECPublicKey(group, key), new OpenSSLECPrivateKey(group, key)); } @@ -105,8 +105,8 @@ public void initialize(AlgorithmParameterSpec param, SecureRandom random) * Store the group in a temporary variable until we know this is a * valid group. */ - final OpenSSLECGroupContext possibleGroup = OpenSSLECGroupContext - .getCurveByName(curveName); + final OpenSSLECGroupContext possibleGroup = + OpenSSLECGroupContext.getCurveByName(curveName); if (possibleGroup == null) { throw new InvalidAlgorithmParameterException("unknown curve name: " + curveName); } @@ -128,7 +128,7 @@ public static void assertCurvesAreValid() { } if (invalidCurves.size() > 0) { throw new AssertionError("Invalid curve names: " - + Arrays.toString(invalidCurves.toArray())); + + Arrays.toString(invalidCurves.toArray())); } } } diff --git a/common/src/main/java/org/conscrypt/OpenSSLECPointContext.java b/common/src/main/java/org/conscrypt/OpenSSLECPointContext.java index 95be03be1..8358d386f 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLECPointContext.java +++ b/common/src/main/java/org/conscrypt/OpenSSLECPointContext.java @@ -34,8 +34,8 @@ public boolean equals(Object o) { } ECPoint getECPoint() { - final byte[][] generatorCoords = NativeCrypto.EC_POINT_get_affine_coordinates( - group.getNativeRef(), pointCtx); + final byte[][] generatorCoords = + NativeCrypto.EC_POINT_get_affine_coordinates(group.getNativeRef(), pointCtx); final BigInteger x = new BigInteger(generatorCoords[0]); final BigInteger y = new BigInteger(generatorCoords[1]); return new ECPoint(x, y); @@ -51,13 +51,12 @@ NativeRef.EC_POINT getNativeRef() { return pointCtx; } - static OpenSSLECPointContext getInstance(OpenSSLECGroupContext group, - ECPoint javaPoint) { - OpenSSLECPointContext point = new OpenSSLECPointContext(group, new NativeRef.EC_POINT( - NativeCrypto.EC_POINT_new(group.getNativeRef()))); - NativeCrypto.EC_POINT_set_affine_coordinates(group.getNativeRef(), - point.getNativeRef(), javaPoint.getAffineX().toByteArray(), - javaPoint.getAffineY().toByteArray()); + static OpenSSLECPointContext getInstance(OpenSSLECGroupContext group, ECPoint javaPoint) { + OpenSSLECPointContext point = new OpenSSLECPointContext( + group, new NativeRef.EC_POINT(NativeCrypto.EC_POINT_new(group.getNativeRef()))); + NativeCrypto.EC_POINT_set_affine_coordinates(group.getNativeRef(), point.getNativeRef(), + javaPoint.getAffineX().toByteArray(), + javaPoint.getAffineY().toByteArray()); return point; } } diff --git a/common/src/main/java/org/conscrypt/OpenSSLECPrivateKey.java b/common/src/main/java/org/conscrypt/OpenSSLECPrivateKey.java index 9af2b1371..d1ecf42f7 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLECPrivateKey.java +++ b/common/src/main/java/org/conscrypt/OpenSSLECPrivateKey.java @@ -16,6 +16,8 @@ package org.conscrypt; +import org.conscrypt.OpenSSLX509CertificateFactory.ParsingException; + import java.io.IOException; import java.io.NotSerializableException; import java.io.ObjectInputStream; @@ -31,7 +33,6 @@ import java.security.spec.ECPrivateKeySpec; import java.security.spec.InvalidKeySpecException; import java.util.Arrays; -import org.conscrypt.OpenSSLX509CertificateFactory.ParsingException; /** * An implementation of a {@link PrivateKey} for EC keys based on BoringSSL. @@ -51,8 +52,8 @@ final class OpenSSLECPrivateKey implements ECPrivateKey, OpenSSLKeyHolder { } OpenSSLECPrivateKey(OpenSSLKey key) { - this.group = new OpenSSLECGroupContext(new NativeRef.EC_GROUP( - NativeCrypto.EC_KEY_get1_group(key.getNativeRef()))); + this.group = new OpenSSLECGroupContext( + new NativeRef.EC_GROUP(NativeCrypto.EC_KEY_get1_group(key.getNativeRef()))); this.key = key; } @@ -61,7 +62,7 @@ final class OpenSSLECPrivateKey implements ECPrivateKey, OpenSSLKeyHolder { group = OpenSSLECGroupContext.getInstance(ecKeySpec.getParams()); final BigInteger privKey = ecKeySpec.getS(); key = new OpenSSLKey(NativeCrypto.EVP_PKEY_new_EC_KEY(group.getNativeRef(), null, - privKey.toByteArray())); + privKey.toByteArray())); } catch (Exception e) { throw new InvalidKeySpecException(e); } @@ -82,8 +83,8 @@ static OpenSSLKey wrapPlatformKey(ECPrivateKey ecPrivateKey) throws InvalidKeyEx * using the key will be delegated to the {@code Signature}/{@code Cipher} implementation of the * provider which accepts the key. */ - static OpenSSLKey wrapJCAPrivateKeyForTLSStackOnly(PrivateKey privateKey, - PublicKey publicKey) throws InvalidKeyException { + static OpenSSLKey wrapJCAPrivateKeyForTLSStackOnly(PrivateKey privateKey, PublicKey publicKey) + throws InvalidKeyException { ECParameterSpec params = null; if (privateKey instanceof ECKey) { params = ((ECKey) privateKey).getParams(); @@ -92,7 +93,7 @@ static OpenSSLKey wrapJCAPrivateKeyForTLSStackOnly(PrivateKey privateKey, } if (params == null) { throw new InvalidKeyException("EC parameters not available. Private: " + privateKey - + ", public: " + publicKey); + + ", public: " + publicKey); } return wrapJCAPrivateKeyForTLSStackOnly(privateKey, params); } @@ -103,7 +104,8 @@ static OpenSSLKey wrapJCAPrivateKeyForTLSStackOnly(PrivateKey privateKey, * provider which accepts the key. */ static OpenSSLKey wrapJCAPrivateKeyForTLSStackOnly(PrivateKey privateKey, - ECParameterSpec params) throws InvalidKeyException { + ECParameterSpec params) + throws InvalidKeyException { if (params == null) { if (privateKey instanceof ECKey) { params = ((ECKey) privateKey).getParams(); @@ -120,20 +122,21 @@ static OpenSSLKey wrapJCAPrivateKeyForTLSStackOnly(PrivateKey privateKey, throw new InvalidKeyException("Invalid EC parameters: " + params); } - return new OpenSSLKey( - NativeCrypto.getECPrivateKeyWrapper(privateKey, group.getNativeRef()), true); + return new OpenSSLKey(NativeCrypto.getECPrivateKeyWrapper(privateKey, group.getNativeRef()), + true); } private static OpenSSLKey wrapPlatformKey(ECPrivateKey ecPrivateKey, - OpenSSLECGroupContext group) throws InvalidKeyException { - return new OpenSSLKey(NativeCrypto.getECPrivateKeyWrapper(ecPrivateKey, - group.getNativeRef()), true); + OpenSSLECGroupContext group) + throws InvalidKeyException { + return new OpenSSLKey( + NativeCrypto.getECPrivateKeyWrapper(ecPrivateKey, group.getNativeRef()), true); } static OpenSSLKey getInstance(ECPrivateKey ecPrivateKey) throws InvalidKeyException { try { - OpenSSLECGroupContext group = OpenSSLECGroupContext.getInstance(ecPrivateKey - .getParams()); + OpenSSLECGroupContext group = + OpenSSLECGroupContext.getInstance(ecPrivateKey.getParams()); /* * If the key is not encodable (PKCS11-like key), then wrap it and @@ -145,7 +148,7 @@ static OpenSSLKey getInstance(ECPrivateKey ecPrivateKey) throws InvalidKeyExcept final BigInteger privKey = ecPrivateKey.getS(); return new OpenSSLKey(NativeCrypto.EVP_PKEY_new_EC_KEY(group.getNativeRef(), null, - privKey.toByteArray())); + privKey.toByteArray())); } catch (Exception e) { throw new InvalidKeyException(e); } @@ -247,8 +250,8 @@ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFo } catch (ParsingException e) { throw new IOException(e); } - group = new OpenSSLECGroupContext(new NativeRef.EC_GROUP( - NativeCrypto.EC_KEY_get1_group(key.getNativeRef()))); + group = new OpenSSLECGroupContext( + new NativeRef.EC_GROUP(NativeCrypto.EC_KEY_get1_group(key.getNativeRef()))); } private void writeObject(ObjectOutputStream stream) throws IOException { diff --git a/common/src/main/java/org/conscrypt/OpenSSLECPublicKey.java b/common/src/main/java/org/conscrypt/OpenSSLECPublicKey.java index d68c465f1..77422fe3d 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLECPublicKey.java +++ b/common/src/main/java/org/conscrypt/OpenSSLECPublicKey.java @@ -16,6 +16,8 @@ package org.conscrypt; +import org.conscrypt.OpenSSLX509CertificateFactory.ParsingException; + import java.io.IOException; import java.io.NotSerializableException; import java.io.ObjectInputStream; @@ -27,7 +29,6 @@ import java.security.spec.ECPublicKeySpec; import java.security.spec.InvalidKeySpecException; import java.util.Arrays; -import org.conscrypt.OpenSSLX509CertificateFactory.ParsingException; /** * An implementation of a {@link java.security.PublicKey} for EC keys based on BoringSSL. @@ -47,18 +48,18 @@ final class OpenSSLECPublicKey implements ECPublicKey, OpenSSLKeyHolder { } OpenSSLECPublicKey(OpenSSLKey key) { - this.group = new OpenSSLECGroupContext(new NativeRef.EC_GROUP( - NativeCrypto.EC_KEY_get1_group(key.getNativeRef()))); + this.group = new OpenSSLECGroupContext( + new NativeRef.EC_GROUP(NativeCrypto.EC_KEY_get1_group(key.getNativeRef()))); this.key = key; } OpenSSLECPublicKey(ECPublicKeySpec ecKeySpec) throws InvalidKeySpecException { try { group = OpenSSLECGroupContext.getInstance(ecKeySpec.getParams()); - OpenSSLECPointContext pubKey = OpenSSLECPointContext.getInstance(group, - ecKeySpec.getW()); + OpenSSLECPointContext pubKey = + OpenSSLECPointContext.getInstance(group, ecKeySpec.getW()); key = new OpenSSLKey(NativeCrypto.EVP_PKEY_new_EC_KEY(group.getNativeRef(), - pubKey.getNativeRef(), null)); + pubKey.getNativeRef(), null)); } catch (Exception e) { throw new InvalidKeySpecException(e); } @@ -66,12 +67,12 @@ final class OpenSSLECPublicKey implements ECPublicKey, OpenSSLKeyHolder { static OpenSSLKey getInstance(ECPublicKey ecPublicKey) throws InvalidKeyException { try { - OpenSSLECGroupContext group = OpenSSLECGroupContext - .getInstance(ecPublicKey.getParams()); - OpenSSLECPointContext pubKey = OpenSSLECPointContext.getInstance(group, - ecPublicKey.getW()); + OpenSSLECGroupContext group = + OpenSSLECGroupContext.getInstance(ecPublicKey.getParams()); + OpenSSLECPointContext pubKey = + OpenSSLECPointContext.getInstance(group, ecPublicKey.getW()); return new OpenSSLKey(NativeCrypto.EVP_PKEY_new_EC_KEY(group.getNativeRef(), - pubKey.getNativeRef(), null)); + pubKey.getNativeRef(), null)); } catch (Exception e) { throw new InvalidKeyException(e); } @@ -98,7 +99,8 @@ public ECParameterSpec getParams() { } private ECPoint getPublicKey() { - final OpenSSLECPointContext pubKey = new OpenSSLECPointContext(group, + final OpenSSLECPointContext pubKey = new OpenSSLECPointContext( + group, new NativeRef.EC_POINT(NativeCrypto.EC_KEY_get_public_key(key.getNativeRef()))); return pubKey.getECPoint(); @@ -163,8 +165,8 @@ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFo } catch (ParsingException e) { throw new IOException(e); } - group = new OpenSSLECGroupContext(new NativeRef.EC_GROUP( - NativeCrypto.EC_KEY_get1_group(key.getNativeRef()))); + group = new OpenSSLECGroupContext( + new NativeRef.EC_GROUP(NativeCrypto.EC_KEY_get1_group(key.getNativeRef()))); } private void writeObject(ObjectOutputStream stream) throws IOException { diff --git a/common/src/main/java/org/conscrypt/OpenSSLEvpCipher.java b/common/src/main/java/org/conscrypt/OpenSSLEvpCipher.java index b53efe83b..ebbb624d6 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLEvpCipher.java +++ b/common/src/main/java/org/conscrypt/OpenSSLEvpCipher.java @@ -16,24 +16,25 @@ package org.conscrypt; +import org.conscrypt.NativeRef.EVP_CIPHER_CTX; + import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.SecureRandom; import java.security.spec.AlgorithmParameterSpec; import java.util.Arrays; + import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.ShortBufferException; import javax.crypto.spec.IvParameterSpec; -import org.conscrypt.NativeRef.EVP_CIPHER_CTX; @Internal public abstract class OpenSSLEvpCipher extends OpenSSLCipher { /** * Native pointer for the OpenSSL EVP_CIPHER context. */ - private final EVP_CIPHER_CTX cipherCtx = new EVP_CIPHER_CTX( - NativeCrypto.EVP_CIPHER_CTX_new()); + private final EVP_CIPHER_CTX cipherCtx = new EVP_CIPHER_CTX(NativeCrypto.EVP_CIPHER_CTX_new()); /** * Whether the cipher has processed any data yet. EVP_CIPHER doesn't @@ -52,9 +53,8 @@ protected OpenSSLEvpCipher(Mode mode, Padding padding) { } @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; if (params instanceof IvParameterSpec) { IvParameterSpec ivParams = (IvParameterSpec) params; @@ -63,11 +63,12 @@ void engineInitInternal(byte[] encodedKey, AlgorithmParameterSpec params, iv = null; } - final long cipherType = NativeCrypto.EVP_get_cipherbyname(getCipherName( - encodedKey.length, mode)); + final long cipherType = + NativeCrypto.EVP_get_cipherbyname(getCipherName(encodedKey.length, mode)); if (cipherType == 0) { throw new InvalidAlgorithmParameterException("Cannot find name for key length = " - + (encodedKey.length * 8) + " and mode = " + mode); + + (encodedKey.length * 8) + + " and mode = " + mode); } final boolean encrypting = isEncrypting(); @@ -76,7 +77,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]; @@ -88,8 +89,8 @@ 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); } this.iv = iv; @@ -103,25 +104,24 @@ void engineInitInternal(byte[] encodedKey, AlgorithmParameterSpec params, } // OpenSSL only supports PKCS5 Padding. - NativeCrypto - .EVP_CIPHER_CTX_set_padding(cipherCtx, getPadding() == Padding.PKCS5PADDING); + NativeCrypto.EVP_CIPHER_CTX_set_padding(cipherCtx, getPadding() == Padding.PKCS5PADDING); modeBlockSize = NativeCrypto.EVP_CIPHER_CTX_block_size(cipherCtx); calledUpdate = false; } @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 { final int intialOutputOffset = outputOffset; final int bytesLeft = output.length - outputOffset; if (bytesLeft < maximumLen) { - throw new ShortBufferWithoutStackTraceException("output buffer too small during update: " - + bytesLeft + " < " + maximumLen); + throw new ShortBufferWithoutStackTraceException( + "output buffer too small during update: " + bytesLeft + " < " + maximumLen); } outputOffset += NativeCrypto.EVP_CipherUpdate(cipherCtx, output, outputOffset, input, - inputOffset, inputLen); + inputOffset, inputLen); calledUpdate = true; @@ -150,8 +150,8 @@ int doFinalInternal(byte[] output, int outputOffset, int maximumLen) final byte[] lastBlock = new byte[maximumLen]; writtenBytes = NativeCrypto.EVP_CipherFinal_ex(cipherCtx, lastBlock, 0); if (writtenBytes > bytesLeft) { - throw new ShortBufferWithoutStackTraceException("buffer is too short: " + writtenBytes + " > " - + bytesLeft); + throw new ShortBufferWithoutStackTraceException( + "buffer is too short: " + writtenBytes + " > " + bytesLeft); } else if (writtenBytes > 0) { System.arraycopy(lastBlock, 0, output, outputOffset, writtenBytes); } @@ -200,8 +200,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"); } @@ -210,8 +210,8 @@ protected int engineDoFinal(byte[] input, int inputOffset, int inputLen, byte[] final int bytesWritten; if (inputLen > 0) { - bytesWritten = updateInternal(input, inputOffset, inputLen, output, outputOffset, - maximumLen); + bytesWritten = + updateInternal(input, inputOffset, inputLen, output, outputOffset, maximumLen); outputOffset += bytesWritten; maximumLen -= bytesWritten; } else { @@ -237,8 +237,7 @@ int getOutputSizeForFinal(int inputLen) { // Extra block for remainder bytes plus padding. // In case it's encrypting and there are no remainder bytes, add an extra block // consisting only of padding. - totalLen += ((totalLen % modeBlockSize != 0) || isEncrypting()) - ? modeBlockSize : 0; + totalLen += ((totalLen % modeBlockSize != 0) || isEncrypting()) ? modeBlockSize : 0; // The minimum multiple of {@code modeBlockSize} that can hold all the bytes. return totalLen - (totalLen % modeBlockSize); } @@ -263,5 +262,4 @@ private void reset() { NativeCrypto.EVP_CipherInit_ex(cipherCtx, 0, encodedKey, iv, isEncrypting()); calledUpdate = false; } - } diff --git a/common/src/main/java/org/conscrypt/OpenSSLEvpCipherAES.java b/common/src/main/java/org/conscrypt/OpenSSLEvpCipherAES.java index ceefd1a98..ccde84143 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLEvpCipherAES.java +++ b/common/src/main/java/org/conscrypt/OpenSSLEvpCipherAES.java @@ -49,8 +49,7 @@ void checkSupportedPadding(Padding padding) throws NoSuchPaddingException { case PKCS5PADDING: return; default: - throw new NoSuchPaddingException( - "Unsupported padding " + padding.toString()); + throw new NoSuchPaddingException("Unsupported padding " + padding.toString()); } } @@ -124,8 +123,7 @@ void checkSupportedKeySize(int keyLength) throws InvalidKeyException { case 32: // AES 256 return; default: - throw new InvalidKeyException("Unsupported key size: " + keyLength - + " bytes"); + throw new InvalidKeyException("Unsupported key size: " + keyLength + " bytes"); } } } diff --git a/common/src/main/java/org/conscrypt/OpenSSLEvpCipherARC4.java b/common/src/main/java/org/conscrypt/OpenSSLEvpCipherARC4.java index 272f698cd..befa6983a 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLEvpCipherARC4.java +++ b/common/src/main/java/org/conscrypt/OpenSSLEvpCipherARC4.java @@ -39,8 +39,7 @@ String getCipherName(int keySize, Mode mode) { } @Override - void checkSupportedKeySize(int keySize) throws InvalidKeyException { - } + void checkSupportedKeySize(int keySize) throws InvalidKeyException {} @Override void checkSupportedMode(Mode mode) throws NoSuchAlgorithmException { diff --git a/common/src/main/java/org/conscrypt/OpenSSLEvpCipherDESEDE.java b/common/src/main/java/org/conscrypt/OpenSSLEvpCipherDESEDE.java index 56d95c217..0a4ff63c3 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLEvpCipherDESEDE.java +++ b/common/src/main/java/org/conscrypt/OpenSSLEvpCipherDESEDE.java @@ -86,8 +86,7 @@ void checkSupportedPadding(Padding padding) throws NoSuchPaddingException { case PKCS5PADDING: return; default: - throw new NoSuchPaddingException("Unsupported padding " - + padding.toString()); + throw new NoSuchPaddingException("Unsupported padding " + padding.toString()); } } diff --git a/common/src/main/java/org/conscrypt/OpenSSLKey.java b/common/src/main/java/org/conscrypt/OpenSSLKey.java index 4249b8efe..04ed73b6c 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLKey.java +++ b/common/src/main/java/org/conscrypt/OpenSSLKey.java @@ -16,6 +16,8 @@ package org.conscrypt; +import org.conscrypt.OpenSSLX509CertificateFactory.ParsingException; + import java.io.InputStream; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; @@ -27,7 +29,6 @@ import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; -import org.conscrypt.OpenSSLX509CertificateFactory.ParsingException; /** * Represents a BoringSSL {@code EVP_PKEY}. @@ -105,8 +106,7 @@ static OpenSSLKey fromPrivateKey(PrivateKey key) throws InvalidKeyException { * * @throws InvalidKeyException if parsing fails */ - static OpenSSLKey fromPrivateKeyPemInputStream(InputStream is) - throws InvalidKeyException { + static OpenSSLKey fromPrivateKeyPemInputStream(InputStream is) throws InvalidKeyException { OpenSSLBIOInputStream bis = new OpenSSLBIOInputStream(is, true); try { long keyCtx = NativeCrypto.PEM_read_bio_PrivateKey(bis.getBioContext()); @@ -130,8 +130,8 @@ static OpenSSLKey fromPrivateKeyPemInputStream(InputStream is) * @param publicKey corresponding public key or {@code null} if not available. Some opaque * private keys cannot be used by the TLS/SSL stack without the public key. */ - static OpenSSLKey fromPrivateKeyForTLSStackOnly( - PrivateKey privateKey, PublicKey publicKey) throws InvalidKeyException { + static OpenSSLKey fromPrivateKeyForTLSStackOnly(PrivateKey privateKey, PublicKey publicKey) + throws InvalidKeyException { OpenSSLKey result = getOpenSSLKey(privateKey); if (result != null) { return result; @@ -154,8 +154,8 @@ static OpenSSLKey fromPrivateKeyForTLSStackOnly( * be used by the TLS/SSL stack without the parameters because the private key itself * might not expose the parameters. */ - static OpenSSLKey fromECPrivateKeyForTLSStackOnly( - PrivateKey key, ECParameterSpec ecParams) throws InvalidKeyException { + static OpenSSLKey fromECPrivateKeyForTLSStackOnly(PrivateKey key, ECParameterSpec ecParams) + throws InvalidKeyException { OpenSSLKey result = getOpenSSLKey(key); if (result != null) { return result; @@ -209,7 +209,8 @@ private static OpenSSLKey fromKeyMaterial(PrivateKey key) throws InvalidKeyExcep * provider which accepts the key. */ private static OpenSSLKey wrapJCAPrivateKeyForTLSStackOnly(PrivateKey privateKey, - PublicKey publicKey) throws InvalidKeyException { + PublicKey publicKey) + throws InvalidKeyException { String keyAlgorithm = privateKey.getAlgorithm(); if ("RSA".equals(keyAlgorithm)) { return OpenSSLRSAPrivateKey.wrapJCAPrivateKeyForTLSStackOnly(privateKey, publicKey); diff --git a/common/src/main/java/org/conscrypt/OpenSSLMac.java b/common/src/main/java/org/conscrypt/OpenSSLMac.java index b8f529632..351524725 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLMac.java +++ b/common/src/main/java/org/conscrypt/OpenSSLMac.java @@ -21,6 +21,7 @@ import java.security.InvalidKeyException; import java.security.Key; import java.security.spec.AlgorithmParameterSpec; + import javax.crypto.MacSpi; import javax.crypto.SecretKey; @@ -65,8 +66,8 @@ protected int engineGetMacLength() { } @Override - protected void engineInit(Key key, AlgorithmParameterSpec params) throws InvalidKeyException, - InvalidAlgorithmParameterException { + protected void engineInit(Key key, AlgorithmParameterSpec params) + throws InvalidKeyException, InvalidAlgorithmParameterException { if (!(key instanceof SecretKey)) { throw new InvalidKeyException("key must be a SecretKey"); } @@ -192,7 +193,6 @@ protected byte[] doFinal() { final NativeRef.HMAC_CTX ctxLocal = ctx; return NativeCrypto.HMAC_Final(ctxLocal); } - } public static final class HmacMD5 extends Hmac { diff --git a/common/src/main/java/org/conscrypt/OpenSSLMessageDigestJDK.java b/common/src/main/java/org/conscrypt/OpenSSLMessageDigestJDK.java index a45cde5de..1b744ed7d 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLMessageDigestJDK.java +++ b/common/src/main/java/org/conscrypt/OpenSSLMessageDigestJDK.java @@ -58,7 +58,7 @@ private OpenSSLMessageDigestJDK(long evp_md, int size) throws NoSuchAlgorithmExc } private OpenSSLMessageDigestJDK(long evp_md, int size, NativeRef.EVP_MD_CTX ctx, - boolean digestInitializedInContext) { + boolean digestInitializedInContext) { this.evp_md = evp_md; this.size = size; this.ctx = ctx; diff --git a/common/src/main/java/org/conscrypt/OpenSSLProvider.java b/common/src/main/java/org/conscrypt/OpenSSLProvider.java index e3a158073..a583db102 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,25 @@ public OpenSSLProvider(String providerName) { put("Alg.Alias.CertificateFactory.X.509", "X509"); /* === HPKE === */ - String baseClass = classExists("android.crypto.hpke.HpkeSpi") - ? PREFIX + "AndroidHpkeSpi" - : PREFIX + "HpkeImpl"; + String baseClass = classExists("android.crypto.hpke.HpkeSpi") ? PREFIX + "AndroidHpkeSpi" + : PREFIX + "HpkeImpl"; 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 +607,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 +616,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 +625,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 +642,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 +655,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 +671,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 +681,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/OpenSSLRSAKeyFactory.java b/common/src/main/java/org/conscrypt/OpenSSLRSAKeyFactory.java index ce08d50e7..ae13df590 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLRSAKeyFactory.java +++ b/common/src/main/java/org/conscrypt/OpenSSLRSAKeyFactory.java @@ -39,7 +39,6 @@ */ @Internal public final class OpenSSLRSAKeyFactory extends KeyFactorySpi { - @Override protected PublicKey engineGeneratePublic(KeySpec keySpec) throws InvalidKeySpecException { if (keySpec == null) { @@ -49,10 +48,11 @@ protected PublicKey engineGeneratePublic(KeySpec keySpec) throws InvalidKeySpecE if (keySpec instanceof RSAPublicKeySpec) { return new OpenSSLRSAPublicKey((RSAPublicKeySpec) keySpec); } else if (keySpec instanceof X509EncodedKeySpec) { - return OpenSSLKey.getPublicKey((X509EncodedKeySpec) keySpec, NativeConstants.EVP_PKEY_RSA); + return OpenSSLKey.getPublicKey((X509EncodedKeySpec) keySpec, + NativeConstants.EVP_PKEY_RSA); } throw new InvalidKeySpecException("Must use RSAPublicKeySpec or X509EncodedKeySpec; was " - + keySpec.getClass().getName()); + + keySpec.getClass().getName()); } @Override @@ -67,10 +67,10 @@ protected PrivateKey engineGeneratePrivate(KeySpec keySpec) throws InvalidKeySpe return new OpenSSLRSAPrivateKey((RSAPrivateKeySpec) keySpec); } else if (keySpec instanceof PKCS8EncodedKeySpec) { return OpenSSLKey.getPrivateKey((PKCS8EncodedKeySpec) keySpec, - NativeConstants.EVP_PKEY_RSA); + NativeConstants.EVP_PKEY_RSA); } throw new InvalidKeySpecException("Must use RSAPublicKeySpec or PKCS8EncodedKeySpec; was " - + keySpec.getClass().getName()); + + keySpec.getClass().getName()); } @Override @@ -104,28 +104,28 @@ protected T engineGetKeySpec(Key key, Class keySpec) T result = (T) new RSAPublicKeySpec(rsaKey.getModulus(), rsaKey.getPublicExponent()); return result; } else if (key instanceof RSAPrivateCrtKey - && RSAPrivateCrtKeySpec.class.isAssignableFrom(keySpec)) { + && RSAPrivateCrtKeySpec.class.isAssignableFrom(keySpec)) { RSAPrivateCrtKey rsaKey = (RSAPrivateCrtKey) key; @SuppressWarnings("unchecked") - T result = (T) new RSAPrivateCrtKeySpec(rsaKey.getModulus(), rsaKey.getPublicExponent(), - rsaKey.getPrivateExponent(), rsaKey.getPrimeP(), rsaKey.getPrimeQ(), - rsaKey.getPrimeExponentP(), rsaKey.getPrimeExponentQ(), - rsaKey.getCrtCoefficient()); + T result = (T) new RSAPrivateCrtKeySpec( + rsaKey.getModulus(), rsaKey.getPublicExponent(), rsaKey.getPrivateExponent(), + rsaKey.getPrimeP(), rsaKey.getPrimeQ(), rsaKey.getPrimeExponentP(), + rsaKey.getPrimeExponentQ(), rsaKey.getCrtCoefficient()); return result; } else if (key instanceof RSAPrivateCrtKey - && RSAPrivateKeySpec.class.isAssignableFrom(keySpec)) { + && RSAPrivateKeySpec.class.isAssignableFrom(keySpec)) { RSAPrivateCrtKey rsaKey = (RSAPrivateCrtKey) key; @SuppressWarnings("unchecked") T result = (T) new RSAPrivateKeySpec(rsaKey.getModulus(), rsaKey.getPrivateExponent()); return result; } else if (key instanceof RSAPrivateKey - && RSAPrivateKeySpec.class.isAssignableFrom(keySpec)) { + && RSAPrivateKeySpec.class.isAssignableFrom(keySpec)) { RSAPrivateKey rsaKey = (RSAPrivateKey) key; @SuppressWarnings("unchecked") T result = (T) new RSAPrivateKeySpec(rsaKey.getModulus(), rsaKey.getPrivateExponent()); return result; } else if (key instanceof PrivateKey - && RSAPrivateCrtKeySpec.class.isAssignableFrom(keySpec)) { + && RSAPrivateCrtKeySpec.class.isAssignableFrom(keySpec)) { final byte[] encoded = key.getEncoded(); if (!"PKCS#8".equals(key.getFormat()) || encoded == null) { throw new InvalidKeySpecException("Not a valid PKCS#8 encoding"); @@ -135,9 +135,10 @@ protected T engineGetKeySpec(Key key, Class keySpec) if (privKey instanceof RSAPrivateCrtKey) { RSAPrivateCrtKey rsaKey = (RSAPrivateCrtKey) privKey; @SuppressWarnings("unchecked") - T result = (T) new RSAPrivateCrtKeySpec(rsaKey.getModulus(), - rsaKey.getPublicExponent(), rsaKey.getPrivateExponent(), rsaKey.getPrimeP(), - rsaKey.getPrimeQ(), rsaKey.getPrimeExponentP(), rsaKey.getPrimeExponentQ(), + T result = (T) new RSAPrivateCrtKeySpec( + rsaKey.getModulus(), rsaKey.getPublicExponent(), + rsaKey.getPrivateExponent(), rsaKey.getPrimeP(), rsaKey.getPrimeQ(), + rsaKey.getPrimeExponentP(), rsaKey.getPrimeExponentQ(), rsaKey.getCrtCoefficient()); return result; } else { @@ -154,11 +155,11 @@ protected T engineGetKeySpec(Key key, Class keySpec) T result = (T) new RSAPrivateKeySpec(rsaKey.getModulus(), rsaKey.getPrivateExponent()); return result; } else if (key instanceof PrivateKey - && PKCS8EncodedKeySpec.class.isAssignableFrom(keySpec)) { + && PKCS8EncodedKeySpec.class.isAssignableFrom(keySpec)) { final byte[] encoded = key.getEncoded(); if (!"PKCS#8".equals(key.getFormat())) { throw new InvalidKeySpecException("Encoding type must be PKCS#8; was " - + key.getFormat()); + + key.getFormat()); } else if (encoded == null) { throw new InvalidKeySpecException("Key is not encodable"); } @@ -168,7 +169,7 @@ protected T engineGetKeySpec(Key key, Class keySpec) final byte[] encoded = key.getEncoded(); if (!"X.509".equals(key.getFormat())) { throw new InvalidKeySpecException("Encoding type must be X.509; was " - + key.getFormat()); + + key.getFormat()); } else if (encoded == null) { throw new InvalidKeySpecException("Key is not encodable"); } @@ -176,7 +177,8 @@ protected T engineGetKeySpec(Key key, Class keySpec) return result; } else { throw new InvalidKeySpecException("Unsupported key type and key spec combination; key=" - + key.getClass().getName() + ", keySpec=" + keySpec.getName()); + + key.getClass().getName() + + ", keySpec=" + keySpec.getName()); } } @@ -192,8 +194,8 @@ protected Key engineTranslateKey(Key key) throws InvalidKeyException { RSAPublicKey rsaKey = (RSAPublicKey) key; try { - return engineGeneratePublic(new RSAPublicKeySpec(rsaKey.getModulus(), - rsaKey.getPublicExponent())); + return engineGeneratePublic( + new RSAPublicKeySpec(rsaKey.getModulus(), rsaKey.getPublicExponent())); } catch (InvalidKeySpecException e) { throw new InvalidKeyException(e); } @@ -209,9 +211,9 @@ protected Key engineTranslateKey(Key key) throws InvalidKeyException { BigInteger crtCoefficient = rsaKey.getCrtCoefficient(); try { - return engineGeneratePrivate(new RSAPrivateCrtKeySpec(modulus, publicExponent, - privateExponent, primeP, primeQ, primeExponentP, primeExponentQ, - crtCoefficient)); + return engineGeneratePrivate(new RSAPrivateCrtKeySpec( + modulus, publicExponent, privateExponent, primeP, primeQ, primeExponentP, + primeExponentQ, crtCoefficient)); } catch (InvalidKeySpecException e) { throw new InvalidKeyException(e); } @@ -247,7 +249,7 @@ protected Key engineTranslateKey(Key key) throws InvalidKeyException { } } else { throw new InvalidKeyException("Key must be an RSA public or private key; was " - + key.getClass().getName()); + + key.getClass().getName()); } } } diff --git a/common/src/main/java/org/conscrypt/OpenSSLRSAKeyPairGenerator.java b/common/src/main/java/org/conscrypt/OpenSSLRSAKeyPairGenerator.java index 64ca7376c..f2dc2372b 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLRSAKeyPairGenerator.java +++ b/common/src/main/java/org/conscrypt/OpenSSLRSAKeyPairGenerator.java @@ -35,9 +35,7 @@ public final class OpenSSLRSAKeyPairGenerator extends KeyPairGeneratorSpi { /** * Default modulus size is 0x10001 (65537) */ - private byte[] publicExponent = new byte[] { - 0x01, 0x00, 0x01 - }; + private byte[] publicExponent = new byte[] {0x01, 0x00, 0x01}; /** * Default RSA key size 2048 bits. @@ -46,8 +44,8 @@ public final class OpenSSLRSAKeyPairGenerator extends KeyPairGeneratorSpi { @Override public KeyPair generateKeyPair() { - final OpenSSLKey key = new OpenSSLKey(NativeCrypto.RSA_generate_key_ex(modulusBits, - publicExponent)); + final OpenSSLKey key = + new OpenSSLKey(NativeCrypto.RSA_generate_key_ex(modulusBits, publicExponent)); PrivateKey privKey = OpenSSLRSAPrivateKey.getInstance(key); PublicKey pubKey = new OpenSSLRSAPublicKey(key); diff --git a/common/src/main/java/org/conscrypt/OpenSSLRSAPrivateCrtKey.java b/common/src/main/java/org/conscrypt/OpenSSLRSAPrivateCrtKey.java index 26be7fc19..ac5e5fd07 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLRSAPrivateCrtKey.java +++ b/common/src/main/java/org/conscrypt/OpenSSLRSAPrivateCrtKey.java @@ -85,8 +85,7 @@ private static OpenSSLKey init(RSAPrivateCrtKeySpec rsaKeySpec) throws InvalidKe return new OpenSSLKey(NativeCrypto.EVP_PKEY_new_RSA( modulus.toByteArray(), publicExponent == null ? null : publicExponent.toByteArray(), - privateExponent.toByteArray(), - primeP == null ? null : primeP.toByteArray(), + privateExponent.toByteArray(), primeP == null ? null : primeP.toByteArray(), primeQ == null ? null : primeQ.toByteArray(), primeExponentP == null ? null : primeExponentP.toByteArray(), primeExponentQ == null ? null : primeExponentQ.toByteArray(), @@ -131,8 +130,7 @@ static OpenSSLKey getInstance(RSAPrivateCrtKey rsaPrivateKey) throws InvalidKeyE return new OpenSSLKey(NativeCrypto.EVP_PKEY_new_RSA( modulus.toByteArray(), publicExponent == null ? null : publicExponent.toByteArray(), - privateExponent.toByteArray(), - primeP == null ? null : primeP.toByteArray(), + privateExponent.toByteArray(), primeP == null ? null : primeP.toByteArray(), primeQ == null ? null : primeQ.toByteArray(), primeExponentP == null ? null : primeExponentP.toByteArray(), primeExponentQ == null ? null : primeExponentQ.toByteArray(), @@ -276,10 +274,8 @@ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFo stream.defaultReadObject(); key = new OpenSSLKey(NativeCrypto.EVP_PKEY_new_RSA( - modulus.toByteArray(), - publicExponent == null ? null : publicExponent.toByteArray(), - privateExponent.toByteArray(), - primeP == null ? null : primeP.toByteArray(), + modulus.toByteArray(), publicExponent == null ? null : publicExponent.toByteArray(), + privateExponent.toByteArray(), primeP == null ? null : primeP.toByteArray(), primeQ == null ? null : primeQ.toByteArray(), primeExponentP == null ? null : primeExponentP.toByteArray(), primeExponentQ == null ? null : primeExponentQ.toByteArray(), diff --git a/common/src/main/java/org/conscrypt/OpenSSLRSAPrivateKey.java b/common/src/main/java/org/conscrypt/OpenSSLRSAPrivateKey.java index 253fe721c..505e1886b 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLRSAPrivateKey.java +++ b/common/src/main/java/org/conscrypt/OpenSSLRSAPrivateKey.java @@ -74,15 +74,9 @@ private static OpenSSLKey init(RSAPrivateKeySpec rsaKeySpec) throws InvalidKeySp } try { - return new OpenSSLKey(NativeCrypto.EVP_PKEY_new_RSA( - modulus.toByteArray(), - null, - privateExponent.toByteArray(), - null, - null, - null, - null, - null)); + return new OpenSSLKey(NativeCrypto.EVP_PKEY_new_RSA(modulus.toByteArray(), null, + privateExponent.toByteArray(), null, + null, null, null, null)); } catch (Exception e) { throw new InvalidKeySpecException(e); } @@ -97,8 +91,9 @@ static OpenSSLRSAPrivateKey getInstance(OpenSSLKey key) { } static OpenSSLKey wrapPlatformKey(RSAPrivateKey rsaPrivateKey) { - return new OpenSSLKey(NativeCrypto.getRSAPrivateKeyWrapper(rsaPrivateKey, rsaPrivateKey - .getModulus().toByteArray()), true); + return new OpenSSLKey(NativeCrypto.getRSAPrivateKeyWrapper( + rsaPrivateKey, rsaPrivateKey.getModulus().toByteArray()), + true); } /** @@ -106,8 +101,8 @@ static OpenSSLKey wrapPlatformKey(RSAPrivateKey rsaPrivateKey) { * using the key will be delegated to the {@code Signature}/{@code Cipher} implementation of the * provider which accepts the key. */ - static OpenSSLKey wrapJCAPrivateKeyForTLSStackOnly(PrivateKey privateKey, - PublicKey publicKey) throws InvalidKeyException { + static OpenSSLKey wrapJCAPrivateKeyForTLSStackOnly(PrivateKey privateKey, PublicKey publicKey) + throws InvalidKeyException { BigInteger modulus = null; if (privateKey instanceof RSAKey) { modulus = ((RSAKey) privateKey).getModulus(); @@ -116,7 +111,7 @@ static OpenSSLKey wrapJCAPrivateKeyForTLSStackOnly(PrivateKey privateKey, } if (modulus == null) { throw new InvalidKeyException("RSA modulus not available. Private: " + privateKey - + ", public: " + publicKey); + + ", public: " + publicKey); } return new OpenSSLKey( NativeCrypto.getRSAPrivateKeyWrapper(privateKey, modulus.toByteArray()), true); @@ -141,15 +136,9 @@ static OpenSSLKey getInstance(RSAPrivateKey rsaPrivateKey) throws InvalidKeyExce } try { - return new OpenSSLKey(NativeCrypto.EVP_PKEY_new_RSA( - modulus.toByteArray(), - null, - privateExponent.toByteArray(), - null, - null, - null, - null, - null)); + return new OpenSSLKey(NativeCrypto.EVP_PKEY_new_RSA(modulus.toByteArray(), null, + privateExponent.toByteArray(), null, + null, null, null, null)); } catch (Exception e) { throw new InvalidKeyException(e); } @@ -263,15 +252,9 @@ public String toString() { private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); - key = new OpenSSLKey(NativeCrypto.EVP_PKEY_new_RSA( - modulus.toByteArray(), - null, - privateExponent.toByteArray(), - null, - null, - null, - null, - null)); + key = new OpenSSLKey(NativeCrypto.EVP_PKEY_new_RSA(modulus.toByteArray(), null, + privateExponent.toByteArray(), null, + null, null, null, null)); fetchedParams = true; } diff --git a/common/src/main/java/org/conscrypt/OpenSSLRSAPublicKey.java b/common/src/main/java/org/conscrypt/OpenSSLRSAPublicKey.java index b2d31ed33..f58be8a08 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLRSAPublicKey.java +++ b/common/src/main/java/org/conscrypt/OpenSSLRSAPublicKey.java @@ -53,14 +53,8 @@ public OpenSSLKey getOpenSSLKey() { OpenSSLRSAPublicKey(RSAPublicKeySpec spec) throws InvalidKeySpecException { try { key = new OpenSSLKey(NativeCrypto.EVP_PKEY_new_RSA( - spec.getModulus().toByteArray(), - spec.getPublicExponent().toByteArray(), - null, - null, - null, - null, - null, - null)); + spec.getModulus().toByteArray(), spec.getPublicExponent().toByteArray(), null, + null, null, null, null, null)); } catch (Exception e) { throw new InvalidKeySpecException(e); } @@ -68,15 +62,10 @@ public OpenSSLKey getOpenSSLKey() { static OpenSSLKey getInstance(RSAPublicKey rsaPublicKey) throws InvalidKeyException { try { - return new OpenSSLKey(NativeCrypto.EVP_PKEY_new_RSA( - rsaPublicKey.getModulus().toByteArray(), - rsaPublicKey.getPublicExponent().toByteArray(), - null, - null, - null, - null, - null, - null)); + return new OpenSSLKey( + NativeCrypto.EVP_PKEY_new_RSA(rsaPublicKey.getModulus().toByteArray(), + rsaPublicKey.getPublicExponent().toByteArray(), + null, null, null, null, null, null)); } catch (Exception e) { throw new InvalidKeyException(e); } @@ -175,15 +164,9 @@ public String toString() { private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); - key = new OpenSSLKey(NativeCrypto.EVP_PKEY_new_RSA( - modulus.toByteArray(), - publicExponent.toByteArray(), - null, - null, - null, - null, - null, - null)); + key = new OpenSSLKey(NativeCrypto.EVP_PKEY_new_RSA(modulus.toByteArray(), + publicExponent.toByteArray(), null, null, + null, null, null, null)); fetchedParams = true; } diff --git a/common/src/main/java/org/conscrypt/OpenSSLServerSocketFactoryImpl.java b/common/src/main/java/org/conscrypt/OpenSSLServerSocketFactoryImpl.java index f216d3055..47541e1e0 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLServerSocketFactoryImpl.java +++ b/common/src/main/java/org/conscrypt/OpenSSLServerSocketFactoryImpl.java @@ -19,8 +19,9 @@ import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; -import javax.net.ServerSocketFactory; import java.security.KeyManagementException; + +import javax.net.ServerSocketFactory; import javax.net.ssl.SSLServerSocketFactory; /** @@ -103,8 +104,8 @@ public ServerSocket createServerSocket(int port, int backlog) throws IOException @Override public ServerSocket createServerSocket(int port, int backlog, InetAddress iAddress) throws IOException { - return new ConscryptServerSocket( - port, backlog, iAddress, (SSLParametersImpl) sslParameters.clone()) + return new ConscryptServerSocket(port, backlog, iAddress, + (SSLParametersImpl) sslParameters.clone()) .setUseEngineSocket(useEngineSocket); } } diff --git a/common/src/main/java/org/conscrypt/OpenSSLSignature.java b/common/src/main/java/org/conscrypt/OpenSSLSignature.java index 01ca3960a..04d40c529 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLSignature.java +++ b/common/src/main/java/org/conscrypt/OpenSSLSignature.java @@ -39,7 +39,8 @@ @Internal public class OpenSSLSignature extends SignatureSpi { private enum EngineType { - RSA, EC, + RSA, + EC, } private NativeRef.EVP_MD_CTX ctx; @@ -178,13 +179,13 @@ private void checkEngineType(OpenSSLKey pkey) throws InvalidKeyException { case RSA: if (pkeyType != NativeConstants.EVP_PKEY_RSA) { throw new InvalidKeyException("Signature initialized as " + engineType - + " (not RSA)"); + + " (not RSA)"); } break; case EC: if (pkeyType != NativeConstants.EVP_PKEY_EC) { throw new InvalidKeyException("Signature initialized as " + engineType - + " (not EC)"); + + " (not EC)"); } break; default: @@ -353,8 +354,8 @@ abstract static class RSAPSSPadding extends OpenSSLSignature { private long mgf1EvpMdRef; private int saltSizeBytes; - RSAPSSPadding( - long contentDigestEvpMdRef, String contentDigestAlgorithm, int saltSizeBytes) { + RSAPSSPadding(long contentDigestEvpMdRef, String contentDigestAlgorithm, + int saltSizeBytes) { super(contentDigestEvpMdRef, EngineType.RSA); this.contentDigestAlgorithm = contentDigestAlgorithm; this.mgf1DigestAlgorithm = contentDigestAlgorithm; @@ -376,11 +377,11 @@ protected final void engineSetParameter(AlgorithmParameterSpec params) if (!(params instanceof PSSParameterSpec)) { throw new InvalidAlgorithmParameterException( "Unsupported parameter: " + params + ". Only " - + PSSParameterSpec.class.getName() + " supported"); + + PSSParameterSpec.class.getName() + " supported"); } PSSParameterSpec spec = (PSSParameterSpec) params; - String specContentDigest = EvpMdRef - .getJcaDigestAlgorithmStandardName(spec.getDigestAlgorithm()); + String specContentDigest = + EvpMdRef.getJcaDigestAlgorithmStandardName(spec.getDigestAlgorithm()); if (specContentDigest == null) { throw new InvalidAlgorithmParameterException( "Unsupported content digest algorithm: " + spec.getDigestAlgorithm()); @@ -391,45 +392,45 @@ protected final void engineSetParameter(AlgorithmParameterSpec params) String specMgfAlgorithm = spec.getMGFAlgorithm(); if (!EvpMdRef.MGF1_ALGORITHM_NAME.equalsIgnoreCase(specMgfAlgorithm) - && !EvpMdRef.MGF1_OID.equals(specMgfAlgorithm)) { + && !EvpMdRef.MGF1_OID.equals(specMgfAlgorithm)) { throw new InvalidAlgorithmParameterException( "Unsupported MGF algorithm: " + specMgfAlgorithm + ". Only " - + EvpMdRef.MGF1_ALGORITHM_NAME + " supported"); + + EvpMdRef.MGF1_ALGORITHM_NAME + " supported"); } AlgorithmParameterSpec mgfSpec = spec.getMGFParameters(); if (!(mgfSpec instanceof MGF1ParameterSpec)) { throw new InvalidAlgorithmParameterException( "Unsupported MGF parameters: " + mgfSpec + ". Only " - + MGF1ParameterSpec.class.getName() + " supported"); + + MGF1ParameterSpec.class.getName() + " supported"); } MGF1ParameterSpec specMgf1Spec = (MGF1ParameterSpec) spec.getMGFParameters(); - String specMgf1Digest = EvpMdRef - .getJcaDigestAlgorithmStandardName(specMgf1Spec.getDigestAlgorithm()); + String specMgf1Digest = + EvpMdRef.getJcaDigestAlgorithmStandardName(specMgf1Spec.getDigestAlgorithm()); if (specMgf1Digest == null) { - throw new InvalidAlgorithmParameterException( - "Unsupported MGF1 digest algorithm: " + specMgf1Spec.getDigestAlgorithm()); + throw new InvalidAlgorithmParameterException("Unsupported MGF1 digest algorithm: " + + specMgf1Spec.getDigestAlgorithm()); } long specMgf1EvpMdRef; try { - specMgf1EvpMdRef = EvpMdRef - .getEVP_MDByJcaDigestAlgorithmStandardName(specMgf1Digest); + specMgf1EvpMdRef = + EvpMdRef.getEVP_MDByJcaDigestAlgorithmStandardName(specMgf1Digest); } catch (NoSuchAlgorithmException e) { throw new ProviderException("Failed to obtain EVP_MD for " + specMgf1Digest, e); } int specSaltSizeBytes = spec.getSaltLength(); if (specSaltSizeBytes < 0) { - throw new InvalidAlgorithmParameterException( - "Salt length must be non-negative: " + specSaltSizeBytes); + throw new InvalidAlgorithmParameterException("Salt length must be non-negative: " + + specSaltSizeBytes); } int specTrailer = spec.getTrailerField(); if (specTrailer != TRAILER_FIELD_BC_ID) { - throw new InvalidAlgorithmParameterException( - "Unsupported trailer field: " + specTrailer + ". Only " - + TRAILER_FIELD_BC_ID + " supported"); + throw new InvalidAlgorithmParameterException("Unsupported trailer field: " + + specTrailer + ". Only " + + TRAILER_FIELD_BC_ID + " supported"); } this.mgf1DigestAlgorithm = specMgf1Digest; @@ -446,13 +447,10 @@ protected final void engineSetParameter(AlgorithmParameterSpec params) protected final AlgorithmParameters engineGetParameters() { try { AlgorithmParameters result = AlgorithmParameters.getInstance("PSS"); - result.init( - new PSSParameterSpec( - contentDigestAlgorithm, - EvpMdRef.MGF1_ALGORITHM_NAME, - new MGF1ParameterSpec(mgf1DigestAlgorithm), - saltSizeBytes, - TRAILER_FIELD_BC_ID)); + result.init(new PSSParameterSpec(contentDigestAlgorithm, + EvpMdRef.MGF1_ALGORITHM_NAME, + new MGF1ParameterSpec(mgf1DigestAlgorithm), + saltSizeBytes, TRAILER_FIELD_BC_ID)); return result; } catch (NoSuchAlgorithmException | InvalidParameterSpecException e) { throw new ProviderException("Failed to create PSS AlgorithmParameters", e); diff --git a/common/src/main/java/org/conscrypt/OpenSSLSignatureRawECDSA.java b/common/src/main/java/org/conscrypt/OpenSSLSignatureRawECDSA.java index 39440ca64..c5046dd7e 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLSignatureRawECDSA.java +++ b/common/src/main/java/org/conscrypt/OpenSSLSignatureRawECDSA.java @@ -89,8 +89,8 @@ protected byte[] engineSign() throws SignatureException { int output_size = NativeCrypto.ECDSA_size(key.getNativeRef()); byte[] outputBuffer = new byte[output_size]; try { - int bytes_written = NativeCrypto.ECDSA_sign( - buffer.array(), buffer.size(), outputBuffer, key.getNativeRef()); + int bytes_written = NativeCrypto.ECDSA_sign(buffer.array(), buffer.size(), outputBuffer, + key.getNativeRef()); if (bytes_written < 0) { throw new SignatureException("Could not compute signature."); } @@ -118,8 +118,8 @@ protected boolean engineVerify(byte[] sigBytes) throws SignatureException { } try { - int result = NativeCrypto.ECDSA_verify( - buffer.array(), buffer.size(), sigBytes, key.getNativeRef()); + int result = NativeCrypto.ECDSA_verify(buffer.array(), buffer.size(), sigBytes, + key.getNativeRef()); if (result == -1) { throw new SignatureException("Could not verify signature."); } diff --git a/common/src/main/java/org/conscrypt/OpenSSLSignatureRawRSA.java b/common/src/main/java/org/conscrypt/OpenSSLSignatureRawRSA.java index cc8db4918..f9764a726 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLSignatureRawRSA.java +++ b/common/src/main/java/org/conscrypt/OpenSSLSignatureRawRSA.java @@ -137,14 +137,14 @@ protected byte[] engineSign() throws SignatureException { } if (inputIsTooLong) { - throw new SignatureException("input length " + inputOffset + " != " - + inputBuffer.length + " (modulus size)"); + throw new SignatureException("input length " + inputOffset + " != " + inputBuffer.length + + " (modulus size)"); } byte[] outputBuffer = new byte[inputBuffer.length]; try { NativeCrypto.RSA_private_encrypt(inputOffset, inputBuffer, outputBuffer, - key.getNativeRef(), NativeConstants.RSA_PKCS1_PADDING); + key.getNativeRef(), NativeConstants.RSA_PKCS1_PADDING); return outputBuffer; } catch (Exception ex) { throw new SignatureException(ex); @@ -168,7 +168,7 @@ protected boolean engineVerify(byte[] sigBytes) throws SignatureException { // exception that matches other implementations. if (sigBytes.length > inputBuffer.length) { throw new SignatureException("Input signature length is too large: " + sigBytes.length - + " > " + inputBuffer.length); + + " > " + inputBuffer.length); } byte[] outputBuffer = new byte[inputBuffer.length]; @@ -176,7 +176,8 @@ protected boolean engineVerify(byte[] sigBytes) throws SignatureException { final int resultSize; try { resultSize = NativeCrypto.RSA_public_decrypt(sigBytes.length, sigBytes, - outputBuffer, key.getNativeRef(), NativeConstants.RSA_PKCS1_PADDING); + outputBuffer, key.getNativeRef(), + NativeConstants.RSA_PKCS1_PADDING); } catch (SignatureException e) { throw e; } catch (Exception e) { diff --git a/common/src/main/java/org/conscrypt/OpenSSLSocketFactoryImpl.java b/common/src/main/java/org/conscrypt/OpenSSLSocketFactoryImpl.java index 0db71cdd9..41c0f3aa4 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLSocketFactoryImpl.java +++ b/common/src/main/java/org/conscrypt/OpenSSLSocketFactoryImpl.java @@ -25,6 +25,7 @@ import java.net.SocketException; import java.net.UnknownHostException; import java.security.KeyManagementException; + import javax.net.SocketFactory; import javax.net.ssl.SSLSocketFactory; @@ -103,11 +104,10 @@ public Socket createSocket() throws IOException { @Override public Socket createSocket(String hostname, int port) throws IOException, UnknownHostException { if (useEngineSocket) { - return createEngineSocket( - hostname, port, (SSLParametersImpl) sslParameters.clone()); + return createEngineSocket(hostname, port, (SSLParametersImpl) sslParameters.clone()); } else { - return createFileDescriptorSocket( - hostname, port, (SSLParametersImpl) sslParameters.clone()); + return createFileDescriptorSocket(hostname, port, + (SSLParametersImpl) sslParameters.clone()); } } @@ -115,34 +115,33 @@ public Socket createSocket(String hostname, int port) throws IOException, Unknow public Socket createSocket(String hostname, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException { if (useEngineSocket) { - return createEngineSocket(hostname, port, localHost, - localPort, (SSLParametersImpl) sslParameters.clone()); + return createEngineSocket(hostname, port, localHost, localPort, + (SSLParametersImpl) sslParameters.clone()); } else { - return createFileDescriptorSocket(hostname, port, localHost, - localPort, (SSLParametersImpl) sslParameters.clone()); + return createFileDescriptorSocket(hostname, port, localHost, localPort, + (SSLParametersImpl) sslParameters.clone()); } } @Override public Socket createSocket(InetAddress address, int port) throws IOException { if (useEngineSocket) { - return createEngineSocket( - address, port, (SSLParametersImpl) sslParameters.clone()); + return createEngineSocket(address, port, (SSLParametersImpl) sslParameters.clone()); } else { - return createFileDescriptorSocket( - address, port, (SSLParametersImpl) sslParameters.clone()); + return createFileDescriptorSocket(address, port, + (SSLParametersImpl) sslParameters.clone()); } } @Override public Socket createSocket(InetAddress address, int port, InetAddress localAddress, - int localPort) throws IOException { + int localPort) throws IOException { if (useEngineSocket) { - return createEngineSocket(address, port, localAddress, - localPort, (SSLParametersImpl) sslParameters.clone()); + return createEngineSocket(address, port, localAddress, localPort, + (SSLParametersImpl) sslParameters.clone()); } else { - return createFileDescriptorSocket(address, port, localAddress, - localPort, (SSLParametersImpl) sslParameters.clone()); + return createFileDescriptorSocket(address, port, localAddress, localPort, + (SSLParametersImpl) sslParameters.clone()); } } @@ -155,11 +154,11 @@ public Socket createSocket(Socket socket, String hostname, int port, boolean aut } if (!useEngineSocket && hasFileDescriptor(socket)) { - return createFileDescriptorSocket( - socket, hostname, port, autoClose, (SSLParametersImpl) sslParameters.clone()); + return createFileDescriptorSocket(socket, hostname, port, autoClose, + (SSLParametersImpl) sslParameters.clone()); } else { - return createEngineSocket( - socket, hostname, port, autoClose, (SSLParametersImpl) sslParameters.clone()); + return createEngineSocket(socket, hostname, port, autoClose, + (SSLParametersImpl) sslParameters.clone()); } } diff --git a/common/src/main/java/org/conscrypt/OpenSSLSocketImpl.java b/common/src/main/java/org/conscrypt/OpenSSLSocketImpl.java index f0c2571e1..3e28cec21 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,15 @@ 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 setChannelIdEnabled(boolean enabled); - @Override - public abstract byte[] getChannelId() throws SSLException; + @Override public abstract byte[] getChannelId() throws SSLException; - @Override - public abstract void setChannelIdPrivateKey(PrivateKey privateKey); + @Override public abstract void setChannelIdPrivateKey(PrivateKey privateKey); /** * @deprecated NPN is not supported @@ -122,8 +116,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 +142,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..aa85e29bf 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLX25519PrivateKey.java +++ b/common/src/main/java/org/conscrypt/OpenSSLX25519PrivateKey.java @@ -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..7ec4c87a6 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLX25519PublicKey.java +++ b/common/src/main/java/org/conscrypt/OpenSSLX25519PublicKey.java @@ -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/OpenSSLX509CRL.java b/common/src/main/java/org/conscrypt/OpenSSLX509CRL.java index 5b131d314..be545b276 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLX509CRL.java +++ b/common/src/main/java/org/conscrypt/OpenSSLX509CRL.java @@ -16,6 +16,8 @@ package org.conscrypt; +import org.conscrypt.OpenSSLX509CertificateFactory.ParsingException; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; @@ -44,7 +46,6 @@ import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.security.auth.x500.X500Principal; -import org.conscrypt.OpenSSLX509CertificateFactory.ParsingException; /** * An implementation of {@link X509CRL} based on BoringSSL. @@ -86,8 +87,7 @@ static OpenSSLX509CRL fromX509DerInputStream(InputStream is) throws ParsingExcep } } - static List fromPkcs7DerInputStream(InputStream is) - throws ParsingException { + static List fromPkcs7DerInputStream(InputStream is) throws ParsingException { OpenSSLBIOInputStream bis = new OpenSSLBIOInputStream(is, true); final long[] certRefs; @@ -125,14 +125,13 @@ static OpenSSLX509CRL fromX509PemInputStream(InputStream is) throws ParsingExcep } } - static List fromPkcs7PemInputStream(InputStream is) - throws ParsingException { + static List fromPkcs7PemInputStream(InputStream is) throws ParsingException { OpenSSLBIOInputStream bis = new OpenSSLBIOInputStream(is, true); final long[] certRefs; try { - certRefs = NativeCrypto.PEM_read_bio_PKCS7(bis.getBioContext(), - NativeCrypto.PKCS7_CRLS); + certRefs = + NativeCrypto.PEM_read_bio_PKCS7(bis.getBioContext(), NativeCrypto.PKCS7_CRLS); } catch (Exception e) { throw new ParsingException(e); } finally { @@ -151,8 +150,8 @@ static List fromPkcs7PemInputStream(InputStream is) @Override public Set getCriticalExtensionOIDs() { - String[] critOids = - NativeCrypto.get_X509_CRL_ext_oids(mContext, this, NativeCrypto.EXTENSION_TYPE_CRITICAL); + String[] critOids = NativeCrypto.get_X509_CRL_ext_oids( + mContext, this, NativeCrypto.EXTENSION_TYPE_CRITICAL); /* * This API has a special case that if there are no extensions, we @@ -160,8 +159,11 @@ public Set getCriticalExtensionOIDs() { * non-critical extensions. */ if ((critOids.length == 0) - && (NativeCrypto.get_X509_CRL_ext_oids(mContext, this, - NativeCrypto.EXTENSION_TYPE_NON_CRITICAL).length == 0)) { + && (NativeCrypto + .get_X509_CRL_ext_oids(mContext, this, + NativeCrypto.EXTENSION_TYPE_NON_CRITICAL) + .length + == 0)) { return null; } @@ -175,9 +177,8 @@ public byte[] getExtensionValue(String oid) { @Override public Set getNonCriticalExtensionOIDs() { - String[] nonCritOids = - NativeCrypto.get_X509_CRL_ext_oids(mContext, this, - NativeCrypto.EXTENSION_TYPE_NON_CRITICAL); + String[] nonCritOids = NativeCrypto.get_X509_CRL_ext_oids( + mContext, this, NativeCrypto.EXTENSION_TYPE_NON_CRITICAL); /* * This API has a special case that if there are no extensions, we @@ -185,8 +186,10 @@ public Set getNonCriticalExtensionOIDs() { * check critical extensions. */ if ((nonCritOids.length == 0) - && (NativeCrypto.get_X509_CRL_ext_oids(mContext, this, - NativeCrypto.EXTENSION_TYPE_CRITICAL).length == 0)) { + && (NativeCrypto + .get_X509_CRL_ext_oids(mContext, this, NativeCrypto.EXTENSION_TYPE_CRITICAL) + .length + == 0)) { return null; } @@ -195,8 +198,8 @@ public Set getNonCriticalExtensionOIDs() { @Override public boolean hasUnsupportedCriticalExtension() { - final String[] criticalOids = - NativeCrypto.get_X509_CRL_ext_oids(mContext, this, NativeCrypto.EXTENSION_TYPE_CRITICAL); + final String[] criticalOids = NativeCrypto.get_X509_CRL_ext_oids( + mContext, this, NativeCrypto.EXTENSION_TYPE_CRITICAL); for (String oid : criticalOids) { final long extensionRef = NativeCrypto.X509_CRL_get_ext(mContext, this, oid); if (NativeCrypto.X509_supported_extension(extensionRef) != 1) { @@ -212,8 +215,8 @@ public byte[] getEncoded() throws CRLException { return NativeCrypto.i2d_X509_CRL(mContext, this); } - private void verifyOpenSSL(OpenSSLKey pkey) throws NoSuchAlgorithmException, - InvalidKeyException, SignatureException { + private void verifyOpenSSL(OpenSSLKey pkey) + throws NoSuchAlgorithmException, InvalidKeyException, SignatureException { try { NativeCrypto.X509_CRL_verify(mContext, this, pkey.getNativeRef()); } catch (BadPaddingException | IllegalBlockSizeException e) { @@ -221,8 +224,9 @@ private void verifyOpenSSL(OpenSSLKey pkey) throws NoSuchAlgorithmException, } } - private void verifyInternal(PublicKey key, String sigProvider) throws NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException { + private void verifyInternal(PublicKey key, String sigProvider) + throws NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, + SignatureException { String sigAlg = getSigAlgName(); if (sigAlg == null) { sigAlg = getSigAlgOID(); @@ -243,8 +247,9 @@ private void verifyInternal(PublicKey key, String sigProvider) throws NoSuchAlgo } @Override - public void verify(PublicKey key) throws CRLException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException { + public void verify(PublicKey key) + throws CRLException, NoSuchAlgorithmException, InvalidKeyException, + NoSuchProviderException, SignatureException { if (key instanceof OpenSSLKeyHolder) { OpenSSLKey pkey = ((OpenSSLKeyHolder) key).getOpenSSLKey(); verifyOpenSSL(pkey); @@ -255,9 +260,9 @@ public void verify(PublicKey key) throws CRLException, NoSuchAlgorithmException, } @Override - public void verify(PublicKey key, String sigProvider) throws CRLException, - NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, - SignatureException { + public void verify(PublicKey key, String sigProvider) + throws CRLException, NoSuchAlgorithmException, InvalidKeyException, + NoSuchProviderException, SignatureException { verifyInternal(key, sigProvider); } @@ -291,8 +296,8 @@ public Date getNextUpdate() { @Override public X509CRLEntry getRevokedCertificate(BigInteger serialNumber) { - final long revokedRef = NativeCrypto.X509_CRL_get0_by_serial(mContext, this, - serialNumber.toByteArray()); + final long revokedRef = + NativeCrypto.X509_CRL_get0_by_serial(mContext, this, serialNumber.toByteArray()); if (revokedRef == 0) { return null; } @@ -307,8 +312,8 @@ public X509CRLEntry getRevokedCertificate(BigInteger serialNumber) { public X509CRLEntry getRevokedCertificate(X509Certificate certificate) { if (certificate instanceof OpenSSLX509Certificate) { OpenSSLX509Certificate osslCert = (OpenSSLX509Certificate) certificate; - final long x509RevokedRef = NativeCrypto.X509_CRL_get0_by_cert(mContext, this, - osslCert.getContext(), osslCert); + final long x509RevokedRef = NativeCrypto.X509_CRL_get0_by_cert( + mContext, this, osslCert.getContext(), osslCert); if (x509RevokedRef == 0) { return null; @@ -388,15 +393,15 @@ public boolean isRevoked(Certificate cert) { osslCert = (OpenSSLX509Certificate) cert; } else { try { - osslCert = OpenSSLX509Certificate.fromX509DerInputStream(new ByteArrayInputStream( - cert.getEncoded())); + osslCert = OpenSSLX509Certificate.fromX509DerInputStream( + new ByteArrayInputStream(cert.getEncoded())); } catch (Exception e) { throw new RuntimeException("cannot convert certificate", e); } } - final long x509RevokedRef = NativeCrypto.X509_CRL_get0_by_cert(mContext, this, - osslCert.getContext(), osslCert); + final long x509RevokedRef = + NativeCrypto.X509_CRL_get0_by_cert(mContext, this, osslCert.getContext(), osslCert); return x509RevokedRef != 0; } @@ -426,5 +431,4 @@ protected void finalize() throws Throwable { super.finalize(); } } - } diff --git a/common/src/main/java/org/conscrypt/OpenSSLX509CRLEntry.java b/common/src/main/java/org/conscrypt/OpenSSLX509CRLEntry.java index d798dafb6..22b13f87d 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLX509CRLEntry.java +++ b/common/src/main/java/org/conscrypt/OpenSSLX509CRLEntry.java @@ -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/OpenSSLX509CertPath.java b/common/src/main/java/org/conscrypt/OpenSSLX509CertPath.java index 3a5cb04cb..1ebee49e0 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLX509CertPath.java +++ b/common/src/main/java/org/conscrypt/OpenSSLX509CertPath.java @@ -16,6 +16,8 @@ package org.conscrypt; +import org.conscrypt.OpenSSLX509CertificateFactory.ParsingException; + import java.io.IOException; import java.io.InputStream; import java.io.PushbackInputStream; @@ -30,7 +32,6 @@ import java.util.Collections; import java.util.Iterator; import java.util.List; -import org.conscrypt.OpenSSLX509CertificateFactory.ParsingException; /** * An implementation of {@link CertPath} based on BoringSSL. @@ -38,9 +39,8 @@ final class OpenSSLX509CertPath extends CertPath { private static final long serialVersionUID = -3249106005255170761L; - private static final byte[] PKCS7_MARKER = new byte[] { - '-', '-', '-', '-', '-', 'B', 'E', 'G', 'I', 'N', ' ', 'P', 'K', 'C', 'S', '7' - }; + private static final byte[] PKCS7_MARKER = new byte[] {'-', '-', '-', '-', '-', 'B', 'E', 'G', + 'I', 'N', ' ', 'P', 'K', 'C', 'S', '7'}; private static final int PUSHBACK_SIZE = 64; @@ -70,8 +70,8 @@ static Encoding findByApiName(String apiName) throws CertificateEncodingExceptio } /** Unmodifiable list of encodings for the API. */ - private static final List ALL_ENCODINGS = Collections.unmodifiableList(Arrays - .asList(new String[] { + private static final List ALL_ENCODINGS = + Collections.unmodifiableList(Arrays.asList(new String[] { Encoding.PKI_PATH.apiName, Encoding.PKCS7.apiName, })); @@ -166,7 +166,7 @@ private static CertPath fromPkiPathEncoding(InputStream inStream) throws Certifi } if (certRefs == null) { - return new OpenSSLX509CertPath(Collections. emptyList()); + return new OpenSSLX509CertPath(Collections.emptyList()); } final List certs = @@ -188,7 +188,7 @@ private static CertPath fromPkiPathEncoding(InputStream inStream) throws Certifi private static CertPath fromPkcs7Encoding(InputStream inStream) throws CertificateException { try { if (inStream == null || inStream.available() == 0) { - return new OpenSSLX509CertPath(Collections. emptyList()); + return new OpenSSLX509CertPath(Collections.emptyList()); } } catch (IOException e) { throw new CertificateException("Problem reading input stream", e); @@ -212,7 +212,8 @@ private static CertPath fromPkcs7Encoding(InputStream inStream) throws Certifica pbis.unread(buffer, 0, len); if (len == PKCS7_MARKER.length && Arrays.equals(PKCS7_MARKER, buffer)) { - return new OpenSSLX509CertPath(OpenSSLX509Certificate.fromPkcs7PemInputStream(pbis)); + return new OpenSSLX509CertPath( + OpenSSLX509Certificate.fromPkcs7PemInputStream(pbis)); } return new OpenSSLX509CertPath(OpenSSLX509Certificate.fromPkcs7DerInputStream(pbis)); diff --git a/common/src/main/java/org/conscrypt/OpenSSLX509Certificate.java b/common/src/main/java/org/conscrypt/OpenSSLX509Certificate.java index 38afd3efb..759cb9def 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLX509Certificate.java +++ b/common/src/main/java/org/conscrypt/OpenSSLX509Certificate.java @@ -16,6 +16,8 @@ package org.conscrypt; +import org.conscrypt.OpenSSLX509CertificateFactory.ParsingException; + import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.math.BigInteger; @@ -51,7 +53,6 @@ import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.security.auth.x500.X500Principal; -import org.conscrypt.OpenSSLX509CertificateFactory.ParsingException; /** * An implementation of {@link X509Certificate} based on BoringSSL. @@ -126,8 +127,7 @@ public static List fromPkcs7DerInputStream(InputStream i return new ArrayList<>(); } - final List certs = new ArrayList<>( - certRefs.length); + final List certs = new ArrayList<>(certRefs.length); for (long certRef : certRefs) { if (certRef == 0) { continue; @@ -160,16 +160,15 @@ public static List fromPkcs7PemInputStream(InputStream i final long[] certRefs; try { - certRefs = NativeCrypto.PEM_read_bio_PKCS7(bis.getBioContext(), - NativeCrypto.PKCS7_CERTS); + certRefs = + NativeCrypto.PEM_read_bio_PKCS7(bis.getBioContext(), NativeCrypto.PKCS7_CERTS); } catch (Exception e) { throw new ParsingException(e); } finally { bis.release(); } - final List certs = new ArrayList<>( - certRefs.length); + final List certs = new ArrayList<>(certRefs.length); for (long certRef : certRefs) { if (certRef == 0) { continue; @@ -192,8 +191,8 @@ public static OpenSSLX509Certificate fromCertificate(Certificate cert) @Override public Set getCriticalExtensionOIDs() { - String[] critOids = - NativeCrypto.get_X509_ext_oids(mContext, this, NativeCrypto.EXTENSION_TYPE_CRITICAL); + String[] critOids = NativeCrypto.get_X509_ext_oids(mContext, this, + NativeCrypto.EXTENSION_TYPE_CRITICAL); /* * This API has a special case that if there are no extensions, we @@ -201,8 +200,10 @@ public Set getCriticalExtensionOIDs() { * non-critical extensions. */ if ((critOids.length == 0) - && (NativeCrypto.get_X509_ext_oids(mContext, this, - NativeCrypto.EXTENSION_TYPE_NON_CRITICAL).length == 0)) { + && (NativeCrypto + .get_X509_ext_oids(mContext, this, NativeCrypto.EXTENSION_TYPE_NON_CRITICAL) + .length + == 0)) { return null; } @@ -216,8 +217,8 @@ public byte[] getExtensionValue(String oid) { @Override public Set getNonCriticalExtensionOIDs() { - String[] nonCritOids = - NativeCrypto.get_X509_ext_oids(mContext, this, NativeCrypto.EXTENSION_TYPE_NON_CRITICAL); + String[] nonCritOids = NativeCrypto.get_X509_ext_oids( + mContext, this, NativeCrypto.EXTENSION_TYPE_NON_CRITICAL); /* * This API has a special case that if there are no extensions, we @@ -225,8 +226,9 @@ public Set getNonCriticalExtensionOIDs() { * check critical extensions. */ if ((nonCritOids.length == 0) - && (NativeCrypto.get_X509_ext_oids(mContext, this, - NativeCrypto.EXTENSION_TYPE_CRITICAL).length == 0)) { + && (NativeCrypto.get_X509_ext_oids(mContext, this, NativeCrypto.EXTENSION_TYPE_CRITICAL) + .length + == 0)) { return null; } @@ -235,28 +237,31 @@ public Set getNonCriticalExtensionOIDs() { @Override public boolean hasUnsupportedCriticalExtension() { - return (NativeCrypto.get_X509_ex_flags(mContext, this) & NativeConstants.EXFLAG_CRITICAL) != 0; + return (NativeCrypto.get_X509_ex_flags(mContext, this) & NativeConstants.EXFLAG_CRITICAL) + != 0; } @Override - @SuppressWarnings({"JdkObsolete", "JavaUtilDate"}) // Needed for API compatibility - public void checkValidity() throws CertificateExpiredException, - CertificateNotYetValidException { + @SuppressWarnings({"JdkObsolete", "JavaUtilDate"}) // Needed for API compatibility + public void checkValidity() + throws CertificateExpiredException, CertificateNotYetValidException { checkValidity(new Date()); } @Override @SuppressWarnings({"JdkObsolete", "JavaUtilDate"}) // Needed for API compatibility - public void checkValidity(Date date) throws CertificateExpiredException, - CertificateNotYetValidException { + public void checkValidity(Date date) + throws CertificateExpiredException, CertificateNotYetValidException { if (getNotBefore().compareTo(date) > 0) { throw new CertificateNotYetValidException("Certificate not valid until " - + getNotBefore().toString() + " (compared to " + date.toString() + ")"); + + getNotBefore().toString() + " (compared to " + + date.toString() + ")"); } if (getNotAfter().compareTo(date) < 0) { throw new CertificateExpiredException("Certificate expired at " - + getNotAfter().toString() + " (compared to " + date.toString() + ")"); + + getNotAfter().toString() + " (compared to " + + date.toString() + ")"); } } @@ -381,9 +386,9 @@ private void verifyOpenSSL(OpenSSLKey pkey) throws CertificateException, Signatu } } - private void verifyInternal(PublicKey key, String sigProvider) throws - NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, - SignatureException, CertificateEncodingException { + private void verifyInternal(PublicKey key, String sigProvider) + throws NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, + SignatureException, CertificateEncodingException { final Signature sig; if (sigProvider == null) { sig = Signature.getInstance(getSigAlgName()); @@ -399,8 +404,9 @@ private void verifyInternal(PublicKey key, String sigProvider) throws } @Override - public void verify(PublicKey key) throws CertificateException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException { + public void verify(PublicKey key) + throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, + NoSuchProviderException, SignatureException { if (key instanceof OpenSSLKeyHolder) { OpenSSLKey pkey = ((OpenSSLKeyHolder) key).getOpenSSLKey(); verifyOpenSSL(pkey); @@ -411,14 +417,14 @@ public void verify(PublicKey key) throws CertificateException, NoSuchAlgorithmEx } @Override - public void verify(PublicKey key, String sigProvider) throws CertificateException, - NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, - SignatureException { + public void verify(PublicKey key, String sigProvider) + throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, + NoSuchProviderException, SignatureException { verifyInternal(key, sigProvider); } /* @Override */ - @SuppressWarnings("MissingOverride") // For compilation with Java 7. + @SuppressWarnings("MissingOverride") // For compilation with Java 7. // noinspection Override public void verify(PublicKey key, Provider sigProvider) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, @@ -519,14 +525,14 @@ private static Collection> alternativeNameArrayToList(Object[][] altName @Override public Collection> getSubjectAlternativeNames() throws CertificateParsingException { - return alternativeNameArrayToList(NativeCrypto.get_X509_GENERAL_NAME_stack(mContext, this, - NativeCrypto.GN_STACK_SUBJECT_ALT_NAME)); + return alternativeNameArrayToList(NativeCrypto.get_X509_GENERAL_NAME_stack( + mContext, this, NativeCrypto.GN_STACK_SUBJECT_ALT_NAME)); } @Override public Collection> getIssuerAlternativeNames() throws CertificateParsingException { - return alternativeNameArrayToList(NativeCrypto.get_X509_GENERAL_NAME_stack(mContext, this, - NativeCrypto.GN_STACK_ISSUER_ALT_NAME)); + return alternativeNameArrayToList(NativeCrypto.get_X509_GENERAL_NAME_stack( + mContext, this, NativeCrypto.GN_STACK_ISSUER_ALT_NAME)); } @Override diff --git a/common/src/main/java/org/conscrypt/OpenSSLX509CertificateFactory.java b/common/src/main/java/org/conscrypt/OpenSSLX509CertificateFactory.java index 5eb4283ca..77f3e7f89 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLX509CertificateFactory.java +++ b/common/src/main/java/org/conscrypt/OpenSSLX509CertificateFactory.java @@ -38,8 +38,8 @@ */ @Internal public class OpenSSLX509CertificateFactory extends CertificateFactorySpi { - private static final byte[] PKCS7_MARKER = new byte[] { - '-', '-', '-', '-', '-', 'B', 'E', 'G', 'I', 'N', ' ', 'P', 'K', 'C', 'S', '7'}; + private static final byte[] PKCS7_MARKER = new byte[] {'-', '-', '-', '-', '-', 'B', 'E', 'G', + 'I', 'N', ' ', 'P', 'K', 'C', 'S', '7'}; private static final byte[] PEM_MARKER = new byte[] {'-', '-', '-', '-', '-', 'B', 'E', 'G', 'I', 'N', ' '}; private static final int DASH = 45; // Value of '-' diff --git a/common/src/main/java/org/conscrypt/OpenSSLXDHKeyAgreement.java b/common/src/main/java/org/conscrypt/OpenSSLXDHKeyAgreement.java index 660c5f153..b310bdfba 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLXDHKeyAgreement.java +++ b/common/src/main/java/org/conscrypt/OpenSSLXDHKeyAgreement.java @@ -25,8 +25,7 @@ */ @Internal public final class OpenSSLXDHKeyAgreement extends OpenSSLBaseDHKeyAgreement { - public OpenSSLXDHKeyAgreement() { - } + public OpenSSLXDHKeyAgreement() {} @Override protected byte[] convertPublicKey(PublicKey key) throws InvalidKeyException { @@ -47,11 +46,9 @@ protected byte[] convertPrivateKey(PrivateKey key) throws InvalidKeyException { } @Override - protected int computeKey(byte[] buffer, byte[] theirPublicKey, byte[] ourPrivateKey) throws InvalidKeyException { - if (!NativeCrypto.X25519( - buffer, - ourPrivateKey, - theirPublicKey)) { + protected int computeKey(byte[] buffer, byte[] theirPublicKey, byte[] ourPrivateKey) + throws InvalidKeyException { + if (!NativeCrypto.X25519(buffer, ourPrivateKey, theirPublicKey)) { throw new InvalidKeyException("Error running X25519"); } diff --git a/common/src/main/java/org/conscrypt/OpenSSLXDHKeyFactory.java b/common/src/main/java/org/conscrypt/OpenSSLXDHKeyFactory.java index 2238cd326..3b8819367 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLXDHKeyFactory.java +++ b/common/src/main/java/org/conscrypt/OpenSSLXDHKeyFactory.java @@ -39,8 +39,8 @@ public final class OpenSSLXDHKeyFactory extends KeyFactorySpi { private static final Class javaXecPublicKeySpec = getJavaXECPublicKeySpec(); private static final Class javaXecPrivateKeySpec = getJavaXECPrivateKeySpec(); - private static final AlgorithmParameterSpec javaX25519AlgorithmSpec - = getJavaX25519ParameterSpec(); + private static final AlgorithmParameterSpec javaX25519AlgorithmSpec = + getJavaX25519ParameterSpec(); public OpenSSLXDHKeyFactory() {} @@ -80,7 +80,7 @@ protected T engineGetKeySpec(Key key, Class keySpec) throw new InvalidKeySpecException("keySpec == null"); } // Support XDH or X25519 algorithm names per JEP 324 - if (!"XDH".equals(key.getAlgorithm()) && !"X25519".equals(key.getAlgorithm()) ) { + if (!"XDH".equals(key.getAlgorithm()) && !"X25519".equals(key.getAlgorithm())) { throw new InvalidKeySpecException("Key must be an XDH or X25519 key"); } if (key.getEncoded() == null) { @@ -105,8 +105,7 @@ protected T engineGetKeySpec(Key key, Class keySpec) T result = (T) new X509EncodedKeySpec(key.getEncoded()); return result; } else if (keySpec == XdhKeySpec.class) { - @SuppressWarnings("unchecked") - T result = (T) new XdhKeySpec(conscryptKey.getU()); + @SuppressWarnings("unchecked") T result = (T) new XdhKeySpec(conscryptKey.getU()); return result; } else if (EncodedKeySpec.class.isAssignableFrom(keySpec)) { return KeySpecUtil.makeRawKeySpec(conscryptKey.getU(), keySpec); @@ -122,15 +121,15 @@ protected T engineGetKeySpec(Key key, Class keySpec) T result = (T) new PKCS8EncodedKeySpec(key.getEncoded()); return result; } else if (keySpec == XdhKeySpec.class) { - @SuppressWarnings("unchecked") - T result = (T) new XdhKeySpec(conscryptKey.getU()); + @SuppressWarnings("unchecked") T result = (T) new XdhKeySpec(conscryptKey.getU()); return result; } else if (EncodedKeySpec.class.isAssignableFrom(keySpec)) { return KeySpecUtil.makeRawKeySpec(conscryptKey.getU(), 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 @@ -162,7 +161,7 @@ protected Key engineTranslateKey(Key key) throws InvalidKeyException { } } else { throw new InvalidKeyException("Key must be XEC public or private key; was " - + key.getClass().getName()); + + key.getClass().getName()); } } @@ -174,40 +173,41 @@ private static Class getJavaXECPrivateKeySpec() { } } - private static Class getJavaXECPublicKeySpec() { - try { - return Class.forName("java.security.spec.XECPublicKeySpec"); - } catch (ClassNotFoundException ignored) { - return null; + private static Class getJavaXECPublicKeySpec() { + try { + return Class.forName("java.security.spec.XECPublicKeySpec"); + } catch (ClassNotFoundException ignored) { + return null; + } } - } - private static AlgorithmParameterSpec getJavaX25519ParameterSpec() { - try { - Class cls = Class.forName("java.security.spec.NamedParameterSpec"); - Field field = cls.getDeclaredField("X25519"); - Object result = field.get(null); - return (AlgorithmParameterSpec) result; - } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException ignored) { - return null; + private static AlgorithmParameterSpec getJavaX25519ParameterSpec() { + try { + Class cls = Class.forName("java.security.spec.NamedParameterSpec"); + Field field = cls.getDeclaredField("X25519"); + Object result = field.get(null); + return (AlgorithmParameterSpec) result; + } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException ignored) { + return null; + } } - } - private KeySpec constructJavaPrivateKeySpec(OpenSSLX25519PrivateKey privateKey) + private KeySpec constructJavaPrivateKeySpec(OpenSSLX25519PrivateKey privateKey) throws InvalidKeySpecException { - if (OpenSSLXDHKeyFactory.javaXecPrivateKeySpec == null) { - throw new InvalidKeySpecException("Could not find java.security.spec.XECPrivateKeySpec"); - } - try { + if (OpenSSLXDHKeyFactory.javaXecPrivateKeySpec == null) { + throw new InvalidKeySpecException( + "Could not find java.security.spec.XECPrivateKeySpec"); + } + try { Constructor c = OpenSSLXDHKeyFactory.javaXecPrivateKeySpec.getConstructor( AlgorithmParameterSpec.class, byte[].class); @SuppressWarnings("unchecked") KeySpec result = (KeySpec) c.newInstance(javaX25519AlgorithmSpec, privateKey.getU()); return result; - } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | - InvocationTargetException e) { - throw new InvalidKeySpecException( - "Could not find java.security.spec.XECPrivateKeySpec", e); + } catch (NoSuchMethodException | InstantiationException | IllegalAccessException + | InvocationTargetException e) { + throw new InvalidKeySpecException("Could not find java.security.spec.XECPrivateKeySpec", + e); } } @@ -227,13 +227,13 @@ private KeySpec constructJavaXecPublicKeySpec(OpenSSLX25519PublicKey publicKey) Constructor c = OpenSSLXDHKeyFactory.javaXecPublicKeySpec.getConstructor( AlgorithmParameterSpec.class, BigInteger.class); @SuppressWarnings("unchecked") - KeySpec result = (KeySpec) c.newInstance( - javaX25519AlgorithmSpec, uToBigInteger(publicKey.getU())); + KeySpec result = (KeySpec) c.newInstance(javaX25519AlgorithmSpec, + uToBigInteger(publicKey.getU())); return result; - } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | - InvocationTargetException e) { - throw new InvalidKeySpecException( - "Could not find java.security.spec.XECPublicKeySpec", e); + } catch (NoSuchMethodException | InstantiationException | IllegalAccessException + | InvocationTargetException e) { + throw new InvalidKeySpecException("Could not find java.security.spec.XECPublicKeySpec", + e); } } } diff --git a/common/src/main/java/org/conscrypt/OpenSSLXDHKeyPairGenerator.java b/common/src/main/java/org/conscrypt/OpenSSLXDHKeyPairGenerator.java index bff2ca66a..2e0e9554b 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLXDHKeyPairGenerator.java +++ b/common/src/main/java/org/conscrypt/OpenSSLXDHKeyPairGenerator.java @@ -42,7 +42,7 @@ public KeyPair generateKeyPair() { NativeCrypto.X25519_keypair(publicKeyBytes, privateKeyBytes); return new KeyPair(new OpenSSLX25519PublicKey(publicKeyBytes), - new OpenSSLX25519PrivateKey(privateKeyBytes)); + new OpenSSLX25519PrivateKey(privateKeyBytes)); } @Override diff --git a/common/src/main/java/org/conscrypt/OpenSslEdDsaKeyFactory.java b/common/src/main/java/org/conscrypt/OpenSslEdDsaKeyFactory.java index 3578c4117..9c0a3cdc5 100644 --- a/common/src/main/java/org/conscrypt/OpenSslEdDsaKeyFactory.java +++ b/common/src/main/java/org/conscrypt/OpenSslEdDsaKeyFactory.java @@ -41,7 +41,7 @@ protected PublicKey engineGeneratePublic(KeySpec keySpec) throws InvalidKeySpecE return new OpenSslEdDsaPublicKey((EncodedKeySpec) keySpec); } throw new InvalidKeySpecException("Must use X509EncodedKeySpec or Raw EncodedKeySpec; was " - + keySpec.getClass().getName()); + + keySpec.getClass().getName()); } @Override @@ -53,7 +53,7 @@ protected PrivateKey engineGeneratePrivate(KeySpec keySpec) throws InvalidKeySpe return new OpenSslEdDsaPrivateKey((EncodedKeySpec) keySpec); } throw new InvalidKeySpecException("Must use PKCS8EncodedKeySpec or Raw EncodedKeySpec; was " - + keySpec.getClass().getName()); + + keySpec.getClass().getName()); } @Override @@ -66,7 +66,7 @@ protected T engineGetKeySpec(Key key, Class keySpec) throw new InvalidKeySpecException("keySpec == null"); } if (!key.getAlgorithm().equals("EdDSA") && !key.getAlgorithm().equals("Ed25519") - && !key.getAlgorithm().equals("1.3.101.112")) { + && !key.getAlgorithm().equals("1.3.101.112")) { throw new InvalidKeySpecException("Key must be an EdDSA or Ed25519 key"); } if (key.getEncoded() == null) { @@ -100,7 +100,8 @@ protected T engineGetKeySpec(Key key, Class 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 @@ -131,8 +132,8 @@ protected Key engineTranslateKey(Key key) throws InvalidKeyException { throw new InvalidKeyException(e); } } else { - throw new InvalidKeyException( - "Key must be XEC public or private key; was " + key.getClass().getName()); + throw new InvalidKeyException("Key must be XEC public or private key; was " + + key.getClass().getName()); } } } diff --git a/common/src/main/java/org/conscrypt/OpenSslEdDsaKeyPairGenerator.java b/common/src/main/java/org/conscrypt/OpenSslEdDsaKeyPairGenerator.java index 2938e5244..fd081d16d 100644 --- a/common/src/main/java/org/conscrypt/OpenSslEdDsaKeyPairGenerator.java +++ b/common/src/main/java/org/conscrypt/OpenSslEdDsaKeyPairGenerator.java @@ -46,7 +46,7 @@ public KeyPair generateKeyPair() { byte[] privateKeySeed = Arrays.copyOf(privateKeyBytes, 32); return new KeyPair(new OpenSslEdDsaPublicKey(publicKeyBytes), - new OpenSslEdDsaPrivateKey(privateKeySeed)); + new OpenSslEdDsaPrivateKey(privateKeySeed)); } @Override diff --git a/common/src/main/java/org/conscrypt/OpenSslMlDsaKeyFactory.java b/common/src/main/java/org/conscrypt/OpenSslMlDsaKeyFactory.java index 521a2e0f2..7c22b6f1b 100644 --- a/common/src/main/java/org/conscrypt/OpenSslMlDsaKeyFactory.java +++ b/common/src/main/java/org/conscrypt/OpenSslMlDsaKeyFactory.java @@ -130,7 +130,7 @@ protected PublicKey engineGeneratePublic(KeySpec keySpec) throws InvalidKeySpecE } if (!(keySpec instanceof EncodedKeySpec)) { throw new InvalidKeySpecException("Currently only EncodedKeySpec is supported; was " - + keySpec.getClass().getName()); + + keySpec.getClass().getName()); } EncodedKeySpec encodedKeySpec = (EncodedKeySpec) keySpec; if (encodedKeySpec.getFormat().equalsIgnoreCase("raw")) { @@ -142,10 +142,10 @@ protected PublicKey engineGeneratePublic(KeySpec keySpec) throws InvalidKeySpecE } byte[] encoded = encodedKeySpec.getEncoded(); try { - OpenSSLKey key = - new OpenSSLKey(NativeCrypto.EVP_PKEY_from_subject_public_key_info(encoded, - new int[] {NativeConstants.EVP_PKEY_ML_DSA_65, - NativeConstants.EVP_PKEY_ML_DSA_87})); + OpenSSLKey key = new OpenSSLKey(NativeCrypto.EVP_PKEY_from_subject_public_key_info( + encoded, + new int[] {NativeConstants.EVP_PKEY_ML_DSA_65, + NativeConstants.EVP_PKEY_ML_DSA_87})); return makePublicKey(key); } catch (OpenSSLX509CertificateFactory.ParsingException e) { throw new InvalidKeySpecException( @@ -188,7 +188,7 @@ protected PrivateKey engineGeneratePrivate(KeySpec keySpec) throws InvalidKeySpe } if (!(keySpec instanceof EncodedKeySpec)) { throw new InvalidKeySpecException("Currently only EncodedKeySpec is supported; was " - + keySpec.getClass().getName()); + + keySpec.getClass().getName()); } EncodedKeySpec encodedKeySpec = (EncodedKeySpec) keySpec; if (encodedKeySpec.getFormat().equalsIgnoreCase("raw")) { @@ -201,9 +201,10 @@ protected PrivateKey engineGeneratePrivate(KeySpec keySpec) throws InvalidKeySpe byte[] encoded = encodedKeySpec.getEncoded(); try { - OpenSSLKey key = new OpenSSLKey(NativeCrypto.EVP_PKEY_from_private_key_info(encoded, + OpenSSLKey key = new OpenSSLKey(NativeCrypto.EVP_PKEY_from_private_key_info( + encoded, new int[] {NativeConstants.EVP_PKEY_ML_DSA_65, - NativeConstants.EVP_PKEY_ML_DSA_87})); + NativeConstants.EVP_PKEY_ML_DSA_87})); return makePrivateKey(key); } catch (OpenSSLX509CertificateFactory.ParsingException e) { throw new InvalidKeySpecException( @@ -252,7 +253,8 @@ protected T engineGetKeySpec(Key key, Class 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 diff --git a/common/src/main/java/org/conscrypt/OpenSslMlDsaKeyPairGenerator.java b/common/src/main/java/org/conscrypt/OpenSslMlDsaKeyPairGenerator.java index c43dc0aec..4631443c9 100644 --- a/common/src/main/java/org/conscrypt/OpenSslMlDsaKeyPairGenerator.java +++ b/common/src/main/java/org/conscrypt/OpenSslMlDsaKeyPairGenerator.java @@ -46,7 +46,8 @@ public KeyPair generateKeyPair() { byte[] privateKeyBytes = new byte[32]; NativeCrypto.RAND_bytes(privateKeyBytes); byte[] publicKeyBytes = NativeCrypto.MLDSA65_public_key_from_seed(privateKeyBytes); - return new KeyPair(new OpenSslMlDsaPublicKey(publicKeyBytes, MlDsaAlgorithm.ML_DSA_65), + return new KeyPair( + new OpenSslMlDsaPublicKey(publicKeyBytes, MlDsaAlgorithm.ML_DSA_65), new OpenSslMlDsaPrivateKey(privateKeyBytes, MlDsaAlgorithm.ML_DSA_65)); } } @@ -69,7 +70,8 @@ public KeyPair generateKeyPair() { byte[] privateKeyBytes = new byte[32]; NativeCrypto.RAND_bytes(privateKeyBytes); byte[] publicKeyBytes = NativeCrypto.MLDSA87_public_key_from_seed(privateKeyBytes); - return new KeyPair(new OpenSslMlDsaPublicKey(publicKeyBytes, MlDsaAlgorithm.ML_DSA_87), + return new KeyPair( + new OpenSslMlDsaPublicKey(publicKeyBytes, MlDsaAlgorithm.ML_DSA_87), new OpenSslMlDsaPrivateKey(privateKeyBytes, MlDsaAlgorithm.ML_DSA_87)); } } diff --git a/common/src/main/java/org/conscrypt/OpenSslMlDsaPrivateKey.java b/common/src/main/java/org/conscrypt/OpenSslMlDsaPrivateKey.java index 094220388..f7237d048 100644 --- a/common/src/main/java/org/conscrypt/OpenSslMlDsaPrivateKey.java +++ b/common/src/main/java/org/conscrypt/OpenSslMlDsaPrivateKey.java @@ -83,7 +83,7 @@ private static byte[] encodeSeed(byte[] unencodedSeed, MlDsaAlgorithm algorithm) OpenSslMlDsaPrivateKey(OpenSSLKey key, MlDsaAlgorithm algorithm) { if (NativeCrypto.EVP_PKEY_type(key.getNativeRef()) - != OpenSslMlDsaKeyFactory.getPKeyType(algorithm)) { + != OpenSslMlDsaKeyFactory.getPKeyType(algorithm)) { throw new IllegalArgumentException("Invalid key type"); } this.algorithm = algorithm; diff --git a/common/src/main/java/org/conscrypt/OpenSslMlDsaPublicKey.java b/common/src/main/java/org/conscrypt/OpenSslMlDsaPublicKey.java index 31e3aecf3..cc0bb0c44 100644 --- a/common/src/main/java/org/conscrypt/OpenSslMlDsaPublicKey.java +++ b/common/src/main/java/org/conscrypt/OpenSslMlDsaPublicKey.java @@ -54,7 +54,7 @@ private static OpenSSLKey getOpenSslKeyFromRaw(byte[] raw, MlDsaAlgorithm algori OpenSslMlDsaPublicKey(OpenSSLKey key, MlDsaAlgorithm algorithm) { if (NativeCrypto.EVP_PKEY_type(key.getNativeRef()) - != OpenSslMlDsaKeyFactory.getPKeyType(algorithm)) { + != OpenSslMlDsaKeyFactory.getPKeyType(algorithm)) { throw new IllegalArgumentException("Invalid key type"); } this.algorithm = algorithm; diff --git a/common/src/main/java/org/conscrypt/OpenSslSignatureEdDsa.java b/common/src/main/java/org/conscrypt/OpenSslSignatureEdDsa.java index b0fd4e7ee..c085b20e2 100644 --- a/common/src/main/java/org/conscrypt/OpenSslSignatureEdDsa.java +++ b/common/src/main/java/org/conscrypt/OpenSslSignatureEdDsa.java @@ -105,8 +105,8 @@ protected boolean engineVerify(byte[] sigBytes) throws SignatureException { throw new SignatureException("No key provided"); } - boolean result = NativeCrypto.EVP_DigestVerify( - ctxLocal, sigBytes, 0, sigBytes.length, buffer.array(), 0, buffer.size()); + boolean result = NativeCrypto.EVP_DigestVerify(ctxLocal, sigBytes, 0, sigBytes.length, + buffer.array(), 0, buffer.size()); buffer.reset(); return result; } diff --git a/common/src/main/java/org/conscrypt/OpenSslSignatureMlDsa.java b/common/src/main/java/org/conscrypt/OpenSslSignatureMlDsa.java index d1bc72720..357d4bff3 100644 --- a/common/src/main/java/org/conscrypt/OpenSslSignatureMlDsa.java +++ b/common/src/main/java/org/conscrypt/OpenSslSignatureMlDsa.java @@ -147,8 +147,8 @@ protected boolean engineVerify(byte[] sigBytes) throws SignatureException { throw new SignatureException("No key provided"); } - boolean result = NativeCrypto.EVP_DigestVerify( - ctxLocal, sigBytes, 0, sigBytes.length, buffer.array(), 0, buffer.size()); + boolean result = NativeCrypto.EVP_DigestVerify(ctxLocal, sigBytes, 0, sigBytes.length, + buffer.array(), 0, buffer.size()); buffer.reset(); return result; } diff --git a/common/src/main/java/org/conscrypt/OpenSslSignatureSlhDsa.java b/common/src/main/java/org/conscrypt/OpenSslSignatureSlhDsa.java index 008f3c6eb..483bf4f0a 100644 --- a/common/src/main/java/org/conscrypt/OpenSslSignatureSlhDsa.java +++ b/common/src/main/java/org/conscrypt/OpenSslSignatureSlhDsa.java @@ -78,8 +78,8 @@ protected byte[] engineSign() throws SignatureException { // This should not happen. throw new SignatureException("No privateKey provided"); } - byte[] sig = NativeCrypto.SLHDSA_SHA2_128S_sign( - buffer.array(), buffer.size(), privateKey.getRaw()); + byte[] sig = NativeCrypto.SLHDSA_SHA2_128S_sign(buffer.array(), buffer.size(), + privateKey.getRaw()); buffer.reset(); return sig; } @@ -90,8 +90,8 @@ protected boolean engineVerify(byte[] sigBytes) throws SignatureException { // This should not happen. throw new SignatureException("No publicKey provided"); } - int result = NativeCrypto.SLHDSA_SHA2_128S_verify( - buffer.array(), buffer.size(), sigBytes, publicKey.getRaw()); + int result = NativeCrypto.SLHDSA_SHA2_128S_verify(buffer.array(), buffer.size(), sigBytes, + publicKey.getRaw()); buffer.reset(); return result == 1; } diff --git a/common/src/main/java/org/conscrypt/OpenSslSlhDsaKeyFactory.java b/common/src/main/java/org/conscrypt/OpenSslSlhDsaKeyFactory.java index a30eba051..6cd9a6723 100644 --- a/common/src/main/java/org/conscrypt/OpenSslSlhDsaKeyFactory.java +++ b/common/src/main/java/org/conscrypt/OpenSslSlhDsaKeyFactory.java @@ -40,8 +40,8 @@ protected PublicKey engineGeneratePublic(KeySpec keySpec) throws InvalidKeySpecE if (keySpec instanceof EncodedKeySpec) { return new OpenSslSlhDsaPublicKey((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 OpenSslSlhDsaPrivateKey((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 @@ -83,7 +83,8 @@ protected T engineGetKeySpec(Key key, Class 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 diff --git a/common/src/main/java/org/conscrypt/OpenSslSlhDsaKeyPairGenerator.java b/common/src/main/java/org/conscrypt/OpenSslSlhDsaKeyPairGenerator.java index 521f71408..0b4952704 100644 --- a/common/src/main/java/org/conscrypt/OpenSslSlhDsaKeyPairGenerator.java +++ b/common/src/main/java/org/conscrypt/OpenSslSlhDsaKeyPairGenerator.java @@ -46,6 +46,6 @@ public KeyPair generateKeyPair() { NativeCrypto.SLHDSA_SHA2_128S_generate_key(publicKeyBytes, privateKeyBytes); return new KeyPair(new OpenSslSlhDsaPublicKey(publicKeyBytes), - new OpenSslSlhDsaPrivateKey(privateKeyBytes)); + new OpenSslSlhDsaPrivateKey(privateKeyBytes)); } } diff --git a/common/src/main/java/org/conscrypt/OpenSslXwingKeyFactory.java b/common/src/main/java/org/conscrypt/OpenSslXwingKeyFactory.java index b8bdaa95e..aaa0f9301 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 @@ -90,7 +90,8 @@ protected T engineGetKeySpec(Key key, Class 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 diff --git a/common/src/main/java/org/conscrypt/OpenSslXwingKeyPairGenerator.java b/common/src/main/java/org/conscrypt/OpenSslXwingKeyPairGenerator.java index 8e8780b02..464292fb7 100644 --- a/common/src/main/java/org/conscrypt/OpenSslXwingKeyPairGenerator.java +++ b/common/src/main/java/org/conscrypt/OpenSslXwingKeyPairGenerator.java @@ -43,6 +43,6 @@ public KeyPair generateKeyPair() { NativeCrypto.RAND_bytes(privateKeyBytes); byte[] publicKeyBytes = NativeCrypto.XWING_public_key_from_seed(privateKeyBytes); return new KeyPair(new OpenSslXwingPublicKey(publicKeyBytes), - new OpenSslXwingPrivateKey(privateKeyBytes)); + new OpenSslXwingPrivateKey(privateKeyBytes)); } } diff --git a/common/src/main/java/org/conscrypt/OpenSslXwingPrivateKey.java b/common/src/main/java/org/conscrypt/OpenSslXwingPrivateKey.java index 059e12ebb..1b52c7b71 100644 --- a/common/src/main/java/org/conscrypt/OpenSslXwingPrivateKey.java +++ b/common/src/main/java/org/conscrypt/OpenSslXwingPrivateKey.java @@ -33,28 +33,9 @@ public class OpenSslXwingPrivateKey implements PrivateKey { // 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, + 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; diff --git a/common/src/main/java/org/conscrypt/OpenSslXwingPublicKey.java b/common/src/main/java/org/conscrypt/OpenSslXwingPublicKey.java index bfd1b26e2..1210a3c85 100644 --- a/common/src/main/java/org/conscrypt/OpenSslXwingPublicKey.java +++ b/common/src/main/java/org/conscrypt/OpenSslXwingPublicKey.java @@ -32,30 +32,10 @@ public class OpenSslXwingPublicKey implements PublicKey { // 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, + 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; diff --git a/common/src/main/java/org/conscrypt/PSKKeyManager.java b/common/src/main/java/org/conscrypt/PSKKeyManager.java index b998189ca..a32ed0fb1 100644 --- a/common/src/main/java/org/conscrypt/PSKKeyManager.java +++ b/common/src/main/java/org/conscrypt/PSKKeyManager.java @@ -17,6 +17,7 @@ package org.conscrypt; import java.net.Socket; + import javax.crypto.SecretKey; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLEngine; @@ -99,7 +100,6 @@ @Deprecated @Internal public interface PSKKeyManager extends KeyManager { - /** * Maximum supported length (in bytes) for PSK identity hint (in modified UTF-8 representation). */ diff --git a/common/src/main/java/org/conscrypt/PSSParameters.java b/common/src/main/java/org/conscrypt/PSSParameters.java index e5759e1f8..40986ae71 100644 --- a/common/src/main/java/org/conscrypt/PSSParameters.java +++ b/common/src/main/java/org/conscrypt/PSSParameters.java @@ -29,7 +29,6 @@ */ @Internal public class PSSParameters extends AlgorithmParametersSpi { - private PSSParameterSpec spec = PSSParameterSpec.DEFAULT; public PSSParameters() {} @@ -79,11 +78,11 @@ protected void engineInit(byte[] bytes) throws IOException { } if (!NativeCrypto.asn1_read_is_empty(seqRef) - || !NativeCrypto.asn1_read_is_empty(readRef)) { + || !NativeCrypto.asn1_read_is_empty(readRef)) { throw new IOException("Error reading ASN.1 encoding"); } this.spec = new PSSParameterSpec(hash, "MGF1", new MGF1ParameterSpec(mgfHash), - saltLength, 1); + saltLength, 1); } finally { NativeCrypto.asn1_read_free(seqRef); NativeCrypto.asn1_read_free(readRef); @@ -118,7 +117,7 @@ protected byte[] engineGetEncoded() throws IOException { cbbRef = NativeCrypto.asn1_write_init(); seqRef = NativeCrypto.asn1_write_sequence(cbbRef); OAEPParameters.writeHashAndMgfHash(seqRef, spec.getDigestAlgorithm(), - (MGF1ParameterSpec) spec.getMGFParameters()); + (MGF1ParameterSpec) spec.getMGFParameters()); // Implementations are prohibited from writing the default value for any of the fields if (spec.getSaltLength() != 20) { long tagRef = 0; diff --git a/common/src/main/java/org/conscrypt/Preconditions.java b/common/src/main/java/org/conscrypt/Preconditions.java index 39fe712c5..10adcf5b5 100644 --- a/common/src/main/java/org/conscrypt/Preconditions.java +++ b/common/src/main/java/org/conscrypt/Preconditions.java @@ -71,10 +71,12 @@ static void checkArgument(boolean condition, String errorMessageTemplate, Object * or string of size {@code size}, and are in order. A position index may range from zero to * {@code size}, inclusive. * - * @param start a user-supplied index identifying a starting position in an array, list or string + * @param start a user-supplied index identifying a starting position in an array, list or + * string * @param end a user-supplied index identifying a ending position in an array, list or string * @param size the size of that array, list or string - * @throws IndexOutOfBoundsException if either index is negative or is greater than {@code size}, + * @throws IndexOutOfBoundsException if either index is negative or is greater than {@code + * size}, * or if {@code end} is less than {@code start} * @throws IllegalArgumentException if {@code size} is negative */ diff --git a/common/src/main/java/org/conscrypt/SSLNullSession.java b/common/src/main/java/org/conscrypt/SSLNullSession.java index 69d6337a3..9a808cfdb 100644 --- a/common/src/main/java/org/conscrypt/SSLNullSession.java +++ b/common/src/main/java/org/conscrypt/SSLNullSession.java @@ -22,6 +22,7 @@ import java.security.cert.X509Certificate; import java.util.Collections; import java.util.List; + import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSessionContext; @@ -76,7 +77,7 @@ public int getApplicationBufferSize() { } @Override - public String getApplicationProtocol() { + public String getApplicationProtocol() { return null; } @@ -165,8 +166,7 @@ public String[] getValueNames() { } @Override - public void invalidate() { - } + public void invalidate() {} @Override public boolean isValid() { diff --git a/common/src/main/java/org/conscrypt/SSLParametersImpl.java b/common/src/main/java/org/conscrypt/SSLParametersImpl.java index f78b8691b..e1bb9e4de 100644 --- a/common/src/main/java/org/conscrypt/SSLParametersImpl.java +++ b/common/src/main/java/org/conscrypt/SSLParametersImpl.java @@ -29,6 +29,7 @@ import java.util.Collection; import java.util.List; import java.util.Set; + import javax.crypto.SecretKey; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; @@ -48,7 +49,6 @@ * socket or not. */ final class SSLParametersImpl implements Cloneable { - // default source of X.509 certificate based authentication keys private static volatile X509KeyManager defaultX509KeyManager; // default source of X.509 certificate based authentication trust decisions @@ -125,9 +125,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; @@ -174,14 +174,15 @@ final class SSLParametersImpl implements Cloneable { } else if (protocols == null) { enabledProtocols = NativeCrypto.getDefaultProtocols().clone(); } else { - 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(); } @@ -201,10 +202,12 @@ 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; @@ -254,12 +257,8 @@ 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 +318,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 +331,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 +351,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 +394,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; } @@ -521,7 +521,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 +579,7 @@ private boolean isSniEnabledByDefault() { */ interface AliasChooser { String chooseClientAlias(X509KeyManager keyManager, X500Principal[] issuers, - String[] keyTypes); + String[] keyTypes); String chooseServerAlias(X509KeyManager keyManager, String keyType); } @@ -610,12 +610,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 +635,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 +653,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 +666,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 +702,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 +712,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 +782,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,9 +805,8 @@ 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}; diff --git a/common/src/main/java/org/conscrypt/SSLUtils.java b/common/src/main/java/org/conscrypt/SSLUtils.java index 39eb05a42..71852b894 100644 --- a/common/src/main/java/org/conscrypt/SSLUtils.java +++ b/common/src/main/java/org/conscrypt/SSLUtils.java @@ -32,8 +32,6 @@ package org.conscrypt; -import static java.lang.Math.min; -import static java.nio.charset.StandardCharsets.US_ASCII; import static org.conscrypt.NativeConstants.SSL3_RT_ALERT; import static org.conscrypt.NativeConstants.SSL3_RT_APPLICATION_DATA; import static org.conscrypt.NativeConstants.SSL3_RT_CHANGE_CIPHER_SPEC; @@ -41,6 +39,9 @@ import static org.conscrypt.NativeConstants.SSL3_RT_HEADER_LENGTH; import static org.conscrypt.NativeConstants.SSL3_RT_MAX_PACKET_SIZE; +import static java.lang.Math.min; +import static java.nio.charset.StandardCharsets.US_ASCII; + import java.io.ByteArrayInputStream; import java.nio.ByteBuffer; import java.security.cert.CertificateEncodingException; @@ -50,6 +51,7 @@ import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; + import javax.net.ssl.SSLException; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLPeerUnverifiedException; @@ -121,9 +123,9 @@ private EngineStates() {} static final int STATE_HANDSHAKE_COMPLETED = 3; /** - * The handshake call returned but the listeners have not yet been notified. This is expected - * behaviour in cut-through mode, where SSL_do_handshake returns before the handshake is - * complete. We can now start writing data to the socket. + * The handshake call returned but the listeners have not yet been notified. This is + * expected behaviour in cut-through mode, where SSL_do_handshake returns before the + * handshake is complete. We can now start writing data to the socket. */ static final int STATE_READY_HANDSHAKE_CUT_THROUGH = 4; @@ -195,7 +197,8 @@ private static CertificateFactory getCertificateFactory() { } private static X509Certificate decodeX509Certificate(CertificateFactory certificateFactory, - byte[] bytes) throws java.security.cert.CertificateException { + byte[] bytes) + throws java.security.cert.CertificateException { if (certificateFactory != null) { return (X509Certificate) certificateFactory.generateCertificate( new ByteArrayInputStream(bytes)); @@ -259,10 +262,12 @@ static String getClientKeyTypeFromSignatureAlg(int signatureAlg) { * * @param clientCertificateTypes * {@code ClientCertificateType} values provided by the server. - * See https://www.ietf.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-2. + * See + * https://www.ietf.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-2. * @param signatureAlgs * {@code SignatureScheme} values provided by the server. - * See https://www.ietf.org/assignments/tls-parameters/tls-parameters.xml#tls-signaturescheme + * See + * https://www.ietf.org/assignments/tls-parameters/tls-parameters.xml#tls-signaturescheme * @return supported key types that can be used in {@code X509KeyManager.chooseClientAlias} and * {@code X509ExtendedKeyManager.chooseEngineClientAlias}. If the inputs imply a preference * order, the returned set will have an iteration order that respects that preference order, @@ -271,7 +276,7 @@ static String getClientKeyTypeFromSignatureAlg(int signatureAlg) { * Visible for testing. */ static Set getSupportedClientKeyTypes(byte[] clientCertificateTypes, - int[] signatureAlgs) { + int[] signatureAlgs) { Set fromClientCerts = new HashSet<>(clientCertificateTypes.length); for (byte keyTypeCode : clientCertificateTypes) { String keyType = SSLUtils.getClientKeyType(keyTypeCode); @@ -340,7 +345,8 @@ static javax.security.cert.X509Certificate[] toCertificateChain(X509Certificate[ * plaintext source bytes. */ static int calculateOutNetBufSize(int pendingBytes) { - return min(SSL3_RT_MAX_PACKET_SIZE, + return min( + SSL3_RT_MAX_PACKET_SIZE, MAX_ENCRYPTION_OVERHEAD_LENGTH + min(MAX_ENCRYPTION_OVERHEAD_DIFF, pendingBytes)); } @@ -395,10 +401,11 @@ static String[] decodeProtocols(byte[] protocols) { for (int i = 0; i < protocols.length;) { int protocolLength = protocols[i]; if (protocolLength < 0 || protocolLength > protocols.length - i) { - throw new IllegalArgumentException( - "Protocol has invalid length (" + protocolLength + " at position " + i - + "): " + (protocols.length < 50 - ? Arrays.toString(protocols) : protocols.length + " byte array")); + throw new IllegalArgumentException("Protocol has invalid length (" + protocolLength + + " at position " + i + "): " + + (protocols.length < 50 + ? Arrays.toString(protocols) + : protocols.length + " byte array")); } numProtocols++; @@ -447,8 +454,8 @@ static byte[] encodeProtocols(String[] protocols) { // Verify that the length is valid here, so that we don't attempt to allocate an array // below if the threshold is violated. if (protocolLength == 0 || protocolLength > MAX_PROTOCOL_LENGTH) { - throw new IllegalArgumentException( - "protocol[" + i + "] has invalid length: " + protocolLength); + throw new IllegalArgumentException("protocol[" + i + + "] has invalid length: " + protocolLength); } // Include a 1-byte prefix for each protocol. @@ -466,8 +473,8 @@ static byte[] encodeProtocols(String[] protocols) { char c = protocol.charAt(ci); if (c > Byte.MAX_VALUE) { // Enforce US-ASCII - throw new IllegalArgumentException("Protocol contains invalid character: " - + c + "(protocol=" + protocol + ")"); + throw new IllegalArgumentException("Protocol contains invalid character: " + c + + "(protocol=" + protocol + ")"); } data[dataIndex++] = (byte) c; } diff --git a/common/src/main/java/org/conscrypt/ScryptKeySpec.java b/common/src/main/java/org/conscrypt/ScryptKeySpec.java index 809459fe6..548b6f1d8 100644 --- a/common/src/main/java/org/conscrypt/ScryptKeySpec.java +++ b/common/src/main/java/org/conscrypt/ScryptKeySpec.java @@ -31,13 +31,8 @@ public class ScryptKeySpec implements KeySpec { private final int parallelizationParameter; private final int keyOutputBits; - public ScryptKeySpec( - char[] password, - byte[] salt, - int costParameter, - int blockSize, - int parallelizationParameter, - int keyOutputBits) { + public ScryptKeySpec(char[] password, byte[] salt, int costParameter, int blockSize, + int parallelizationParameter, int keyOutputBits) { this.password = password; this.salt = salt; this.costParameter = costParameter; diff --git a/common/src/main/java/org/conscrypt/ScryptSecretKeyFactory.java b/common/src/main/java/org/conscrypt/ScryptSecretKeyFactory.java index a58cfee38..bf44d5531 100644 --- a/common/src/main/java/org/conscrypt/ScryptSecretKeyFactory.java +++ b/common/src/main/java/org/conscrypt/ScryptSecretKeyFactory.java @@ -22,15 +22,14 @@ 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,9 @@ 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)); + return new ScryptKey(NativeCrypto.Scrypt_generate_key( + new String(password).getBytes(StandardCharsets.UTF_8), salt, n, r, p, + keyOutputBits / 8)); } private Object getValue(KeySpec spec, String methodName) @@ -75,8 +73,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"); diff --git a/common/src/main/java/org/conscrypt/ServerSessionContext.java b/common/src/main/java/org/conscrypt/ServerSessionContext.java index 64fca9a79..f3db4e248 100644 --- a/common/src/main/java/org/conscrypt/ServerSessionContext.java +++ b/common/src/main/java/org/conscrypt/ServerSessionContext.java @@ -42,7 +42,7 @@ public final class ServerSessionContext extends AbstractSessionContext { // sure you don't reuse sessions externalized with i2d_SSL_SESSION // between apps. However our sessions are either in memory or // exported to a app's SSLServerSessionCache. - setSesssionIdContext(new byte[] { ' ' }); + setSesssionIdContext(new byte[] {' '}); } /** diff --git a/common/src/main/java/org/conscrypt/SessionSnapshot.java b/common/src/main/java/org/conscrypt/SessionSnapshot.java index 1fc708c5e..d9e6465a3 100644 --- a/common/src/main/java/org/conscrypt/SessionSnapshot.java +++ b/common/src/main/java/org/conscrypt/SessionSnapshot.java @@ -21,6 +21,7 @@ import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; + import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSessionContext; @@ -143,7 +144,7 @@ public Certificate[] getLocalCertificates() { @Override @SuppressWarnings("deprecation") // Public API public javax.security.cert.X509Certificate[] getPeerCertificateChain() - throws SSLPeerUnverifiedException { + throws SSLPeerUnverifiedException { if (!Platform.isJavaxCertificateSupported()) { throw new UnsupportedOperationException("Use getPeerCertificates() instead"); } diff --git a/common/src/main/java/org/conscrypt/ShortBufferWithoutStackTraceException.java b/common/src/main/java/org/conscrypt/ShortBufferWithoutStackTraceException.java index 13c38d49f..5830bf002 100644 --- a/common/src/main/java/org/conscrypt/ShortBufferWithoutStackTraceException.java +++ b/common/src/main/java/org/conscrypt/ShortBufferWithoutStackTraceException.java @@ -35,7 +35,8 @@ public ShortBufferWithoutStackTraceException(String msg) { super(msg); } - @Override public synchronized Throwable fillInStackTrace() { + @Override + public synchronized Throwable fillInStackTrace() { return this; } } diff --git a/common/src/main/java/org/conscrypt/Spake2PlusKeyManager.java b/common/src/main/java/org/conscrypt/Spake2PlusKeyManager.java index ff490647e..bb324c9ce 100644 --- a/common/src/main/java/org/conscrypt/Spake2PlusKeyManager.java +++ b/common/src/main/java/org/conscrypt/Spake2PlusKeyManager.java @@ -36,7 +36,7 @@ public class Spake2PlusKeyManager implements KeyManager { private final int handshakeLimit; Spake2PlusKeyManager(byte[] context, byte[] password, byte[] idProver, byte[] idVerifier, - boolean isClient, int handshakeLimit) { + boolean isClient, int handshakeLimit) { this.context = context == null ? new byte[0] : context; this.password = password; this.idProver = idProver == null ? new byte[0] : idProver; diff --git a/common/src/main/java/org/conscrypt/TrustManagerFactoryImpl.java b/common/src/main/java/org/conscrypt/TrustManagerFactoryImpl.java index f33316491..232467bc2 100644 --- a/common/src/main/java/org/conscrypt/TrustManagerFactoryImpl.java +++ b/common/src/main/java/org/conscrypt/TrustManagerFactoryImpl.java @@ -37,6 +37,7 @@ import java.security.InvalidAlgorithmParameterException; import java.security.KeyStore; import java.security.KeyStoreException; + import javax.net.ssl.ManagerFactoryParameters; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactorySpi; @@ -49,7 +50,6 @@ */ @Internal public class TrustManagerFactoryImpl extends TrustManagerFactorySpi { - private KeyStore keyStore; /** @@ -70,8 +70,7 @@ public void engineInit(KeyStore ks) throws KeyStoreException { @Override public void engineInit(ManagerFactoryParameters spec) throws InvalidAlgorithmParameterException { - throw new InvalidAlgorithmParameterException( - "ManagerFactoryParameters not supported"); + throw new InvalidAlgorithmParameterException("ManagerFactoryParameters not supported"); } /** @@ -80,9 +79,8 @@ public void engineInit(ManagerFactoryParameters spec) @Override public TrustManager[] engineGetTrustManagers() { if (keyStore == null) { - throw new IllegalStateException( - "TrustManagerFactory is not initialized"); + throw new IllegalStateException("TrustManagerFactory is not initialized"); } - return new TrustManager[] { new TrustManagerImpl(keyStore) }; + return new TrustManager[] {new TrustManagerImpl(keyStore)}; } } diff --git a/common/src/main/java/org/conscrypt/TrustManagerImpl.java b/common/src/main/java/org/conscrypt/TrustManagerImpl.java index bedb2ce24..adb206e5b 100644 --- a/common/src/main/java/org/conscrypt/TrustManagerImpl.java +++ b/common/src/main/java/org/conscrypt/TrustManagerImpl.java @@ -88,8 +88,7 @@ public final class TrustManagerImpl extends X509ExtendedTrustManager { private static final TrustAnchorComparator TRUST_ANCHOR_COMPARATOR = new TrustAnchorComparator(); - private static final Set