summaryrefslogtreecommitdiffstats
path: root/x-net/src
diff options
context:
space:
mode:
authorPeter Hallam <peterhal@google.com>2010-05-03 12:57:15 -0700
committerPeter Hallam <peterhal@google.com>2010-05-04 16:30:12 -0700
commit6b811c5daec1b28e6f63b57f98a032236f2c3cf7 (patch)
treea733f20e87a9739253d495c14d54e7d253e35771 /x-net/src
parent0a98ab45e3566542f2d669eb0ffd28a560d97d28 (diff)
downloadlibcore-6b811c5daec1b28e6f63b57f98a032236f2c3cf7.zip
libcore-6b811c5daec1b28e6f63b57f98a032236f2c3cf7.tar.gz
libcore-6b811c5daec1b28e6f63b57f98a032236f2c3cf7.tar.bz2
Merge awt-kernel, icu, luni-kernel, prefs, security-kernel, x-net into luni
Merge xml except xmlpull and kxml into luni
Diffstat (limited to 'x-net/src')
-rw-r--r--x-net/src/main/java/javax/net/DefaultServerSocketFactory.java49
-rw-r--r--x-net/src/main/java/javax/net/DefaultSocketFactory.java60
-rw-r--r--x-net/src/main/java/javax/net/ServerSocketFactory.java109
-rw-r--r--x-net/src/main/java/javax/net/SocketFactory.java153
-rw-r--r--x-net/src/main/java/javax/net/package.html7
-rw-r--r--x-net/src/main/java/javax/net/ssl/CertPathTrustManagerParameters.java52
-rw-r--r--x-net/src/main/java/javax/net/ssl/DefaultHostnameVerifier.java329
-rw-r--r--x-net/src/main/java/javax/net/ssl/DefaultSSLContext.java124
-rw-r--r--x-net/src/main/java/javax/net/ssl/DefaultSSLServerSocketFactory.java62
-rw-r--r--x-net/src/main/java/javax/net/ssl/DefaultSSLSocketFactory.java76
-rw-r--r--x-net/src/main/java/javax/net/ssl/HandshakeCompletedEvent.java141
-rw-r--r--x-net/src/main/java/javax/net/ssl/HandshakeCompletedListener.java34
-rw-r--r--x-net/src/main/java/javax/net/ssl/HostnameVerifier.java40
-rw-r--r--x-net/src/main/java/javax/net/ssl/HttpsURLConnection.java222
-rw-r--r--x-net/src/main/java/javax/net/ssl/KeyManager.java27
-rw-r--r--x-net/src/main/java/javax/net/ssl/KeyManagerFactory.java233
-rw-r--r--x-net/src/main/java/javax/net/ssl/KeyManagerFactorySpi.java74
-rw-r--r--x-net/src/main/java/javax/net/ssl/KeyStoreBuilderParameters.java79
-rw-r--r--x-net/src/main/java/javax/net/ssl/ManagerFactoryParameters.java27
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLContext.java253
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLContextSpi.java109
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLEngine.java464
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLEngineResult.java172
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLException.java61
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLHandshakeException.java37
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLKeyException.java36
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLPeerUnverifiedException.java38
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLPermission.java58
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLProtocolException.java37
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLServerSocket.java232
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLServerSocketFactory.java103
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLSession.java231
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLSessionBindingEvent.java75
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLSessionBindingListener.java44
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLSessionContext.java82
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLSocket.java299
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLSocketFactory.java147
-rw-r--r--x-net/src/main/java/javax/net/ssl/TrustManager.java28
-rw-r--r--x-net/src/main/java/javax/net/ssl/TrustManagerFactory.java229
-rw-r--r--x-net/src/main/java/javax/net/ssl/TrustManagerFactorySpi.java67
-rw-r--r--x-net/src/main/java/javax/net/ssl/X509ExtendedKeyManager.java76
-rw-r--r--x-net/src/main/java/javax/net/ssl/X509KeyManager.java113
-rw-r--r--x-net/src/main/java/javax/net/ssl/X509TrustManager.java76
-rw-r--r--x-net/src/main/java/javax/net/ssl/package.html20
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/AbstractSessionContext.java221
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/AlertException.java66
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/AlertProtocol.java286
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Appendable.java33
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateMessage.java176
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateRequest.java189
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateVerify.java97
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CipherSuite.java610
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientHandshakeImpl.java629
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientHello.java206
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientKeyExchange.java152
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientSessionContext.java229
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ConnectionState.java169
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ConnectionStateSSLv3.java354
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ConnectionStateTLS.java352
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ContentType.java49
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DHParameters.java108
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DataStream.java42
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DelegatedTask.java65
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DigitalSignature.java254
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/EndOfBufferException.java35
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/EndOfSourceException.java34
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/FileClientSessionCache.java374
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Finished.java82
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Handshake.java89
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/HandshakeIODataStream.java464
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/HandshakeProtocol.java534
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/HelloRequest.java77
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/JSSEProvider.java137
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/KeyManagerFactoryImpl.java133
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/KeyManagerImpl.java186
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Logger.java122
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Message.java74
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/NativeCrypto.java330
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLMessageDigest.java118
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLMessageDigestJDK.java117
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLServerSocketFactoryImpl.java71
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLServerSocketImpl.java163
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSessionImpl.java483
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSignature.java215
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketFactoryImpl.java84
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImpl.java995
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImplWrapper.java203
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/PRF.java201
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ProtocolVersion.java158
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLBufferedInput.java77
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLClientSessionCache.java53
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLContextImpl.java127
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLEngineAppData.java95
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLEngineDataStream.java91
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLEngineImpl.java769
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLInputStream.java125
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLParameters.java440
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLRecordProtocol.java482
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLServerSessionCache.java52
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLSessionImpl.java366
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLStreamedInput.java57
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLv3Constants.java84
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHandshakeImpl.java724
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHello.java137
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHelloDone.java78
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerKeyExchange.java193
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerSessionContext.java137
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/TrustManagerFactoryImpl.java134
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/TrustManagerImpl.java234
-rw-r--r--x-net/src/main/native/org_apache_harmony_xnet_provider_jsse_NativeCrypto.cpp2655
-rw-r--r--x-net/src/main/native/sub.mk21
-rw-r--r--x-net/src/test/impl/java.injected/org/apache/harmony/xnet/provider/jsse/ClientSessionContextTest.java86
-rw-r--r--x-net/src/test/impl/java.injected/org/apache/harmony/xnet/provider/jsse/FakeSession.java114
-rw-r--r--x-net/src/test/impl/java.injected/org/apache/harmony/xnet/provider/jsse/FileClientSessionCacheTest.java57
-rw-r--r--x-net/src/test/java/tests/api/javax/net/AllTests.java37
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ServerSocketFactoryTest.java251
-rw-r--r--x-net/src/test/java/tests/api/javax/net/SocketFactoryTest.java408
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/AllTests.java71
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/CertPathTrustManagerParametersTest.java96
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/CertificatesToPlayWith.java478
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/HandshakeCompletedEventTest.java743
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/HostnameVerifierTest.java213
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/HttpsURLConnectionTest.java498
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/KeyManagerFactory1Test.java634
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/KeyManagerFactory2Test.java287
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/KeyManagerFactorySpiTest.java180
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/KeyStoreBuilderParametersTest.java150
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/SSLContext1Test.java718
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/SSLContext2Test.java323
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/SSLContextSpiTest.java323
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/SSLEngineResultHandshakeStatusTest.java100
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/SSLEngineResultStatusTest.java107
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/SSLEngineResultTest.java259
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/SSLEngineTest.java1929
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/SSLExceptionTest.java211
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/SSLHandshakeExceptionTest.java73
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/SSLKeyExceptionTest.java73
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/SSLPeerUnverifiedExceptionTest.java73
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/SSLPermissionTest.java92
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/SSLProtocolExceptionTest.java73
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/SSLServerSocketFactoryTest.java135
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/SSLServerSocketTest.java614
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/SSLSessionBindingEventTest.java260
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/SSLSessionBindingListenerTest.java103
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/SSLSessionContextTest.java141
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/SSLSessionTest.java895
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/SSLSocketFactoryTest.java178
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/SSLSocketTest.java916
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/TrustManagerFactory1Test.java712
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/TrustManagerFactory2Test.java279
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/TrustManagerFactorySpiTest.java168
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/X509ExtendedKeyManagerTest.java200
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/X509KeyManagerTest.java794
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/X509TrustManagerTest.java258
-rw-r--r--x-net/src/test/java/tests/xnet/AllTests.java34
155 files changed, 0 insertions, 36226 deletions
diff --git a/x-net/src/main/java/javax/net/DefaultServerSocketFactory.java b/x-net/src/main/java/javax/net/DefaultServerSocketFactory.java
deleted file mode 100644
index 9e31be4..0000000
--- a/x-net/src/main/java/javax/net/DefaultServerSocketFactory.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.ServerSocket;
-
-/**
- * Default implementation of {@link javax.net.ServerSocketFactory}
- */
-final class DefaultServerSocketFactory extends ServerSocketFactory {
-
- DefaultServerSocketFactory() {
- super();
- }
-
- @Override
- public ServerSocket createServerSocket(int port) throws IOException {
- return new ServerSocket(port);
- }
-
- @Override
- public ServerSocket createServerSocket(int port, int backlog) throws IOException {
- return new ServerSocket(port, backlog);
- }
-
- @Override
- public ServerSocket createServerSocket(int port, int backlog, InetAddress iAddress)
- throws IOException {
- return new ServerSocket(port, backlog, iAddress);
- }
-
-}
diff --git a/x-net/src/main/java/javax/net/DefaultSocketFactory.java b/x-net/src/main/java/javax/net/DefaultSocketFactory.java
deleted file mode 100644
index 010c720..0000000
--- a/x-net/src/main/java/javax/net/DefaultSocketFactory.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.net.UnknownHostException;
-
-/**
- * Default implementation of {@link javax.net.SocketFactory}
- */
-final class DefaultSocketFactory extends SocketFactory {
-
- DefaultSocketFactory() {
- super();
- }
-
- @Override
- public Socket createSocket() throws IOException {
- return new Socket();
- }
-
- @Override
- public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
- return new Socket(host, port);
- }
-
- @Override
- public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
- throws IOException, UnknownHostException {
- return new Socket(host, port, localHost, localPort);
- }
-
- @Override
- public Socket createSocket(InetAddress host, int port) throws IOException {
- return new Socket(host, port);
- }
-
- @Override
- public Socket createSocket(InetAddress address, int port, InetAddress localAddress,
- int localPort) throws IOException {
- return new Socket(address, port, localAddress, localPort);
- }
-}
diff --git a/x-net/src/main/java/javax/net/ServerSocketFactory.java b/x-net/src/main/java/javax/net/ServerSocketFactory.java
deleted file mode 100644
index f2d2c0d..0000000
--- a/x-net/src/main/java/javax/net/ServerSocketFactory.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.ServerSocket;
-import java.net.SocketException;
-
-/**
- * This abstract class defines methods to create server sockets. It can be
- * subclassed to create specific server socket types.
- */
-public abstract class ServerSocketFactory {
- private static ServerSocketFactory defaultFactory;
-
- /**
- * Gets the default server socket factory of the system which can be used to
- * create new server sockets without creating a subclass of this factory.
- *
- * @return the system default server socket factory.
- */
- public static synchronized ServerSocketFactory getDefault() {
- if (defaultFactory == null) {
- defaultFactory = new DefaultServerSocketFactory();
- }
- return defaultFactory;
- }
-
- /**
- * Creates a new {@code ServerSocketFactory} instance.
- */
- protected ServerSocketFactory() {
- super();
- }
-
- /**
- * Creates a new server socket which is not bound to any local address. This
- * method has to be overridden by a subclass otherwise a {@code
- * SocketException} is thrown.
- *
- * @return the created unbound server socket.
- * @throws IOException
- * if an error occurs while creating a new server socket.
- */
- public ServerSocket createServerSocket() throws IOException {
- // follow RI's behavior
- throw new SocketException("Unbound server sockets not implemented");
- }
-
- /**
- * Creates a new server socket which is bound to the given port.
- *
- * @param port
- * the port on which the created socket has to listen.
- * @return the created bound server socket.
- * @throws IOException
- * if an error occurs while creating a new server socket.
- */
- public abstract ServerSocket createServerSocket(int port) throws IOException;
-
- /**
- * Creates a new server socket which is bound to the given port and
- * configures its maximum of queued connections.
- *
- * @param port
- * the port on which the created socket has to listen.
- * @param backlog
- * the maximum of queued connections.
- * @return the created bound server socket.
- * @throws IOException
- * if an error occurs while creating a new server socket.
- */
- public abstract ServerSocket createServerSocket(int port, int backlog) throws IOException;
-
- /**
- * Creates a new server socket which is bound to the given address on the
- * specified port and configures its maximum of queued connections.
- *
- * @param port
- * the port on which the created socket has to listen.
- * @param backlog
- * the maximum of queued connections.
- * @param iAddress
- * the address of the network interface which is used by the
- * created socket.
- * @return the created bound server socket.
- * @throws IOException
- * if an error occurs while creating a new server socket.
- */
- public abstract ServerSocket createServerSocket(int port, int backlog, InetAddress iAddress)
- throws IOException;
-
-}
diff --git a/x-net/src/main/java/javax/net/SocketFactory.java b/x-net/src/main/java/javax/net/SocketFactory.java
deleted file mode 100644
index eb0cfcb..0000000
--- a/x-net/src/main/java/javax/net/SocketFactory.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.net.SocketException;
-import java.net.UnknownHostException;
-
-/**
- * This abstract class defines methods to create sockets. It can be subclassed
- * to create specific socket types with additional socket-level functionality.
- */
-public abstract class SocketFactory {
-
- private static SocketFactory defaultFactory;
-
- /**
- * Gets the default socket factory of the system which can be used to create
- * new sockets without creating a subclass of this factory.
- *
- * @return the system default socket factory.
- */
- public static synchronized SocketFactory getDefault() {
- if (defaultFactory == null) {
- defaultFactory = new DefaultSocketFactory();
- }
- return defaultFactory;
- }
-
- /**
- * Creates a new {@code SocketFactory} instance.
- */
- protected SocketFactory() {
- super();
- }
-
- /**
- * Creates a new socket which is not connected to any remote host. This
- * method has to be overridden by a subclass otherwise a {@code
- * SocketException} is thrown.
- *
- * @return the created unconnected socket.
- * @throws IOException
- * if an error occurs while creating a new socket.
- */
- public Socket createSocket() throws IOException {
- // follow RI's behavior
- throw new SocketException("Unconnected sockets not implemented");
- }
-
- /**
- * Creates a new socket which is connected to the remote host specified by
- * the parameters {@code host} and {@code port}. The socket is bound to any
- * available local address and port.
- *
- * @param host
- * the remote host address the socket has to be connected to.
- * @param port
- * the port number of the remote host at which the socket is
- * connected.
- * @return the created connected socket.
- * @throws IOException
- * if an error occurs while creating a new socket.
- * @throws UnknownHostException
- * if the specified host is unknown or the IP address could not
- * be resolved.
- */
- public abstract Socket createSocket(String host, int port) throws IOException,
- UnknownHostException;
-
- /**
- * Creates a new socket which is connected to the remote host specified by
- * the parameters {@code host} and {@code port}. The socket is bound to the
- * local network interface specified by the InetAddress {@code localHost} on
- * port {@code localPort}.
- *
- * @param host
- * the remote host address the socket has to be connected to.
- * @param port
- * the port number of the remote host at which the socket is
- * connected.
- * @param localHost
- * the local host address the socket is bound to.
- * @param localPort
- * the port number of the local host at which the socket is
- * bound.
- * @return the created connected socket.
- * @throws IOException
- * if an error occurs while creating a new socket.
- * @throws UnknownHostException
- * if the specified host is unknown or the IP address could not
- * be resolved.
- */
- public abstract Socket createSocket(String host, int port, InetAddress localHost, int localPort)
- throws IOException, UnknownHostException;
-
- /**
- * Creates a new socket which is connected to the remote host specified by
- * the InetAddress {@code host}. The socket is bound to any available local
- * address and port.
- *
- * @param host
- * the host address the socket has to be connected to.
- * @param port
- * the port number of the remote host at which the socket is
- * connected.
- * @return the created connected socket.
- * @throws IOException
- * if an error occurs while creating a new socket.
- */
- public abstract Socket createSocket(InetAddress host, int port) throws IOException;
-
-
- /**
- * Creates a new socket which is connected to the remote host specified by
- * the InetAddress {@code address}. The socket is bound to the local network
- * interface specified by the InetAddress {@code localHost} on port {@code
- * localPort}.
- *
- * @param address
- * the remote host address the socket has to be connected to.
- * @param port
- * the port number of the remote host at which the socket is
- * connected.
- * @param localAddress
- * the local host address the socket is bound to.
- * @param localPort
- * the port number of the local host at which the socket is
- * bound.
- * @return the created connected socket.
- * @throws IOException
- * if an error occurs while creating a new socket.
- */
- public abstract Socket createSocket(InetAddress address, int port, InetAddress localAddress,
- int localPort) throws IOException;
-}
diff --git a/x-net/src/main/java/javax/net/package.html b/x-net/src/main/java/javax/net/package.html
deleted file mode 100644
index 5674d06..0000000
--- a/x-net/src/main/java/javax/net/package.html
+++ /dev/null
@@ -1,7 +0,0 @@
-<html>
- <body>
- <p>
- This package provides factory classes to create sockets and server-sockets. This classes can be subclassed to create factories for other kinds of socket for example the SSL-capable sockets from the package javax.net.ssl.
- </p>
- </body>
-</html>
diff --git a/x-net/src/main/java/javax/net/ssl/CertPathTrustManagerParameters.java b/x-net/src/main/java/javax/net/ssl/CertPathTrustManagerParameters.java
deleted file mode 100644
index dcf7a4d..0000000
--- a/x-net/src/main/java/javax/net/ssl/CertPathTrustManagerParameters.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.security.cert.CertPathParameters;
-
-/**
- * Certification path parameters to provide to certification path
- * based {@link TrustManager}.
- *
- * @since 1.5
- */
-public class CertPathTrustManagerParameters implements ManagerFactoryParameters {
-
- private final CertPathParameters param;
-
- /**
- * Creates a new {@code CertPathTrustManagerParameters} with the specified
- * certification path parameters.
- *
- * @param parameters
- * the certification path parameters.
- */
- public CertPathTrustManagerParameters(CertPathParameters parameters) {
- param = (CertPathParameters) parameters.clone();
- }
-
- /**
- * Returns a copy of the certification path parameters.
- *
- * @return a copy of the certification path parameters.
- */
- public CertPathParameters getParameters() {
- return (CertPathParameters) param.clone();
- }
-
-}
diff --git a/x-net/src/main/java/javax/net/ssl/DefaultHostnameVerifier.java b/x-net/src/main/java/javax/net/ssl/DefaultHostnameVerifier.java
deleted file mode 100644
index 779c46a..0000000
--- a/x-net/src/main/java/javax/net/ssl/DefaultHostnameVerifier.java
+++ /dev/null
@@ -1,329 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// BEGIN android-added
-// Copied and condensed code taken from the Apache HttpClient. Also slightly
-// modified, so it matches the package/class structure of the core libraries.
-// This HostnameVerifier does checking similar to what the RI and popular
-// browsers do.
-// END android-added
-
-package javax.net.ssl;
-
-import org.apache.harmony.luni.util.Inet6Util;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateParsingException;
-import java.security.cert.X509Certificate;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Locale;
-import java.util.StringTokenizer;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSocket;
-
-/**
- * A HostnameVerifier that works the same way as Curl and Firefox.
- * <p/>
- * The hostname must match either the first CN, or any of the subject-alts.
- * A wildcard can occur in the CN, and in any of the subject-alts.
- * <p/>
- * The only difference between BROWSER_COMPATIBLE and STRICT is that a wildcard
- * (such as "*.foo.com") with BROWSER_COMPATIBLE matches all subdomains,
- * including "a.b.foo.com".
- *
- * @author Julius Davies
- */
-class DefaultHostnameVerifier implements HostnameVerifier {
-
- /**
- * This contains a list of 2nd-level domains that aren't allowed to
- * have wildcards when combined with country-codes.
- * For example: [*.co.uk].
- * <p/>
- * The [*.co.uk] problem is an interesting one. Should we just hope
- * that CA's would never foolishly allow such a certificate to happen?
- * Looks like we're the only implementation guarding against this.
- * Firefox, Curl, Sun Java 1.4, 5, 6 don't bother with this check.
- */
- private final static String[] BAD_COUNTRY_2LDS =
- { "ac", "co", "com", "ed", "edu", "go", "gouv", "gov", "info",
- "lg", "ne", "net", "or", "org" };
-
- static {
- // Just in case developer forgot to manually sort the array. :-)
- Arrays.sort(BAD_COUNTRY_2LDS);
- }
-
- public DefaultHostnameVerifier() {
- super();
- }
-
- public final void verify(String host, SSLSocket ssl)
- throws IOException {
- if(host == null) {
- throw new NullPointerException("host to verify is null");
- }
-
- SSLSession session = ssl.getSession();
- Certificate[] certs = session.getPeerCertificates();
- X509Certificate x509 = (X509Certificate) certs[0];
- verify(host, x509);
- }
-
- public final boolean verify(String host, SSLSession session) {
- try {
- Certificate[] certs = session.getPeerCertificates();
- X509Certificate x509 = (X509Certificate) certs[0];
- verify(host, x509);
- return true;
- }
- catch(SSLException e) {
- return false;
- }
- }
-
- public final void verify(String host, X509Certificate cert)
- throws SSLException {
- String[] cns = getCNs(cert);
- String[] subjectAlts = getDNSSubjectAlts(cert);
- verify(host, cns, subjectAlts);
- }
-
- public final void verify(final String host, final String[] cns,
- final String[] subjectAlts,
- final boolean strictWithSubDomains)
- throws SSLException {
-
- // Build the list of names we're going to check. Our DEFAULT and
- // STRICT implementations of the HostnameVerifier only use the
- // first CN provided. All other CNs are ignored.
- // (Firefox, wget, curl, Sun Java 1.4, 5, 6 all work this way).
- LinkedList<String> names = new LinkedList<String>();
- if(cns != null && cns.length > 0 && cns[0] != null) {
- names.add(cns[0]);
- }
- if(subjectAlts != null) {
- for (String subjectAlt : subjectAlts) {
- if (subjectAlt != null) {
- names.add(subjectAlt);
- }
- }
- }
-
- if(names.isEmpty()) {
- String msg = "Certificate for <" + host +
- "> doesn't contain CN or DNS subjectAlt";
- throw new SSLException(msg);
- }
-
- // StringBuffer for building the error message.
- StringBuffer buf = new StringBuffer();
-
- // We're can be case-insensitive when comparing the host we used to
- // establish the socket to the hostname in the certificate.
- String hostName = host.trim().toLowerCase(Locale.ENGLISH);
- boolean match = false;
- for(Iterator<String> it = names.iterator(); it.hasNext();) {
- // Don't trim the CN, though!
- String cn = it.next();
- cn = cn.toLowerCase(Locale.ENGLISH);
- // Store CN in StringBuffer in case we need to report an error.
- buf.append(" <");
- buf.append(cn);
- buf.append('>');
- if(it.hasNext()) {
- buf.append(" OR");
- }
-
- // The CN better have at least two dots if it wants wildcard
- // action. It also can't be [*.co.uk] or [*.co.jp] or
- // [*.org.uk], etc...
- boolean doWildcard = cn.startsWith("*.") &&
- cn.lastIndexOf('.') >= 0 &&
- acceptableCountryWildcard(cn) &&
- !Inet6Util.isValidIPV4Address(host);
-
- if(doWildcard) {
- match = hostName.endsWith(cn.substring(1));
- if(match && strictWithSubDomains) {
- // If we're in strict mode, then [*.foo.com] is not
- // allowed to match [a.b.foo.com]
- match = countDots(hostName) == countDots(cn);
- }
- } else {
- match = hostName.equals(cn);
- }
- if(match) {
- break;
- }
- }
- if(!match) {
- throw new SSLException("hostname in certificate didn't match: <" +
- host + "> !=" + buf);
- }
- }
-
- public static boolean acceptableCountryWildcard(String cn) {
- int cnLen = cn.length();
- if(cnLen >= 7 && cnLen <= 9) {
- // Look for the '.' in the 3rd-last position:
- if(cn.charAt(cnLen - 3) == '.') {
- // Trim off the [*.] and the [.XX].
- String s = cn.substring(2, cnLen - 3);
- // And test against the sorted array of bad 2lds:
- int x = Arrays.binarySearch(BAD_COUNTRY_2LDS, s);
- return x < 0;
- }
- }
- return true;
- }
-
- public static String[] getCNs(X509Certificate cert) {
- LinkedList<String> cnList = new LinkedList<String>();
- /*
- Sebastian Hauer's original StrictSSLProtocolSocketFactory used
- getName() and had the following comment:
-
- Parses a X.500 distinguished name for the value of the
- "Common Name" field. This is done a bit sloppy right
- now and should probably be done a bit more according to
- <code>RFC 2253</code>.
-
- I've noticed that toString() seems to do a better job than
- getName() on these X500Principal objects, so I'm hoping that
- addresses Sebastian's concern.
-
- For example, getName() gives me this:
- 1.2.840.113549.1.9.1=#16166a756c6975736461766965734063756362632e636f6d
-
- whereas toString() gives me this:
- EMAILADDRESS=juliusdavies@cucbc.com
-
- Looks like toString() even works with non-ascii domain names!
- I tested it with "&#x82b1;&#x5b50;.co.jp" and it worked fine.
- */
- String subjectPrincipal = cert.getSubjectX500Principal().toString();
- StringTokenizer st = new StringTokenizer(subjectPrincipal, ",");
- while(st.hasMoreTokens()) {
- String tok = st.nextToken();
- int x = tok.indexOf("CN=");
- if(x >= 0) {
- cnList.add(tok.substring(x + 3));
- }
- }
- if(!cnList.isEmpty()) {
- String[] cns = new String[cnList.size()];
- cnList.toArray(cns);
- return cns;
- } else {
- return null;
- }
- }
-
-
- /**
- * Extracts the array of SubjectAlt DNS names from an X509Certificate.
- * Returns null if there aren't any.
- * <p/>
- * Note: Java doesn't appear able to extract international characters
- * from the SubjectAlts. It can only extract international characters
- * from the CN field.
- * <p/>
- * (Or maybe the version of OpenSSL I'm using to test isn't storing the
- * international characters correctly in the SubjectAlts?).
- *
- * @param cert X509Certificate
- * @return Array of SubjectALT DNS names stored in the certificate.
- */
- public static String[] getDNSSubjectAlts(X509Certificate cert) {
- LinkedList<String> subjectAltList = new LinkedList<String>();
- Collection<List<?>> c = null;
- try {
- c = cert.getSubjectAlternativeNames();
- }
- catch(CertificateParsingException cpe) {
- Logger.getLogger(DefaultHostnameVerifier.class.getName())
- .log(Level.FINE, "Error parsing certificate.", cpe);
- }
- if(c != null) {
- for (List<?> aC : c) {
- List<?> list = aC;
- int type = ((Integer) list.get(0)).intValue();
- // If type is 2, then we've got a dNSName
- if (type == 2) {
- String s = (String) list.get(1);
- subjectAltList.add(s);
- }
- }
- }
- if(!subjectAltList.isEmpty()) {
- String[] subjectAlts = new String[subjectAltList.size()];
- subjectAltList.toArray(subjectAlts);
- return subjectAlts;
- } else {
- return null;
- }
- }
-
- /**
- * Counts the number of dots "." in a string.
- * @param s string to count dots from
- * @return number of dots
- */
- public static int countDots(final String s) {
- int count = 0;
- for(int i = 0; i < s.length(); i++) {
- if(s.charAt(i) == '.') {
- count++;
- }
- }
- return count;
- }
-
- /**
- * Checks to see if the supplied hostname matches any of the supplied CNs
- * or "DNS" Subject-Alts. Most implementations only look at the first CN,
- * and ignore any additional CNs. Most implementations do look at all of
- * the "DNS" Subject-Alts. The CNs or Subject-Alts may contain wildcards
- * according to RFC 2818.
- *
- * @param cns CN fields, in order, as extracted from the X.509
- * certificate.
- * @param subjectAlts Subject-Alt fields of type 2 ("DNS"), as extracted
- * from the X.509 certificate.
- * @param host The hostname to verify.
- * @throws SSLException If verification failed.
- */
- public final void verify(
- final String host,
- final String[] cns,
- final String[] subjectAlts) throws SSLException {
- verify(host, cns, subjectAlts, false);
- }
-
-}
diff --git a/x-net/src/main/java/javax/net/ssl/DefaultSSLContext.java b/x-net/src/main/java/javax/net/ssl/DefaultSSLContext.java
deleted file mode 100644
index a12d385..0000000
--- a/x-net/src/main/java/javax/net/ssl/DefaultSSLContext.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.io.FileInputStream;
-import java.security.AccessController;
-import java.security.KeyStore;
-import java.security.PrivilegedAction;
-import java.security.Provider;
-import java.security.Security;
-
-import org.apache.harmony.security.fortress.Engine;
-import org.apache.harmony.security.fortress.Services;
-
-/**
- * Support class for this package.
- */
-final class DefaultSSLContext {
- private static SSLContext defaultSSLContext;
-
- static synchronized SSLContext getContext() {
- if (defaultSSLContext == null) {
- defaultSSLContext = AccessController
- .doPrivileged(new PrivilegedAction<SSLContext>() {
- public SSLContext run() {
- return findDefault();
- }
- });
- }
- return defaultSSLContext;
- }
-
- private static SSLContext findDefault() {
- // FIXME EXPORT CONTROL
- for (Provider provider : Services.getProvidersList()) {
- final Provider.Service service = Engine.door.getService(provider, "SSLContext");
- if (service != null) {
- try {
- SSLContext con = new SSLContext((SSLContextSpi) service.newInstance(null),
- service.getProvider(), service.getAlgorithm());
-
- /*
- * TODO
- * javax.net.ssl.keyStoreProvider,
- * javax.net.ssl.trustStoreProvider system property
- */
-
- // find KeyStore, KeyManagers
- KeyManager[] keyManagers = null;
- KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
- String keystore = System.getProperty("javax.net.ssl.keyStore");
- String keystorepwd = System.getProperty("javax.net.ssl.keyStorePassword");
- char[] pwd = null;
- if (keystorepwd != null) {
- pwd = keystorepwd.toCharArray();
- }
- if (keystore != null) {
- FileInputStream fis = new FileInputStream(keystore);
- try {
- ks.load(fis, pwd);
- } finally {
- fis.close();
- }
- KeyManagerFactory kmf;
- String kmfAlg = Security.getProperty("ssl.KeyManagerFactory.algorithm");
- if (kmfAlg == null) {
- kmfAlg = "SunX509";
- }
- kmf = KeyManagerFactory.getInstance(kmfAlg);
- kmf.init(ks, pwd);
- keyManagers = kmf.getKeyManagers();
- }
-
- // find TrustStore, TrustManagers
- TrustManager[] trustManagers = null;
- keystore = System.getProperty("javax.net.ssl.trustStore");
- keystorepwd = System.getProperty("javax.net.ssl.trustStorePassword");
- pwd = null;
- if (keystorepwd != null) {
- pwd = keystorepwd.toCharArray();
- }
- // TODO Defaults: jssecacerts; cacerts
- if (keystore != null) {
- FileInputStream fis = new FileInputStream(keystore);
- try {
- ks.load(fis, pwd);
- } finally {
- fis.close();
- }
- TrustManagerFactory tmf;
- String tmfAlg = Security.getProperty("ssl.TrustManagerFactory.algorithm");
- if (tmfAlg == null) {
- tmfAlg = "PKIX";
- }
- tmf = TrustManagerFactory.getInstance(tmfAlg);
- tmf.init(ks);
- trustManagers = tmf.getTrustManagers();
- }
-
- con.init(keyManagers, trustManagers, null);
- return con;
- } catch (Exception e) {
- // ignore and try another
- }
- }
- }
- return null;
- }
-}
diff --git a/x-net/src/main/java/javax/net/ssl/DefaultSSLServerSocketFactory.java b/x-net/src/main/java/javax/net/ssl/DefaultSSLServerSocketFactory.java
deleted file mode 100644
index 3e58897..0000000
--- a/x-net/src/main/java/javax/net/ssl/DefaultSSLServerSocketFactory.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.ServerSocket;
-import java.net.SocketException;
-
-/**
- * Default inoperative implementation of javax.net.ssl.SSLServerSocketFactory
- */
-class DefaultSSLServerSocketFactory extends SSLServerSocketFactory {
-
- private final String errMessage;
-
- DefaultSSLServerSocketFactory(String mes) {
- errMessage = mes;
- }
-
- @Override
- public String[] getDefaultCipherSuites() {
- return new String[0];
- }
-
- @Override
- public String[] getSupportedCipherSuites() {
- return new String[0];
- }
-
- @Override
- public ServerSocket createServerSocket(int port) throws IOException {
- throw new SocketException(errMessage);
- }
-
- @Override
- public ServerSocket createServerSocket(int port, int backlog) throws IOException {
- throw new SocketException(errMessage);
- }
-
- @Override
- public ServerSocket createServerSocket(int port, int backlog, InetAddress iAddress)
- throws IOException {
- throw new SocketException(errMessage);
- }
-
-}
diff --git a/x-net/src/main/java/javax/net/ssl/DefaultSSLSocketFactory.java b/x-net/src/main/java/javax/net/ssl/DefaultSSLSocketFactory.java
deleted file mode 100644
index 4035a0e..0000000
--- a/x-net/src/main/java/javax/net/ssl/DefaultSSLSocketFactory.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.net.SocketException;
-import java.net.UnknownHostException;
-
-/**
- * Default inoperative implementation of javax.net.ssl.SSLSocketFactory
- *
- */
-class DefaultSSLSocketFactory extends SSLSocketFactory {
-
- private final String errMessage;
-
- DefaultSSLSocketFactory(String mes) {
- errMessage = mes;
- }
-
- @Override
- public String[] getDefaultCipherSuites() {
- return new String[0];
- }
-
- @Override
- public String[] getSupportedCipherSuites() {
- return new String[0];
- }
-
- @Override
- public Socket createSocket(Socket s, String host, int port, boolean autoClose)
- throws IOException {
- throw new SocketException(errMessage);
- }
-
- @Override
- public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
- throw new SocketException(errMessage);
- }
-
- @Override
- public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
- throws IOException, UnknownHostException {
- throw new SocketException(errMessage);
- }
-
- @Override
- public Socket createSocket(InetAddress host, int port) throws IOException {
- throw new SocketException(errMessage);
- }
-
- @Override
- public Socket createSocket(InetAddress address, int port, InetAddress localAddress,
- int localPort) throws IOException {
- throw new SocketException(errMessage);
- }
-
-}
diff --git a/x-net/src/main/java/javax/net/ssl/HandshakeCompletedEvent.java b/x-net/src/main/java/javax/net/ssl/HandshakeCompletedEvent.java
deleted file mode 100644
index 4618280..0000000
--- a/x-net/src/main/java/javax/net/ssl/HandshakeCompletedEvent.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.io.Serializable;
-import java.security.Principal;
-import java.security.cert.Certificate;
-import javax.security.cert.X509Certificate;
-import java.util.EventObject;
-
-/**
- * The event object encapsulating the information about a completed SSL
- * handshake on a SSL connection.
- */
-public class HandshakeCompletedEvent extends EventObject implements Serializable {
-
- /**
- * The 5.0 spec. doesn't declare this serialVersionUID field In order to be
- * compatible it is explicitly declared here
- */
- private static final long serialVersionUID = 7914963744257769778L;
-
- private transient SSLSession session;
-
- /**
- * Creates a new {@code HandshakeCompletedEvent} with the specified SSL
- * socket and SSL session.
- *
- * @param sock
- * the SSL socket.
- * @param s
- * the SSL session.
- */
- public HandshakeCompletedEvent(SSLSocket sock, SSLSession s) {
- super(sock);
- session = s;
- }
-
- /**
- * Returns the SSL session associated with this event.
- *
- * @return the SSL session associated with this event.
- */
- public SSLSession getSession() {
- return session;
- }
-
- /**
- * Returns the name of the cipher suite negotiated during this handshake.
- *
- * @return the name of the cipher suite negotiated during this handshake.
- */
- public String getCipherSuite() {
- return session.getCipherSuite();
- }
-
- /**
- * Returns the list of local certificates used during the handshake. These
- * certificates were sent to the peer.
- *
- * @return Returns the list of certificates used during the handshake with
- * the local identity certificate followed by CAs, or {@code null}
- * if no certificates were used during the handshake.
- */
- public Certificate[] getLocalCertificates() {
- return session.getLocalCertificates();
- }
-
- /**
- * Return the list of certificates identifying the peer during the
- * handshake.
- *
- * @return the list of certificates identifying the peer with the peer's
- * identity certificate followed by CAs.
- * @throws SSLPeerUnverifiedException
- * if the identity of the peer has not been verified.
- */
- public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException {
- return session.getPeerCertificates();
- }
-
- /**
- * Returns the list of certificates identifying the peer. The peer's
- * identity certificate is followed by the validated certificate authority
- * certificates.
- * <p>
- * <b>Replaced by:</b> {@link #getPeerCertificates()}
- *
- * @return the list of certificates identifying the peer
- * @throws SSLPeerUnverifiedException
- * if the identity of the peer has not been verified.
- */
- public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException {
- return session.getPeerCertificateChain();
- }
-
- /**
- * Returns the {@code Principal} identifying the peer.
- *
- * @return the {@code Principal} identifying the peer.
- * @throws SSLPeerUnverifiedException
- * if the identity of the peer has not been verified.
- */
- public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
- return session.getPeerPrincipal();
- }
-
- /**
- * Returns the {@code Principal} used to identify during the handshake.
- *
- * @return the {@code Principal} used to identify during the handshake.
- */
- public Principal getLocalPrincipal() {
- return session.getLocalPrincipal();
- }
-
- /**
- * Returns the SSL socket that produced this event.
- *
- * @return the SSL socket that produced this event.
- */
- public SSLSocket getSocket() {
- return (SSLSocket) this.source;
- }
-
-}
diff --git a/x-net/src/main/java/javax/net/ssl/HandshakeCompletedListener.java b/x-net/src/main/java/javax/net/ssl/HandshakeCompletedListener.java
deleted file mode 100644
index 5032c63..0000000
--- a/x-net/src/main/java/javax/net/ssl/HandshakeCompletedListener.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.util.EventListener;
-
-/**
- * The listener to be implemented to receive event notifications on completion
- * of SSL handshake on an SSL connection.
- */
-public interface HandshakeCompletedListener extends EventListener {
- /**
- * The callback method that is invoked when a SSL handshake is completed.
- *
- * @param event
- * the information on the completed SSL handshake event.
- */
- void handshakeCompleted(HandshakeCompletedEvent event);
-}
diff --git a/x-net/src/main/java/javax/net/ssl/HostnameVerifier.java b/x-net/src/main/java/javax/net/ssl/HostnameVerifier.java
deleted file mode 100644
index 805762e..0000000
--- a/x-net/src/main/java/javax/net/ssl/HostnameVerifier.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-/**
- * The interface to be used to provide hostname verification functionality.
- * <p>
- * This is an extended verification option that implementers can provide. It is to be used
- * during a handshake if the URL's hostname does not match the peer's
- * identification hostname.
- */
-public interface HostnameVerifier {
- /**
- * Verifies that the specified hostname is allowed within the specified SSL
- * session.
- *
- * @param hostname
- * the hostname.
- * @param session
- * the SSL session of the connection.
- * @return {@code true} if the specified hostname is allowed, otherwise
- * {@code false}.
- */
- boolean verify(String hostname, SSLSession session);
-}
diff --git a/x-net/src/main/java/javax/net/ssl/HttpsURLConnection.java b/x-net/src/main/java/javax/net/ssl/HttpsURLConnection.java
deleted file mode 100644
index 8c49690..0000000
--- a/x-net/src/main/java/javax/net/ssl/HttpsURLConnection.java
+++ /dev/null
@@ -1,222 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.net.HttpURLConnection;
-import java.net.URL;
-import java.security.Principal;
-import java.security.cert.Certificate;
-import java.security.cert.X509Certificate;
-
-/**
- * This abstract subclass of {@code HttpURLConnection} defines methods for
- * managing HTTPS connections according to the description given by RFC 2818.
- */
-public abstract class HttpsURLConnection extends HttpURLConnection {
-
- private static HostnameVerifier defaultHostnameVerifier = new DefaultHostnameVerifier();
-
- private static SSLSocketFactory defaultSSLSocketFactory = (SSLSocketFactory) SSLSocketFactory
- .getDefault();
-
- /**
- * Sets the default hostname verifier to be used by new instances.
- *
- * @param v
- * the new default hostname verifier
- * @throws IllegalArgumentException
- * if the specified verifier is {@code null}.
- */
- public static void setDefaultHostnameVerifier(HostnameVerifier v) {
- if (v == null) {
- throw new IllegalArgumentException("HostnameVerifier is null");
- }
- defaultHostnameVerifier = v;
- }
-
- /**
- * Returns the default hostname verifier.
- *
- * @return the default hostname verifier.
- */
- public static HostnameVerifier getDefaultHostnameVerifier() {
- return defaultHostnameVerifier;
- }
-
- /**
- * Sets the default SSL socket factory to be used by new instances.
- *
- * @param sf
- * the new default SSL socket factory.
- * @throws IllegalArgumentException
- * if the specified socket factory is {@code null}.
- */
- public static void setDefaultSSLSocketFactory(SSLSocketFactory sf) {
- if (sf == null) {
- throw new IllegalArgumentException("SSLSocketFactory is null");
- }
- defaultSSLSocketFactory = sf;
- }
-
- /**
- * Returns the default SSL socket factory for new instances.
- *
- * @return the default SSL socket factory for new instances.
- */
- public static SSLSocketFactory getDefaultSSLSocketFactory() {
- return defaultSSLSocketFactory;
- }
-
- /**
- * The host name verifier used by this connection. It is initialized from
- * the default hostname verifier
- * {@link #setDefaultHostnameVerifier(HostnameVerifier)} or
- * {@link #getDefaultHostnameVerifier()}.
- */
- protected HostnameVerifier hostnameVerifier;
-
- private SSLSocketFactory sslSocketFactory;
-
- /**
- * Creates a new {@code HttpsURLConnection} with the specified {@code URL}.
- *
- * @param url
- * the {@code URL} to connect to.
- */
- protected HttpsURLConnection(URL url) {
- super(url);
- hostnameVerifier = defaultHostnameVerifier;
- sslSocketFactory = defaultSSLSocketFactory;
- }
-
- /**
- * Returns the name of the cipher suite negotiated during the SSL handshake.
- *
- * @return the name of the cipher suite negotiated during the SSL handshake.
- * @throws IllegalStateException
- * if no connection has been established yet.
- */
- public abstract String getCipherSuite();
-
- /**
- * Returns the list of local certificates used during the handshake. These
- * certificates were sent to the peer.
- *
- * @return Returns the list of certificates used during the handshake with
- * the local identity certificate followed by CAs, or {@code null}
- * if no certificates were used during the handshake.
- * @throws IllegalStateException
- * if no connection has been established yet.
- */
- public abstract Certificate[] getLocalCertificates();
-
- /**
- * Return the list of certificates identifying the peer during the
- * handshake.
- *
- * @return the list of certificates identifying the peer with the peer's
- * identity certificate followed by CAs.
- * @throws SSLPeerUnverifiedException
- * if the identity of the peer has not been verified..
- * @throws IllegalStateException
- * if no connection has been established yet.
- */
- public abstract Certificate[] getServerCertificates() throws SSLPeerUnverifiedException;
-
- /**
- * Returns the {@code Principal} identifying the peer.
- *
- * @return the {@code Principal} identifying the peer.
- * @throws SSLPeerUnverifiedException
- * if the identity of the peer has not been verified.
- * @throws IllegalStateException
- * if no connection has been established yet.
- */
- public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
- Certificate[] certs = getServerCertificates();
- if (certs == null || certs.length == 0 || (!(certs[0] instanceof X509Certificate))) {
- throw new SSLPeerUnverifiedException("No server's end-entity certificate");
- }
- return ((X509Certificate) certs[0]).getSubjectX500Principal();
- }
-
- /**
- * Returns the {@code Principal} used to identify the local host during the handshake.
- *
- * @return the {@code Principal} used to identify the local host during the handshake, or
- * {@code null} if none was used.
- * @throws IllegalStateException
- * if no connection has been established yet.
- */
- public Principal getLocalPrincipal() {
- Certificate[] certs = getLocalCertificates();
- if (certs == null || certs.length == 0 || (!(certs[0] instanceof X509Certificate))) {
- return null;
- }
- return ((X509Certificate) certs[0]).getSubjectX500Principal();
- }
-
- /**
- * Sets the hostname verifier for this instance.
- *
- * @param v
- * the hostname verifier for this instance.
- * @throws IllegalArgumentException
- * if the specified verifier is {@code null}.
- */
- public void setHostnameVerifier(HostnameVerifier v) {
- if (v == null) {
- throw new IllegalArgumentException("HostnameVerifier is null");
- }
- hostnameVerifier = v;
- }
-
- /**
- * Returns the hostname verifier used by this instance.
- *
- * @return the hostname verifier used by this instance.
- */
- public HostnameVerifier getHostnameVerifier() {
- return hostnameVerifier;
- }
-
- /**
- * Sets the SSL socket factory for this instance.
- *
- * @param sf
- * the SSL socket factory to be used by this instance.
- * @throws IllegalArgumentException
- * if the specified socket factory is {@code null}.
- */
- public void setSSLSocketFactory(SSLSocketFactory sf) {
- if (sf == null) {
- throw new IllegalArgumentException("SSLSocketFactory is null");
- }
- sslSocketFactory = sf;
- }
-
- /**
- * Returns the SSL socket factory used by this instance.
- *
- * @return the SSL socket factory used by this instance.
- */
- public SSLSocketFactory getSSLSocketFactory() {
- return sslSocketFactory;
- }
-
-}
diff --git a/x-net/src/main/java/javax/net/ssl/KeyManager.java b/x-net/src/main/java/javax/net/ssl/KeyManager.java
deleted file mode 100644
index 30c8032..0000000
--- a/x-net/src/main/java/javax/net/ssl/KeyManager.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-/**
- * This is the interface to implement in order to mark a class as a JSSE key
- * managers so that key managers can be easily grouped. The key managers are
- * responsible for handling the keys used to authenticate the local side to its
- * peer,
- */
-public interface KeyManager {
-}
diff --git a/x-net/src/main/java/javax/net/ssl/KeyManagerFactory.java b/x-net/src/main/java/javax/net/ssl/KeyManagerFactory.java
deleted file mode 100644
index 99a37a8..0000000
--- a/x-net/src/main/java/javax/net/ssl/KeyManagerFactory.java
+++ /dev/null
@@ -1,233 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.security.AccessController;
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.PrivilegedAction;
-import java.security.Provider;
-import java.security.Security;
-import java.security.UnrecoverableKeyException;
-
-import org.apache.harmony.security.fortress.Engine;
-
-/**
- * The public API for {@code KeyManagerFactory} implementations.
- */
-public class KeyManagerFactory {
- // Store KeyManagerFactory service name
- private static final String SERVICE = "KeyManagerFactory";
-
- // Used to access common engine functionality
- private static Engine engine = new Engine(SERVICE);
-
- // Store default property name
- private static final String PROPERTY_NAME = "ssl.KeyManagerFactory.algorithm";
-
- /**
- * Returns the default key manager factory algorithm name.
- * <p>
- * The default algorithm name is specified by the security property:
- * {@code 'ssl.KeyManagerFactory.algorithm'}.
- *
- * @return the default algorithm name.
- */
- public static final String getDefaultAlgorithm() {
- return AccessController.doPrivileged(new PrivilegedAction<String>() {
- public String run() {
- return Security.getProperty(PROPERTY_NAME);
- }
- });
- }
-
- /**
- * Creates a new {@code KeyManagerFactory} instance for the specified key
- * management algorithm.
- *
- * @param algorithm
- * the name of the requested key management algorithm.
- * @return a key manager factory for the requested algorithm.
- * @throws NoSuchAlgorithmException
- * if no installed provider can provide the requested algorithm.
- * @throws NullPointerException
- * if {@code algorithm} is {@code null} (instead of
- * NoSuchAlgorithmException as in 1.4 release)
- */
- public static final KeyManagerFactory getInstance(String algorithm)
- throws NoSuchAlgorithmException {
- if (algorithm == null) {
- throw new NullPointerException("algorithm is null");
- }
- synchronized (engine) {
- engine.getInstance(algorithm, null);
- return new KeyManagerFactory((KeyManagerFactorySpi) engine.spi, engine.provider,
- algorithm);
- }
- }
-
- /**
- * Creates a new {@code KeyManagerFactory} instance for the specified key
- * management algorithm from the specified provider.
- *
- * @param algorithm
- * the name of the requested key management algorithm name.
- * @param provider
- * the name of the provider that provides the requested
- * algorithm.
- * @return a key manager factory for the requested algorithm.
- * @throws NoSuchAlgorithmException
- * if the specified provider cannot provide the requested
- * algorithm.
- * @throws NoSuchProviderException
- * if the specified provider does not exist.
- * @throws NullPointerException
- * if {@code algorithm} is {@code null} (instead of
- * NoSuchAlgorithmException as in 1.4 release)
- */
- public static final KeyManagerFactory getInstance(String algorithm, String provider)
- throws NoSuchAlgorithmException, NoSuchProviderException {
- if ((provider == null) || (provider.length() == 0)) {
- throw new IllegalArgumentException("Provider is null or empty");
- }
- Provider impProvider = Security.getProvider(provider);
- if (impProvider == null) {
- throw new NoSuchProviderException(provider);
- }
- return getInstance(algorithm, impProvider);
- }
-
- /**
- * Creates a new {@code KeyManagerFactory} instance for the specified key
- * management algorithm from the specified provider.
- *
- * @param algorithm
- * the name of the requested key management algorithm name.
- * @param provider
- * the provider that provides the requested algorithm.
- * @return a key manager factory for the requested algorithm.
- * @throws NoSuchAlgorithmException
- * if the specified provider cannot provide the requested
- * algorithm.
- * @throws NullPointerException
- * if {@code algorithm} is {@code null} (instead of
- * NoSuchAlgorithmException as in 1.4 release)
- */
- public static final KeyManagerFactory getInstance(String algorithm, Provider provider)
- throws NoSuchAlgorithmException {
- if (provider == null) {
- throw new IllegalArgumentException("Provider is null");
- }
- if (algorithm == null) {
- throw new NullPointerException("algorithm is null");
- }
- synchronized (engine) {
- engine.getInstance(algorithm, provider, null);
- return new KeyManagerFactory((KeyManagerFactorySpi) engine.spi, provider, algorithm);
- }
- }
-
- // Store used provider
- private final Provider provider;
-
- // Store used KeyManagerFactorySpi implementation
- private final KeyManagerFactorySpi spiImpl;
-
- // Store used algorithm
- private final String algorithm;
-
- /**
- * Creates a new {@code KeyManagerFactory}.
- *
- * @param factorySpi
- * the implementation delegate.
- * @param provider
- * the provider.
- * @param algorithm
- * the key management algorithm name.
- */
- protected KeyManagerFactory(KeyManagerFactorySpi factorySpi, Provider provider, String algorithm) {
- super();
- this.provider = provider;
- this.algorithm = algorithm;
- this.spiImpl = factorySpi;
- }
-
- /**
- * Returns the name of the key management algorithm.
- *
- * @return the name of the key management algorithm.
- */
- public final String getAlgorithm() {
- return algorithm;
- }
-
- /**
- * Returns the provider for this {@code KeyManagerFactory} instance.
- *
- * @return the provider for this {@code KeyManagerFactory} instance.
- */
- public final Provider getProvider() {
- return provider;
- }
-
- /**
- * Initializes this instance with the specified key store and password.
- *
- * @param ks
- * the key store or {@code null} to use the default key store.
- * @param password
- * the password for the specified key store or {@code null} if no
- * key store is provided.
- * @throws KeyStoreException
- * if initializing this key manager factory fails.
- * @throws NoSuchAlgorithmException
- * if a required algorithm is not available.
- * @throws UnrecoverableKeyException
- * if a key cannot be recovered.
- */
- public final void init(KeyStore ks, char[] password) throws KeyStoreException,
- NoSuchAlgorithmException, UnrecoverableKeyException {
- spiImpl.engineInit(ks, password);
- }
-
- /**
- * Initializes this instance with the specified factory parameters.
- *
- * @param spec
- * the factory parameters.
- * @throws InvalidAlgorithmParameterException
- * if an error occurs.
- */
- public final void init(ManagerFactoryParameters spec) throws InvalidAlgorithmParameterException {
- spiImpl.engineInit(spec);
- }
-
- /**
- * Returns a list of key managers, one instance for each type of key in the
- * key store.
- *
- * @return a list of key managers.
- */
- public final KeyManager[] getKeyManagers() {
- return spiImpl.engineGetKeyManagers();
- }
-}
diff --git a/x-net/src/main/java/javax/net/ssl/KeyManagerFactorySpi.java b/x-net/src/main/java/javax/net/ssl/KeyManagerFactorySpi.java
deleted file mode 100644
index 39925f9..0000000
--- a/x-net/src/main/java/javax/net/ssl/KeyManagerFactorySpi.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.UnrecoverableKeyException;
-
-/**
- * The <i>Service Provider Interface</i> (SPI) for the
- * {@code KeyManagerFactory} class.
- */
-public abstract class KeyManagerFactorySpi {
-
- /**
- * Creates a new {@code KeyManagerFactorySpi} instance.
- */
- public KeyManagerFactorySpi() {
- super();
- }
-
- /**
- * Initializes this instance with the specified key store and password.
- *
- * @param ks
- * the key store or {@code null} to use the default key store.
- * @param password
- * the key store password.
- * @throws KeyStoreException
- * if initializing this instance fails.
- * @throws NoSuchAlgorithmException
- * if a required algorithm is not available.
- * @throws UnrecoverableKeyException
- * if a key cannot be recovered.
- */
- protected abstract void engineInit(KeyStore ks, char[] password) throws KeyStoreException,
- NoSuchAlgorithmException, UnrecoverableKeyException;
-
- /**
- * Initializes this instance with the specified factory parameters.
- *
- * @param spec
- * the factory parameters.
- * @throws InvalidAlgorithmParameterException
- * if an error occurs.
- */
- protected abstract void engineInit(ManagerFactoryParameters spec)
- throws InvalidAlgorithmParameterException;
-
- /**
- * Returns a list of key managers, one instance for each type of key in the
- * key store.
- *
- * @return a list of key managers.
- */
- protected abstract KeyManager[] engineGetKeyManagers();
-}
diff --git a/x-net/src/main/java/javax/net/ssl/KeyStoreBuilderParameters.java b/x-net/src/main/java/javax/net/ssl/KeyStoreBuilderParameters.java
deleted file mode 100644
index d30cc8a..0000000
--- a/x-net/src/main/java/javax/net/ssl/KeyStoreBuilderParameters.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.security.KeyStore;
-
-/**
- * The parameters for {@code KeyManager}s. The parameters are a list of
- * {@code KeyStore.Builder}s.
- *
- * @since 1.5
- * @see KeyStore.Builder
- */
-public class KeyStoreBuilderParameters implements ManagerFactoryParameters {
-
- private final List<KeyStore.Builder> ksbuilders;
-
- /**
- * Creates a new {@code KeyStoreBuilderParameters} with the specified key
- * store builder.
- *
- * @param builder
- * the key store builder.
- */
- public KeyStoreBuilderParameters(KeyStore.Builder builder) {
- super();
- ksbuilders = Collections.singletonList(builder);
- }
-
- /**
- * Creates a new {@code KeyStoreBuilderParameters} with the specified list
- * of {@code KeyStore.Builder}s.
- *
- * @param parameters
- * the list of key store builders
- * @throws IllegalArgumentException
- * if the specified list is empty.
- */
- @SuppressWarnings("unchecked")
- public KeyStoreBuilderParameters(List parameters) {
- super();
- if (parameters == null) {
- throw new NullPointerException("Builders list is null");
- }
- if (parameters.isEmpty()) {
- throw new IllegalArgumentException("Builders list is empty");
- }
- ksbuilders = Collections.unmodifiableList(new ArrayList<KeyStore.Builder>(parameters));
- }
-
- /**
- * Returns the unmodifiable list of {@code KeyStore.Builder}s associated
- * with this parameters instance.
- *
- * @return the unmodifiable list of {@code KeyStore.Builder}s.
- */
- @SuppressWarnings("unchecked")
- public List getParameters() {
- return ksbuilders;
- }
-}
diff --git a/x-net/src/main/java/javax/net/ssl/ManagerFactoryParameters.java b/x-net/src/main/java/javax/net/ssl/ManagerFactoryParameters.java
deleted file mode 100644
index b90deeb..0000000
--- a/x-net/src/main/java/javax/net/ssl/ManagerFactoryParameters.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-/**
- * The marker interface for key manager factory parameters. Its purpose is to
- * group key manager factory parameters objects.
- *
- * @since 1.4
- */
-public interface ManagerFactoryParameters {
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLContext.java b/x-net/src/main/java/javax/net/ssl/SSLContext.java
deleted file mode 100644
index 8a0a157..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLContext.java
+++ /dev/null
@@ -1,253 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.security.KeyManagementException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.Provider;
-import java.security.SecureRandom;
-import java.security.Security;
-
-import org.apache.harmony.security.fortress.Engine;
-
-
-/**
- * The public API for secure socket protocol implementations. It acts as factory
- * for {@code SSLSocketFactory}'s and {@code SSLEngine}s.
- */
-public class SSLContext {
- // StoreSSLContext service name
- private static final String SERVICE = "SSLContext";
-
- // Used to access common engine functionality
- private static Engine engine = new Engine(SERVICE);
-
- /**
- * Creates a new {@code SSLContext} instance for the specified protocol.
- *
- * @param protocol
- * the requested protocol to create a context for.
- * @return the created {@code SSLContext} instance.
- * @throws NoSuchAlgorithmException
- * if no installed provider can provide the requested protocol
- * @throws NullPointerException
- * if {@code protocol} is {@code null} (instead of
- * NoSuchAlgorithmException as in 1.4 release)
- */
- public static SSLContext getInstance(String protocol) throws NoSuchAlgorithmException {
- if (protocol == null) {
- throw new NullPointerException("protocol is null");
- }
- synchronized (engine) {
- engine.getInstance(protocol, null);
- return new SSLContext((SSLContextSpi) engine.spi, engine.provider, protocol);
- }
- }
-
- /**
- * Creates a new {@code SSLContext} instance for the specified protocol from
- * the specified provider.
- *
- * @param protocol
- * the requested protocol to create a context for.
- * @param provider
- * the name of the provider that provides the requested protocol.
- * @return an {@code SSLContext} for the requested protocol.
- * @throws NoSuchAlgorithmException
- * if the specified provider cannot provider the requested
- * protocol.
- * @throws NoSuchProviderException
- * if the specified provider does not exits.
- * @throws NullPointerException
- * if {@code protocol} is {@code null} (instead of
- * NoSuchAlgorithmException as in 1.4 release)
- */
- public static SSLContext getInstance(String protocol, String provider)
- throws NoSuchAlgorithmException, NoSuchProviderException {
- if (provider == null) {
- throw new IllegalArgumentException("Provider is null");
- }
- if (provider.length() == 0) {
- throw new IllegalArgumentException("Provider is empty");
- }
- Provider impProvider = Security.getProvider(provider);
- if (impProvider == null) {
- throw new NoSuchProviderException(provider);
- }
- return getInstance(protocol, impProvider);
- }
-
- /**
- * Creates a new {@code SSLContext} instance for the specified protocol from
- * the specified provider.
- *
- * @param protocol
- * the requested protocol to create a context for
- * @param provider
- * the provider that provides the requested protocol.
- * @return an {@code SSLContext} for the requested protocol.
- * @throws NoSuchAlgorithmException
- * if the specified provider cannot provide the requested
- * protocol.
- * @throws NullPointerException
- * if {@code protocol} is {@code null} (instead of
- * NoSuchAlgorithmException as in 1.4 release)
- */
- public static SSLContext getInstance(String protocol, Provider provider)
- throws NoSuchAlgorithmException {
- if (provider == null) {
- throw new IllegalArgumentException("provider is null");
- }
- if (protocol == null) {
- throw new NullPointerException("protocol is null");
- }
- synchronized (engine) {
- engine.getInstance(protocol, provider, null);
- return new SSLContext((SSLContextSpi) engine.spi, provider, protocol);
- }
- }
-
- private final Provider provider;
-
- private final SSLContextSpi spiImpl;
-
- private final String protocol;
-
- /**
- * Creates a new {@code SSLContext}.
- *
- * @param contextSpi
- * the implementation delegate.
- * @param provider
- * the provider.
- * @param protocol
- * the protocol name.
- */
- protected SSLContext(SSLContextSpi contextSpi, Provider provider, String protocol) {
- this.provider = provider;
- this.protocol = protocol;
- this.spiImpl = contextSpi;
- }
-
- /**
- * Returns the name of the secure socket protocol of this instance.
- *
- * @return the name of the secure socket protocol of this instance.
- */
- public final String getProtocol() {
- return protocol;
- }
-
- /**
- * Returns the provider of this {@code SSLContext} instance.
- *
- * @return the provider of this {@code SSLContext} instance.
- */
- public final Provider getProvider() {
- return provider;
- }
-
- /**
- * Initializes this {@code SSLContext} instance. All of the arguments are
- * optional, and the security providers will be searched for the required
- * implementations of the needed algorithms.
- *
- * @param km
- * the key sources or {@code null}.
- * @param tm
- * the trust decision sources or {@code null}.
- * @param sr
- * the randomness source or {@code null.}
- * @throws KeyManagementException
- * if initializing this instance fails.
- */
- public final void init(KeyManager[] km, TrustManager[] tm, SecureRandom sr)
- throws KeyManagementException {
- spiImpl.engineInit(km, tm, sr);
- }
-
- /**
- * Returns a socket factory for this instance.
- *
- * @return a socket factory for this instance.
- */
- public final SSLSocketFactory getSocketFactory() {
- return spiImpl.engineGetSocketFactory();
- }
-
- /**
- * Returns a server socket factory for this instance.
- *
- * @return a server socket factory for this instance.
- */
- public final SSLServerSocketFactory getServerSocketFactory() {
- return spiImpl.engineGetServerSocketFactory();
- }
-
- /**
- * Creates an {@code SSLEngine} instance from this context.
- *
- * @return an {@code SSLEngine} instance from this context.
- * @throws UnsupportedOperationException
- * if the provider does not support the operation.
- */
- public final SSLEngine createSSLEngine() {
- return spiImpl.engineCreateSSLEngine();
- }
-
- /**
- * Creates an {@code SSLEngine} instance from this context with the
- * specified hostname and port.
- *
- * @param peerHost
- * the name of the host
- * @param peerPort
- * the port
- * @return an {@code SSLEngine} instance from this context.
- * @throws UnsupportedOperationException
- * if the provider does not support the operation.
- */
- public final SSLEngine createSSLEngine(String peerHost, int peerPort) {
- return spiImpl.engineCreateSSLEngine(peerHost, peerPort);
- }
-
- /**
- * Returns the SSL session context that encapsulates the set of SSL sessions
- * that can be used for handshake of server-side SSL sockets.
- *
- * @return the SSL server session context for this context or {@code null}
- * if the underlying provider does not provide an implementation of
- * the {@code SSLSessionContext} interface.
- */
- public final SSLSessionContext getServerSessionContext() {
- return spiImpl.engineGetServerSessionContext();
- }
-
- /**
- * Returns the SSL session context that encapsulates the set of SSL sessions
- * that can be used for handshake of client-side SSL sockets.
- *
- * @return the SSL client session context for this context or {@code null}
- * if the underlying provider does not provide an implementation of
- * the {@code SSLSessionContext} interface.
- */
- public final SSLSessionContext getClientSessionContext() {
- return spiImpl.engineGetClientSessionContext();
- }
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLContextSpi.java b/x-net/src/main/java/javax/net/ssl/SSLContextSpi.java
deleted file mode 100644
index 44d2c59..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLContextSpi.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.security.KeyManagementException;
-import java.security.SecureRandom;
-
-/**
- * The <i>Service Provider Interface</i> (SPI) for the {@code SSLContext} class.
- */
-public abstract class SSLContextSpi {
-
- /**
- * Creates a new {@code SSLContextSpi} instance.
- */
- public SSLContextSpi() {
- super();
- }
-
- /**
- * Initializes this {@code SSLContext} instance. All of the arguments are
- * optional, and the security providers will be searched for the required
- * implementations of the needed algorithms.
- *
- * @param km
- * the key sources or {@code null}.
- * @param tm
- * the trust decision sources or {@code null}.
- * @param sr
- * the randomness source or {@code null.}
- * @throws KeyManagementException
- * if initializing this instance fails.
- */
- protected abstract void engineInit(KeyManager[] km, TrustManager[] tm, SecureRandom sr)
- throws KeyManagementException;
-
- /**
- * Returns a socket factory for this instance.
- *
- * @return a socket factory for this instance.
- */
- protected abstract SSLSocketFactory engineGetSocketFactory();
-
- /**
- * Returns a server socket factory for this instance.
- *
- * @return a server socket factory for this instance.
- */
- protected abstract SSLServerSocketFactory engineGetServerSocketFactory();
-
- /**
- * Creates an {@code SSLEngine} instance from this context with the
- * specified hostname and port.
- *
- * @param host
- * the name of the host
- * @param port
- * the port
- * @return an {@code SSLEngine} instance from this context.
- * @throws UnsupportedOperationException
- * if the provider does not support the operation.
- */
- protected abstract SSLEngine engineCreateSSLEngine(String host, int port);
-
- /**
- * Creates an {@code SSLEngine} instance from this context.
- *
- * @return an {@code SSLEngine} instance from this context.
- * @throws UnsupportedOperationException
- * if the provider does not support the operation.
- */
- protected abstract SSLEngine engineCreateSSLEngine();
-
- /**
- * Returns the SSL session context that encapsulates the set of SSL sessions
- * that can be used for the server side of the SSL handshake.
- *
- * @return the SSL server session context for this context or {@code null}
- * if the underlying provider does not provide an implementation of
- * the {@code SSLSessionContext} interface.
- */
- protected abstract SSLSessionContext engineGetServerSessionContext();
-
- /**
- * Returns the SSL session context that encapsulates the set of SSL sessions
- * that can be used for the client side of the SSL handshake.
- *
- * @return the SSL client session context for this context or {@code null}
- * if the underlying provider does not provide an implementation of
- * the {@code SSLSessionContext} interface.
- */
- protected abstract SSLSessionContext engineGetClientSessionContext();
-
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLEngine.java b/x-net/src/main/java/javax/net/ssl/SSLEngine.java
deleted file mode 100644
index 46e11a4..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLEngine.java
+++ /dev/null
@@ -1,464 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.nio.ByteBuffer;
-
-/**
- * The abstract implementation of secure communications using SSL, TLS, or other
- * protocols. It includes the setup, handshake, and encrypt/decrypt
- * functionality needed to create a secure connection.
- *
- * @since 1.5
- */
-public abstract class SSLEngine {
- private final String peerHost;
- private final int peerPort;
-
- /**
- * Creates a new {@code SSLEngine} instance.
- */
- protected SSLEngine() {
- super();
- peerHost = null;
- peerPort = -1;
- }
-
- /**
- * Creates a new {@code SSLEngine} instance with the specified host and
- * port.
- *
- * @param host
- * the name of the host.
- * @param port
- * the port of the host.
- */
- protected SSLEngine(String host, int port) {
- super();
- this.peerHost = host;
- this.peerPort = port;
- }
-
- /**
- * Returns the name of the peer host.
- *
- * @return the name of the peer host, or {@code null} if none is available.
- */
- public String getPeerHost() {
- return peerHost;
- }
-
- /**
- * Returns the port number of the peer host.
- *
- * @return the port number of the peer host, or {@code -1} is none is
- * available.
- */
- public int getPeerPort() {
- return peerPort;
- }
-
- /**
- * Initiates a handshake on this engine.
- * <p>
- * Calling this method is not needed for the initial handshake: it will be
- * called by {@code wrap} or {@code unwrap} if the initial handshake has not
- * been started yet.
- *
- * @throws SSLException
- * if starting the handshake fails.
- * @throws IllegalStateException
- * if the engine does not have all the needed settings (e.g.
- * client/server mode not set).
- */
- public abstract void beginHandshake() throws SSLException;
-
- /**
- * Notifies this engine instance that no more inbound network data will be
- * sent to this engine.
- *
- * @throws SSLException
- * if this engine did not receive a needed protocol specific
- * close notification message from the peer.
- */
- public abstract void closeInbound() throws SSLException;
-
- /**
- * Notifies this engine instance that no more outbound application data will
- * be sent to this engine.
- */
- public abstract void closeOutbound();
-
- /**
- * Returns a delegate task for this engine instance. Some engine operations
- * may require the results of blocking or long running operations, and the
- * {@code SSLEngineResult} instances returned by this engine may indicate
- * that a delegated task result is needed. In this case the
- * {@link Runnable#run() run} method of the returned {@code Runnable}
- * delegated task must be called.
- *
- * @return a delegate task, or {@code null} if none are available.
- */
- public abstract Runnable getDelegatedTask();
-
- /**
- * Returns the SSL cipher suite names that are enabled in this engine
- * instance.
- *
- * @return the SSL cipher suite names that are enabled in this engine
- * instance.
- */
- public abstract String[] getEnabledCipherSuites();
-
- /**
- * Returns the protocol version names that are enabled in this engine
- * instance.
- *
- * @return the protocol version names that are enabled in this engine
- * instance.
- */
- public abstract String[] getEnabledProtocols();
-
- /**
- * Returns whether new SSL sessions may be established by this engine.
- *
- * @return {@code true} if new session may be established, {@code false} if
- * existing sessions must be reused.
- */
- public abstract boolean getEnableSessionCreation();
-
- /**
- * Returns the status of the handshake of this engine instance.
- *
- * @return the status of the handshake of this engine instance.
- */
- public abstract SSLEngineResult.HandshakeStatus getHandshakeStatus();
-
- /**
- * Returns whether this engine instance will require client authentication.
- *
- * @return {@code true} if this engine will require client authentication,
- * {@code false} if no client authentication is needed.
- */
- public abstract boolean getNeedClientAuth();
-
- /**
- * Returns the SSL session for this engine instance.
- *
- * @return the SSL session for this engine instance.
- */
- public abstract SSLSession getSession();
-
- /**
- * Returns the SSL cipher suite names that are supported by this engine.
- * These cipher suites can be enabled using
- * {@link #setEnabledCipherSuites(String[])}.
- *
- * @return the SSL cipher suite names that are supported by this engine.
- */
- public abstract String[] getSupportedCipherSuites();
-
- /**
- * Returns the protocol names that are supported by this engine. These
- * protocols can be enables using {@link #setEnabledProtocols(String[])}.
- *
- * @return the protocol names that are supported by this engine.
- */
- public abstract String[] getSupportedProtocols();
-
- /**
- * Returns whether this engine is set to act in client mode when
- * handshaking.
- *
- * @return {@code true} if the engine is set to do handshaking in client
- * mode.
- */
- public abstract boolean getUseClientMode();
-
- /**
- * Returns whether this engine will request client authentication.
- *
- * @return {@code true} if client authentication will be requested,
- * {@code false} otherwise.
- */
- public abstract boolean getWantClientAuth();
-
- /**
- * Returns whether no more inbound data will be accepted by this engine.
- *
- * @return {@code true} if no more inbound data will be accepted by this
- * engine, {@code false} otherwise.
- */
- public abstract boolean isInboundDone();
-
- /**
- * Returns whether no more outbound data will be produced by this engine.
- *
- * @return {@code true} if no more outbound data will be producted by this
- * engine, {@code otherwise} false.
- */
- public abstract boolean isOutboundDone();
-
- /**
- * Sets the SSL cipher suite names that should be enabled in this engine
- * instance. Only cipher suites listed by {@code getSupportedCipherSuites()}
- * are allowed.
- *
- * @param suites
- * the SSL cipher suite names to be enabled.
- * @throws IllegalArgumentException
- * if one of the specified cipher suites is not supported, or if
- * {@code suites} is {@code null}.
- */
- public abstract void setEnabledCipherSuites(String[] suites);
-
- /**
- * Sets the protocol version names that should be enabled in this engine
- * instance. Only protocols listed by {@code getSupportedProtocols()} are
- * allowed.
- *
- * @param protocols
- * the protocol version names to be enabled.
- * @throws IllegalArgumentException
- * if one of the protocol version names is not supported, or if
- * {@code protocols} is {@code null}.
- */
- public abstract void setEnabledProtocols(String[] protocols);
-
- /**
- * Sets whether new SSL sessions may be established by this engine instance.
- *
- * @param flag
- * {@code true} if new SSL sessions may be established,
- * {@code false} if existing SSL sessions must be reused.
- */
- public abstract void setEnableSessionCreation(boolean flag);
-
- /**
- * Sets whether this engine must require client authentication. The client
- * authentication is one of:
- * <ul>
- * <li>authentication required</li>
- * <li>authentication requested</li>
- * <li>no authentication needed</li>
- * </ul>
- * This method overrides the setting of {@link #setWantClientAuth(boolean)}.
- *
- * @param need
- * {@code true} if client authentication is required,
- * {@code false} if no authentication is needed.
- */
- public abstract void setNeedClientAuth(boolean need);
-
- /**
- * Sets whether this engine should act in client (or server) mode when
- * handshaking.
- *
- * @param mode
- * {@code true} if this engine should act in client mode,
- * {@code false} if not.
- * @throws IllegalArgumentException
- * if this method is called after starting the initial
- * handshake.
- */
- public abstract void setUseClientMode(boolean mode);
-
- /**
- * Sets whether this engine should request client authentication. The client
- * authentication is one of the following:
- * <ul>
- * <li>authentication required</li>
- * <li>authentication requested</li>
- * <li>no authentication needed</li>
- * </ul>
- * This method overrides the setting of {@link #setNeedClientAuth(boolean)}.
- *
- * @param want
- * {@code true} if client authentication should be requested,
- * {@code false} if no authentication is needed.
- */
- public abstract void setWantClientAuth(boolean want);
-
- /**
- * Decodes the incoming network data buffer into application data buffers.
- * If a handshake has not been started yet, it will automatically be
- * started.
- *
- * @param src
- * the buffer with incoming network data
- * @param dsts
- * the array of destination buffers for incoming application
- * data.
- * @param offset
- * the offset in the array of destination buffers to which data
- * is to be transferred.
- * @param length
- * the maximum number of destination buffers to be used.
- * @return the result object of this operation.
- * @throws SSLException
- * if a problem occurred while processing the data.
- * @throws IndexOutOfBoundsException
- * if {@code length} is greater than
- * {@code dsts.length - offset}.
- * @throws java.nio.ReadOnlyBufferException
- * if one of the destination buffers is read-only.
- * @throws IllegalArgumentException
- * if {@code src}, {@code dsts}, or one of the entries in
- * {@code dsts} is {@code null}.
- * @throws IllegalStateException
- * if the engine does not have all the needed settings (e.g.
- * client/server mode not set).
- */
- public abstract SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dsts, int offset, int length)
- throws SSLException;
-
- /**
- * Encodes the outgoing application data buffers into the network data
- * buffer. If a handshake has not been started yet, it will automatically be
- * started.
- *
- * @param srcs
- * the array of source buffers of outgoing application data.
- * @param offset
- * the offset in the array of source buffers from which data is
- * to be retrieved.
- * @param length
- * the maximum number of source buffers to be used.
- * @param dst
- * the destination buffer for network data.
- * @return the result object of this operation.
- * @throws SSLException
- * if a problem occurred while processing the data.
- * @throws IndexOutOfBoundsException
- * if {@code length} is greater than
- * {@code srcs.length - offset}.
- * @throws java.nio.ReadOnlyBufferException
- * if the destination buffer is readonly.
- * @throws IllegalArgumentException
- * if {@code srcs}, {@code dst}, or one the entries in
- * {@code srcs} is {@code null}.
- * @throws IllegalStateException
- * if the engine does not have all the needed settings (e.g.
- * client/server mode not set).
- */
- public abstract SSLEngineResult wrap(ByteBuffer[] srcs, int offset, int length, ByteBuffer dst)
- throws SSLException;
-
- /**
- * Decodes the incoming network data buffer into the application data
- * buffer. If a handshake has not been started yet, it will automatically be
- * started.
- *
- * @param src
- * the buffer with incoming network data
- * @param dst
- * the destination buffer for incoming application data.
- * @return the result object of this operation.
- * @throws SSLException
- * if a problem occurred while processing the data.
- * @throws java.nio.ReadOnlyBufferException
- * if one of the destination buffers is read-only.
- * @throws IllegalArgumentException
- * if {@code src} or {@code dst} is {@code null}.
- * @throws IllegalStateException
- * if the engine does not have all the needed settings (e.g.
- * client/server mode not set).
- */
- public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer dst) throws SSLException {
- return unwrap(src, new ByteBuffer[] { dst }, 0, 1);
- }
-
- /**
- * Decodes the incoming network data buffer into the application data
- * buffers. If a handshake has not been started yet, it will automatically
- * be started.
- *
- * @param src
- * the buffer with incoming network data
- * @param dsts
- * the array of destination buffers for incoming application
- * data.
- * @return the result object of this operation.
- * @throws SSLException
- * if a problem occurred while processing the data.
- * @throws java.nio.ReadOnlyBufferException
- * if one of the destination buffers is read-only.
- * @throws IllegalArgumentException
- * if {@code src} or {@code dsts} is {@code null}.
- * @throws IllegalStateException
- * if the engine does not have all the needed settings (e.g.
- * client/server mode not set).
- */
- public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dsts) throws SSLException {
- if (dsts == null) {
- throw new IllegalArgumentException("Byte buffer array dsts is null");
- }
- return unwrap(src, dsts, 0, dsts.length);
- }
-
- /**
- * Encodes the outgoing application data buffers into the network data
- * buffer. If a handshake has not been started yet, it will automatically be
- * started.
- *
- * @param srcs
- * the array of source buffers of outgoing application data.
- * @param dst
- * the destination buffer for network data.
- * @return the result object of this operation.
- * @throws SSLException
- * if a problem occurred while processing the data.
- * @throws java.nio.ReadOnlyBufferException
- * if the destination buffer is readonly.
- * @throws IllegalArgumentException
- * if {@code srcs} or {@code dst} is {@code null}.
- * @throws IllegalStateException
- * if the engine does not have all the needed settings (e.g.
- * client/server mode not set).
- */
- public SSLEngineResult wrap(ByteBuffer[] srcs, ByteBuffer dst) throws SSLException {
- if (srcs == null) {
- throw new IllegalArgumentException("Byte buffer array srcs is null");
- }
- return wrap(srcs, 0, srcs.length, dst);
- }
-
- /**
- * Encodes the outgoing application data buffer into the network data
- * buffer. If a handshake has not been started yet, it will automatically be
- * started.
- *
- * @param src
- * the source buffers of outgoing application data.
- * @param dst
- * the destination buffer for network data.
- * @return the result object of this operation.
- * @throws SSLException
- * if a problem occurred while processing the data.
- * @throws java.nio.ReadOnlyBufferException
- * if the destination buffer is readonly.
- * @throws IllegalArgumentException
- * if {@code src} or {@code dst} is {@code null}.
- * @throws IllegalStateException
- * if the engine does not have all the needed settings (e.g.
- * client/server mode not set).
- */
- public SSLEngineResult wrap(ByteBuffer src, ByteBuffer dst) throws SSLException {
- return wrap(new ByteBuffer[] { src }, 0, 1, dst);
- }
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLEngineResult.java b/x-net/src/main/java/javax/net/ssl/SSLEngineResult.java
deleted file mode 100644
index 8a98831..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLEngineResult.java
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-/**
- * The result object describing the state of the {@code SSLEngine} produced
- * by the {@code wrap()} and {@code unwrap()} operations.
- */
-public class SSLEngineResult {
-
- /**
- * The {@code enum} describing the state of the current handshake.
- */
- public enum HandshakeStatus {
- /**
- * No handshake in progress.
- */
- NOT_HANDSHAKING,
- /**
- * The handshake is finished.
- */
- FINISHED,
- /**
- * The results of one (or more) delegated tasks are needed to continue
- * the handshake.
- */
- NEED_TASK,
- /**
- * The engine must send data to the remote side to continue the
- * handshake.
- */
- NEED_WRAP,
- /**
- * The engine needs to receive data from the remote side to continue the
- * handshake.
- */
- NEED_UNWRAP
- }
-
- /**
- * The {@code enum} describing the result of the {@code SSLEngine}
- * operation.
- */
- public static enum Status {
- /**
- * The size of the destination buffer is too small to hold the result of
- * the current operation.
- */
- BUFFER_OVERFLOW,
- /**
- * There were not enough bytes available in the source buffer to
- * complete the current operation.
- */
- BUFFER_UNDERFLOW,
- /**
- * The operation closed this side of the communication or was already
- * closed.
- */
- CLOSED,
- /**
- * The operation completed successfully.
- */
- OK
- }
-
- // Store Status object
- private final SSLEngineResult.Status status;
-
- // Store HandshakeStatus object
- private final SSLEngineResult.HandshakeStatus handshakeStatus;
-
- // Store bytesConsumed
- private final int bytesConsumed;
-
- // Store bytesProduced
- private final int bytesProduced;
-
- /**
- * Creates a new {@code SSLEngineResult} instance with the specified state
- * values.
- *
- * @param status
- * the return value of the {@code SSLEngine} operation.
- * @param handshakeStatus
- * the status of the current handshake
- * @param bytesConsumed
- * the number of bytes retrieved from the source buffer(s).
- * @param bytesProduced
- * the number of bytes transferred to the destination buffer(s).
- * @throws IllegalArgumentException
- * if {@code status} or {@code handshakeStatus} is {@code null},
- * or if {@code bytesConsumed} or {@code bytesProduces} are
- * negative.
- */
- public SSLEngineResult(SSLEngineResult.Status status,
- SSLEngineResult.HandshakeStatus handshakeStatus, int bytesConsumed, int bytesProduced) {
- if (status == null) {
- throw new IllegalArgumentException("status is null");
- }
- if (handshakeStatus == null) {
- throw new IllegalArgumentException("handshakeStatus is null");
- }
- if (bytesConsumed < 0) {
- throw new IllegalArgumentException("bytesConsumed is negative");
- }
- if (bytesProduced < 0) {
- throw new IllegalArgumentException("bytesProduced is negative");
- }
- this.status = status;
- this.handshakeStatus = handshakeStatus;
- this.bytesConsumed = bytesConsumed;
- this.bytesProduced = bytesProduced;
- }
-
- /**
- * Returns the return value of the {@code SSLEngine} operation.
- *
- * @return the return value of the {@code SSLEngine} operation.
- */
- public final Status getStatus() {
- return status;
- }
-
- /**
- * Returns the status of the current handshake.
- *
- * @return the status of the current handshake.
- */
- public final HandshakeStatus getHandshakeStatus() {
- return handshakeStatus;
- }
-
- /**
- * Returns the number of bytes retrieved from the source buffer(s).
- *
- * @return the number of bytes retrieved from the source buffer(s).
- */
- public final int bytesConsumed() {
- return bytesConsumed;
- }
-
- /**
- * Returns the number of bytes transferred to the destination buffer(s).
- *
- * @return the number of bytes transferred to the destination buffer(s).
- */
- public final int bytesProduced() {
- return bytesProduced;
- }
-
- @Override
- public String toString() {
- return "SSLEngineReport: Status = " + status + " HandshakeStatus = " + handshakeStatus
- + "\n bytesConsumed = " + bytesConsumed + " bytesProduced = "
- + bytesProduced;
- }
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLException.java b/x-net/src/main/java/javax/net/ssl/SSLException.java
deleted file mode 100644
index 5d716f7..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLException.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.io.IOException;
-
-/**
- * The base class for all SSL related exceptions.
- */
-public class SSLException extends IOException {
- private static final long serialVersionUID = 4511006460650708967L;
-
- /**
- * Creates a new {@code SSLException} with the specified reason.
- *
- * @param reason
- * the reason for the exception.
- */
- public SSLException(String reason) {
- super(reason);
- }
-
- /**
- * Creates a new {@code SSLException} with the specified message and cause.
- *
- * @param message
- * the detail message for the exception.
- * @param cause
- * the cause.
- */
- public SSLException(String message, Throwable cause) {
- super(message);
- super.initCause(cause);
- }
-
- /**
- * Creates a new {@code SSLException} with the specified cause.
- *
- * @param cause
- * the cause
- */
- public SSLException(Throwable cause) {
- super(cause == null ? null : cause.toString());
- super.initCause(cause);
- }
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLHandshakeException.java b/x-net/src/main/java/javax/net/ssl/SSLHandshakeException.java
deleted file mode 100644
index 1c17ae7..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLHandshakeException.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-/**
- * The exception that is thrown when a handshake could not be completed
- * successfully.
- */
-public class SSLHandshakeException extends SSLException {
-
- private static final long serialVersionUID = -5045881315018326890L;
-
- /**
- * Creates a new {@code SSLHandshakeException} with the specified message.
- *
- * @param reason
- * the detail message for the exception.
- */
- public SSLHandshakeException(String reason) {
- super(reason);
- }
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLKeyException.java b/x-net/src/main/java/javax/net/ssl/SSLKeyException.java
deleted file mode 100644
index 6d81676..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLKeyException.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-/**
- * The exception that is thrown when an invalid SSL key is encountered.
- */
-public class SSLKeyException extends SSLException {
-
- private static final long serialVersionUID = -8071664081941937874L;
-
- /**
- * Creates a new {@code SSLKeyException} with the specified message.
- *
- * @param reason
- * the detail message for the exception.
- */
- public SSLKeyException(String reason) {
- super(reason);
- }
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLPeerUnverifiedException.java b/x-net/src/main/java/javax/net/ssl/SSLPeerUnverifiedException.java
deleted file mode 100644
index bb5bd64..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLPeerUnverifiedException.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-/**
- * The exception that is thrown when the identity of a peer has not beed
- * verified.
- */
-public class SSLPeerUnverifiedException extends SSLException {
-
- private static final long serialVersionUID = -8919512675000600547L;
-
- /**
- * Creates a new {@code SSLPeerUnverifiedException} with the specified
- * message.
- *
- * @param reason
- * the detail message for the exception.
- */
- public SSLPeerUnverifiedException(String reason) {
- super(reason);
- }
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLPermission.java b/x-net/src/main/java/javax/net/ssl/SSLPermission.java
deleted file mode 100644
index 5b5c76f..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLPermission.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.security.BasicPermission;
-
-/**
- * The class representing a network permission.
- * <p>
- * The following permissions are defined, allowing the specified action:
- * <dl>
- * <dt> {@code "setHostnameVerifier"} </dt>
- * <dd> setting a callback object for additional verification of a hostname mismatch.</dd>
- * <dt> {@code "getSSLSessionContext"} </dt>
- * <dd> getting the {@code SSLSessionContext} of an {@code SSLSession}.</dd>
- * </dl>
- */
-public final class SSLPermission extends BasicPermission {
-
- private static final long serialVersionUID = -3456898025505876775L;
-
- /**
- * Creates a new {@code SSLPermission} with the specified name.
- *
- * @param name
- * the permission name.
- */
- public SSLPermission(String name) {
- super(name);
- }
-
- /**
- * Creates a new {@code SSLPermission} with the specified name.
- *
- * @param name
- * the permission name.
- * @param actions
- * is ignored and should be {@code null}.
- */
- public SSLPermission(String name, String actions) {
- super(name, actions);
- }
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLProtocolException.java b/x-net/src/main/java/javax/net/ssl/SSLProtocolException.java
deleted file mode 100644
index 50ed74d..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLProtocolException.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-/**
- * The exception that is thrown when an error in the operation of the SSL
- * protocol is encountered.
- */
-public class SSLProtocolException extends SSLException {
-
- private static final long serialVersionUID = 5445067063799134928L;
-
- /**
- * Creates a new {@code SSLProtocolException} with the specified message.
- *
- * @param reason
- * the detail message for the exception.
- */
- public SSLProtocolException(String reason) {
- super(reason);
- }
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLServerSocket.java b/x-net/src/main/java/javax/net/ssl/SSLServerSocket.java
deleted file mode 100644
index 8bd8918..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLServerSocket.java
+++ /dev/null
@@ -1,232 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.ServerSocket;
-
-/**
- * The extension of {@code ServerSocket} which provides secure server sockets
- * based on protocols like SSL, TLS, or others.
- */
-public abstract class SSLServerSocket extends ServerSocket {
-
- /**
- * Only to be used by subclasses.
- * <p>
- * Creates a TCP server socket with the default authentication context.
- *
- * @throws IOException
- * if creating the socket fails.
- */
- protected SSLServerSocket() throws IOException {
- super();
- }
-
- /**
- * Only to be used by subclasses.
- * <p>
- * Creates a TCP server socket on the specified port with the default
- * authentication context. The connection's default backlog size is 50
- * connections.
- * @param port
- * the port to listen on.
- * @throws IOException
- * if creating the socket fails.
- */
- protected SSLServerSocket(int port) throws IOException {
- super(port);
- }
-
- /**
- * Only to be used by subclasses.
- * <p>
- * Creates a TCP server socket on the specified port using the specified
- * backlog and the default authentication context.
- *
- * @param port
- * the port to listen on.
- * @param backlog
- * the number of pending connections to queue.
- * @throws IOException
- * if creating the socket fails.
- */
- protected SSLServerSocket(int port, int backlog) throws IOException {
- super(port, backlog);
- }
-
- /**
- * Only to be used by subclasses.
- * <p>
- * Creates a TCP server socket on the specified port, using the specified
- * backlog, listening on the specified interface, and using the default
- * authentication context.
- *
- * @param port
- * the port the listen on.
- * @param backlog
- * the number of pending connections to queue.
- * @param address
- * the address of the interface to accept connections on.
- * @throws IOException
- * if creating the socket fails.
- */
- protected SSLServerSocket(int port, int backlog, InetAddress address) throws IOException {
- super(port, backlog, address);
- }
-
- /**
- * Returns the names of the enabled cipher suites to be used for new
- * connections.
- *
- * @return the names of the enabled cipher suites to be used for new
- * connections.
- */
- public abstract String[] getEnabledCipherSuites();
-
- /**
- * Sets the names of the cipher suites to be enabled for new connections.
- * Only cipher suites returned by {@link #getSupportedCipherSuites()} are
- * allowed.
- *
- * @param suites
- * the names of the to be enabled cipher suites.
- * @throws IllegalArgumentException
- * if one of the cipher suite names is not supported.
- */
- public abstract void setEnabledCipherSuites(String[] suites);
-
- /**
- * Returns the names of the supported cipher suites.
- *
- * @return the names of the supported cipher suites.
- */
- public abstract String[] getSupportedCipherSuites();
-
- /**
- * Returns the names of the supported protocols.
- *
- * @return the names of the supported protocols.
- */
- public abstract String[] getSupportedProtocols();
-
- /**
- * Returns the names of the enabled protocols to be used for new
- * connections.
- *
- * @return the names of the enabled protocols to be used for new
- * connections.
- */
- public abstract String[] getEnabledProtocols();
-
- /**
- * Sets the names of the protocols to be enabled for new connections. Only
- * protocols returned by {@link #getSupportedProtocols()} are allowed.
- *
- * @param protocols
- * the names of the to be enabled protocols.
- * @throws IllegalArgumentException
- * if one of the protocols is not supported.
- */
- public abstract void setEnabledProtocols(String[] protocols);
-
- /**
- * Sets whether server-mode connections will be configured to require client
- * authentication. The client authentication is one of the following:
- * <ul>
- * <li>authentication required</li>
- * <li>authentication requested</li>
- * <li>no authentication needed</li>
- * </ul>
- * This method overrides the setting of {@link #setWantClientAuth(boolean)}.
- *
- * @param need
- * {@code true} if client authentication is required,
- * {@code false} if no authentication is needed.
- */
- public abstract void setNeedClientAuth(boolean need);
-
- /**
- * Returns whether server-mode connections will be configured to require
- * client authentication.
- *
- * @return {@code true} if client authentication is required, {@code false}
- * if no client authentication is needed.
- */
- public abstract boolean getNeedClientAuth();
-
- /**
- * Sets whether server-mode connections will be configured to request client
- * authentication. The client authentication is one of the following:
- * <ul>
- * <li>authentication required</li>
- * <li>authentication requested</li>
- * <li>no authentication needed</li>
- * </ul>
- * This method overrides the setting of {@link #setNeedClientAuth(boolean)}.
- *
- * @param want
- * {@code true} if client authentication should be requested,
- * {@code false} if no authentication is needed.
- */
- public abstract void setWantClientAuth(boolean want);
-
- /**
- * Returns whether server-mode connections will be configured to request
- * client authentication.
- *
- * @return {@code true} is client authentication will be requested,
- * {@code false} if no client authentication is needed.
- */
- public abstract boolean getWantClientAuth();
-
- /**
- * Sets whether new connections should act in client mode when handshaking.
- *
- * @param mode
- * {@code true} if new connections should act in client mode,
- * {@code false} if not.
- */
- public abstract void setUseClientMode(boolean mode);
-
- /**
- * Returns whether new connection will act in client mode when handshaking.
- *
- * @return {@code true} if new connections will act in client mode when
- * handshaking, {@code false} if not.
- */
- public abstract boolean getUseClientMode();
-
- /**
- * Sets whether new SSL sessions may be established for new connections.
- *
- * @param flag
- * {@code true} if new SSL sessions may be established,
- * {@code false} if existing SSL sessions must be reused.
- */
- public abstract void setEnableSessionCreation(boolean flag);
-
- /**
- * Returns whether new SSL sessions may be established for new connections.
- *
- * @return {@code true} if new SSL sessions may be established,
- * {@code false} if existing SSL sessions must be reused.
- */
- public abstract boolean getEnableSessionCreation();
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLServerSocketFactory.java b/x-net/src/main/java/javax/net/ssl/SSLServerSocketFactory.java
deleted file mode 100644
index ccb2c5d..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLServerSocketFactory.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.security.Security;
-
-import javax.net.ServerSocketFactory;
-
-/**
- * The factory for SSL server sockets.
- */
-public abstract class SSLServerSocketFactory extends ServerSocketFactory {
- // TODO EXPORT CONTROL
-
- // The default SSL socket factory
- private static ServerSocketFactory defaultServerSocketFactory;
-
- private static String defaultName;
-
- /**
- * Returns the default {@code SSLServerSocketFactory} instance. The default
- * implementation is defined by the security property
- * "ssl.ServerSocketFactory.provider".
- *
- * @return the default {@code SSLServerSocketFactory} instance.
- */
- public static synchronized ServerSocketFactory getDefault() {
- if (defaultServerSocketFactory != null) {
- return defaultServerSocketFactory;
- }
- if (defaultName == null) {
- AccessController.doPrivileged(new PrivilegedAction<Void>() {
- public Void run() {
- defaultName = Security.getProperty("ssl.ServerSocketFactory.provider");
- if (defaultName != null) {
- ClassLoader cl = Thread.currentThread().getContextClassLoader();
- if (cl == null) {
- cl = ClassLoader.getSystemClassLoader();
- }
- try {
- final Class<?> ssfc = Class.forName(defaultName, true, cl);
- defaultServerSocketFactory = (ServerSocketFactory) ssfc.newInstance();
- } catch (Exception e) {
- }
- }
- return null;
- }
- });
- }
- if (defaultServerSocketFactory == null) {
- // Try to find in providers
- SSLContext context = DefaultSSLContext.getContext();
- if (context != null) {
- defaultServerSocketFactory = context.getServerSocketFactory();
- }
- }
- if (defaultServerSocketFactory == null) {
- // Use internal dummy implementation
- defaultServerSocketFactory = new DefaultSSLServerSocketFactory(
- "No ServerSocketFactory installed");
- }
- return defaultServerSocketFactory;
- }
-
- /**
- * Creates a new {@code SSLServerSocketFactory} instance.
- */
- protected SSLServerSocketFactory() {
- super();
- }
-
- /**
- * Returns the names of the cipher suites that are enabled by default.
- *
- * @return the names of the cipher suites that are enabled by default
- */
- public abstract String[] getDefaultCipherSuites();
-
- /**
- * Returns the list of supported cipher suites that could be enabled for an
- * SSL connection created by this factory.
- *
- * @return the list of supported cipher suites
- */
- public abstract String[] getSupportedCipherSuites();
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLSession.java b/x-net/src/main/java/javax/net/ssl/SSLSession.java
deleted file mode 100644
index 14a312a..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLSession.java
+++ /dev/null
@@ -1,231 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.security.Principal;
-import java.security.cert.Certificate;
-import javax.security.cert.X509Certificate;
-
-/**
- * The interface representing an SSL session.
- */
-public interface SSLSession {
-
- /**
- * Returns the maximum size that an application buffer can be for this
- * session.
- *
- * @return the maximum application buffer size.
- */
- public int getApplicationBufferSize();
-
- /**
- * Returns the name of the cipher suite used in this session.
- *
- * @return the name of the cipher suite used in this session.
- */
- public String getCipherSuite();
-
- /**
- * Returns the time this session was created, in milliseconds since midnight
- * January 1st 1970 UTC.
- *
- * @return the time the session was created.
- */
- public long getCreationTime();
-
- /**
- * Returns this sessions identifier.
- *
- * @return this sessions identifier.
- */
- public byte[] getId();
-
- /**
- * Returns the time this session was last accessed, in milliseconds since
- * midnight January 1st 1970 UTC.
- *
- * @return the time this session was last accessed.
- */
- public long getLastAccessedTime();
-
- /**
- * Returns the list of certificates that were used to identify the local
- * side to the peer during the handshake.
- *
- * @return the list of certificates, ordered from local certificate to
- * CA's certificates.
- */
- public Certificate[] getLocalCertificates();
-
- /**
- * Returns the principal used to identify the local side to the peer during
- * the handshake.
- *
- * @return the principal used to identify the local side.
- */
- public Principal getLocalPrincipal();
-
- /**
- * Returns the maximum size that a network buffer can be for this session.
- *
- * @return the maximum network buffer size.
- */
- public int getPacketBufferSize();
-
- /**
- * Returns the list of certificates the peer used to identify itself during
- * the handshake.
- * <p>
- * Note: this method exists for compatility reasons, use
- * {@link #getPeerCertificates()} instead.
- *
- * @return the list of certificates, ordered from the identity certificate to
- * the CA's certificates
- * @throws SSLPeerUnverifiedException
- * if the identity of the peer is not verified.
- */
- public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException;
-
- /**
- * Returns the list of certificates the peer used to identify itself during
- * the handshake.
- *
- * @return the list of certificates, ordered from the identity certificate to
- * the CA's certificates.
- * @throws SSLPeerUnverifiedException
- * if the identity of the peer is not verified.
- */
- public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException;
-
- /**
- * Returns the host name of the peer of this session. The host name is not
- * authenticated.
- *
- * @return the host name of the peer of this session, or {@code null} if no
- * host name is available.
- */
- public String getPeerHost();
-
- /**
- * Returns the port number of the peer of this session. The port number is
- * not authenticated.
- *
- * @return the port number of the peer, of {@code -1} is no port number is
- * available.
- */
- public int getPeerPort();
-
- /**
- * Returns the principal identifying the peer during the handshake.
- *
- * @return the principal identifying the peer.
- * @throws SSLPeerUnverifiedException
- * if the identity of the peer has not been verified.
- */
- public Principal getPeerPrincipal() throws SSLPeerUnverifiedException;
-
- /**
- * Returns the protocol name that is used for all connections in this
- * session.
- *
- * @return the protocol name that is used for all connections in this
- * session.
- */
- public String getProtocol();
-
- /**
- * Returns the context of this session. If a context is available and a
- * security manager is installed, the
- * {@code SSLPermission("getSSLSessionContext"} is checked with the security
- * manager.
- *
- * @return the context of this session or {@code null} if no context is
- * available.
- */
- public SSLSessionContext getSessionContext();
-
- /**
- * Returns the object bound to the specified name in this session's
- * application layer data.
- *
- * @param name
- * the name of the bound value.
- * @return the value bound to the specified name, or {@code null} if the
- * specified name does not exist or is not accessible in the current
- * access control context.
- * @throws IllegalArgumentException
- * if {@code name} is {@code null}.
- */
- public Object getValue(String name);
-
- /**
- * Returns the list of the object names bound to this session's application
- * layer data..
- * <p>
- * Depending on the current access control context, the list of object names
- * may be different.
- *
- * @return the list of the object names bound to this session's application
- * layer data.
- */
- public String[] getValueNames();
-
- /**
- * Invalidates this session.
- * <p>
- * No new connections can be created, but any existing connection remains
- * valid until it is closed.
- */
- public void invalidate();
-
- /**
- * Returns whether this session is valid.
- *
- * @return {@code true} if this session is valid, otherwise {@code false}.
- */
- public boolean isValid();
-
- /**
- * Binds the specified object under the specified name in this session's
- * application layer data.
- * <p>
- * For bindings (new or existing) implementing the
- * {@code SSLSessionBindingListener} interface the object will be notified.
- *
- * @param name
- * the name to bind the object to.
- * @param value
- * the object to bind.
- * @throws IllegalArgumentException
- * if either {@code name} or {@code value} is {@code null}.
- */
- public void putValue(String name, Object value);
-
- /**
- * Removes the binding for the specified name in this session's application
- * layer data. If the existing binding implements the
- * {@code SSLSessionBindingListener} interface the object will be notified.
- *
- * @param name
- * the binding to remove.
- * @throws IllegalArgumentException
- * if {@code name} is {@code null}.
- */
- public void removeValue(String name);
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLSessionBindingEvent.java b/x-net/src/main/java/javax/net/ssl/SSLSessionBindingEvent.java
deleted file mode 100644
index 19ae835..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLSessionBindingEvent.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.io.Serializable;
-import java.util.EventObject;
-
-/**
- * The event sent to an {@code SSLSessionBindingListener} when the listener
- * object is bound ({@link SSLSession#putValue(String, Object)}) or unbound
- * ({@link SSLSession#removeValue(String)}) to an {@code SSLSession}.
- */
-public class SSLSessionBindingEvent extends EventObject implements Serializable {
-
- /**
- * The 5.0 spec. doesn't declare this serialVersionUID field In order to be compatible it is
- * explicitly declared here
- */
- private static final long serialVersionUID = 3989172637106345L;
-
- /**
- * @serial include
- */
- private final String name;
-
- /**
- * Creates a new {@code SSLSessionBindingEvent} for the specified session
- * indicating a binding event for the specified name.
- *
- * @param session
- * the session for which the event occurs.
- * @param name
- * the name of the object being (un)bound.
- */
- public SSLSessionBindingEvent(SSLSession session, String name) {
- super(session);
- this.name = name;
- }
-
- /**
- * Returns the name of the binding being added or removed.
- *
- * @return the name of the binding.
- */
- public String getName() {
- return name;
- }
-
- /**
- * Returns the session to which the binding is added or from which it is
- * removed.
- *
- * @return the session to which the binding is added or from which it is
- * removed.
- */
- public SSLSession getSession() {
- return (SSLSession) this.source;
- }
-
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLSessionBindingListener.java b/x-net/src/main/java/javax/net/ssl/SSLSessionBindingListener.java
deleted file mode 100644
index 43ad745..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLSessionBindingListener.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.util.EventListener;
-
-/**
- * The interface to be implemented by any object that requires notification when
- * data objects are bound to (or unbound from) an {@code SSLSession}.
- */
-public interface SSLSessionBindingListener extends EventListener {
-
- /**
- * Notifies this listener when a value is bound to an {@code SSLSession}.
- *
- * @param event
- * the event data.
- */
- public void valueBound(SSLSessionBindingEvent event);
-
- /**
- * Notifies this listener when a value is unbound from an {@code SSLSession}.
- *
- * @param event
- * the event data.
- */
- public void valueUnbound(SSLSessionBindingEvent event);
-
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLSessionContext.java b/x-net/src/main/java/javax/net/ssl/SSLSessionContext.java
deleted file mode 100644
index 154376e..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLSessionContext.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.util.Enumeration;
-
-/**
- * A collection of {@code SSLSession}s.
- */
-public interface SSLSessionContext {
- /**
- * Returns an iterable of all session identifiers in this session context.
- *
- * @return an iterable of all session identifiers in this session context.
- */
- @SuppressWarnings("unchecked")
- public Enumeration getIds();
-
- /**
- * Returns the session for the specified session identifier.
- *
- * @param sessionId
- * the session identifier of the session to look up.
- * @return the session for the specified session identifier, or {@code null}
- * if the specified session identifier does not refer to a session
- * in this context.
- */
- public SSLSession getSession(byte[] sessionId);
-
- /**
- * Returns the size of the session cache for this session context.
- *
- * @return the size of the session cache for this session context, or
- * {@code zero} if unlimited.
- */
- public int getSessionCacheSize();
-
- /**
- * Returns the timeout for sessions in this session context. Sessions
- * exceeding the timeout are invalidated.
- *
- * @return the timeout in seconds, or {@code zero} if unlimited.
- */
- public int getSessionTimeout();
-
- /**
- * Sets the size of the session cache for this session context.
- *
- * @param size
- * the size of the session cache, or {@code zero} for unlimited
- * cache size.
- * @throws IllegalArgumentException
- * if {@code size} is negative.
- */
- public void setSessionCacheSize(int size) throws IllegalArgumentException;
-
- /**
- * Sets the timeout for sessions in this context. Sessions exceeding the
- * timeout are invalidated.
- *
- * @param seconds
- * the timeout in seconds, or {@code zero} if unlimited.
- * @throws IllegalArgumentException
- * if {@code seconds} is negative.
- */
- public void setSessionTimeout(int seconds) throws IllegalArgumentException;
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLSocket.java b/x-net/src/main/java/javax/net/ssl/SSLSocket.java
deleted file mode 100644
index 4a70843..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLSocket.java
+++ /dev/null
@@ -1,299 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.net.UnknownHostException;
-
-/**
- * The extension of {@code Socket} providing secure protocols like SSL (Secure
- * Socket Layer") or TLS (Transport Layer Security).
- */
-public abstract class SSLSocket extends Socket {
-
- /**
- * Only to be used by subclasses.
- * <p>
- * Creates a TCP socket.
- */
- protected SSLSocket() {
- super();
- }
-
- /**
- * Only to be used by subclasses.
- * <p>
- * Creates a TCP socket connection to the specified host at the specified
- * port.
- *
- * @param host
- * the host name to connect to.
- * @param port
- * the port number to connect to.
- * @throws IOException
- * if creating the socket fails.
- * @throws UnknownHostException
- * if the specified host is not known.
- */
- protected SSLSocket(String host, int port) throws IOException, UnknownHostException {
- super(host, port);
- }
-
- /**
- * Only to be used by subclasses.
- * <p>
- * Creates a TCP socket connection to the specified address at the specified
- * port.
- *
- * @param address
- * the address to connect to.
- * @param port
- * the port number to connect to.
- * @throws IOException
- * if creating the socket fails.
- */
- protected SSLSocket(InetAddress address, int port) throws IOException {
- super(address, port);
- }
-
- /**
- * Only to be used by subclasses.
- * <p>
- * Creates a TCP socket connection to the specified host at the specified
- * port with the client side bound to the specified address and port.
- *
- * @param host
- * the host name to connect to.
- * @param port
- * the port number to connect to.
- * @param clientAddress
- * the client address to bind to
- * @param clientPort
- * the client port number to bind to.
- * @throws IOException
- * if creating the socket fails.
- * @throws UnknownHostException
- * if the specified host is not known.
- */
- protected SSLSocket(String host, int port, InetAddress clientAddress, int clientPort)
- throws IOException, UnknownHostException {
- super(host, port, clientAddress, clientPort);
- }
-
- /**
- * Only to be used by subclasses.
- * <p>
- * Creates a TCP socket connection to the specified address at the specified
- * port with the client side bound to the specified address and port.
- *
- * @param address
- * the address to connect to.
- * @param port
- * the port number to connect to.
- * @param clientAddress
- * the client address to bind to.
- * @param clientPort
- * the client port number to bind to.
- * @throws IOException
- * if creating the socket fails.
- */
- protected SSLSocket(InetAddress address, int port, InetAddress clientAddress, int clientPort)
- throws IOException {
- super(address, port, clientAddress, clientPort);
- }
-
- /**
- * Returns the names of the supported cipher suites.
- *
- * @return the names of the supported cipher suites.
- */
- public abstract String[] getSupportedCipherSuites();
-
- /**
- * Returns the names of the enabled cipher suites.
- *
- * @return the names of the enabled cipher suites.
- */
- public abstract String[] getEnabledCipherSuites();
-
- /**
- * Sets the names of the cipher suites to be enabled.
- * Only cipher suites returned by {@link #getSupportedCipherSuites()} are
- * allowed.
- *
- * @param suites
- * the names of the to be enabled cipher suites.
- * @throws IllegalArgumentException
- * if one of the cipher suite names is not supported.
- */
- public abstract void setEnabledCipherSuites(String[] suites);
-
- /**
- * Returns the names of the supported protocols.
- *
- * @return the names of the supported protocols.
- */
- public abstract String[] getSupportedProtocols();
-
- /**
- * Returns the names of the enabled protocols.
- *
- * @return the names of the enabled protocols.
- */
- public abstract String[] getEnabledProtocols();
-
- /**
- * Sets the names of the protocols to be enabled. Only
- * protocols returned by {@link #getSupportedProtocols()} are allowed.
- *
- * @param protocols
- * the names of the to be enabled protocols.
- * @throws IllegalArgumentException
- * if one of the protocols is not supported.
- */
- public abstract void setEnabledProtocols(String[] protocols);
-
- /**
- * Returns the {@code SSLSession} for this connection. If necessary, a
- * handshake will be initiated, in which case this method will block until the handshake
- * has been established. If the handshake fails, an invalid session object
- * will be returned.
- *
- * @return the session object.
- */
- public abstract SSLSession getSession();
-
- /**
- * Registers the specified listener to receive notification on completion of a
- * handshake on this connection.
- *
- * @param listener
- * the listener to register.
- * @throws IllegalArgumentException
- * if {@code listener} is {@code null}.
- */
- public abstract void addHandshakeCompletedListener(HandshakeCompletedListener listener);
-
- /**
- * Removes the specified handshake completion listener.
- *
- * @param listener
- * the listener to remove.
- * @throws IllegalArgumentException
- * if the specified listener is not registered or {@code null}.
- */
- public abstract void removeHandshakeCompletedListener(HandshakeCompletedListener listener);
-
- /**
- * Starts a new SSL handshake on this connection.
- *
- * @throws IOException
- * if an error occurs.
- */
- public abstract void startHandshake() throws IOException;
-
- /**
- * Sets whether this connection should act in client mode when handshaking.
- *
- * @param mode
- * {@code true} if this connection should act in client mode,
- * {@code false} if not.
- */
- public abstract void setUseClientMode(boolean mode);
-
- /**
- * Returns whether this connection will act in client mode when handshaking.
- *
- * @return {@code true} if this connections will act in client mode when
- * handshaking, {@code false} if not.
- */
- public abstract boolean getUseClientMode();
-
- /**
- * Sets whether this connection should require client authentication. This
- * is only useful for sockets in server mode. The client authentication is
- * one of the following:
- * <ul>
- * <li>authentication required</li>
- * <li>authentication requested</li>
- * <li>no authentication needed</li>
- * </ul>
- * This method overrides the setting of {@link #setWantClientAuth(boolean)}.
- *
- * @param need
- * {@code true} if client authentication is required,
- * {@code false} if no authentication is needed.
- */
- public abstract void setNeedClientAuth(boolean need);
-
- /**
- * Returns whether this connection requires client authentication.
- * This is only useful for sockets in server mode.
- *
- * @return {@code true} if client authentication is required, {@code false}
- * if no client authentication is needed.
- */
- public abstract boolean getNeedClientAuth();
-
- /**
- * Sets whether this connections should request client authentication. This
- * is only useful for sockets in server mode. The client authentication is
- * one of:
- * <ul>
- * <li>authentication required</li>
- * <li>authentication requested</li>
- * <li>no authentication needed</li>
- * </ul>
- * This method overrides the setting of {@link #setNeedClientAuth(boolean)}.
- *
- * @param want
- * {@code true} if client authentication should be requested,
- * {@code false} if not authentication is needed.
- */
- public abstract void setWantClientAuth(boolean want);
-
- /**
- * Returns whether this connections will request client authentication.
- *
- * @return {@code true} is client authentication will be requested,
- * {@code false} if no client authentication is needed.
- */
- public abstract boolean getWantClientAuth();
-
- /**
- * Sets whether new SSL sessions may be created by this socket or if
- * existing sessions must be reused.
- *
- * @param flag
- * {@code true} if new sessions may be created, otherwise
- * {@code false}.
- */
- public abstract void setEnableSessionCreation(boolean flag);
-
- /**
- * Returns whether new SSL sessions may be created by this socket or if
- * existing sessions must be reused.
- *
- * @return {@code true} if new sessions may be created, otherwise
- * {@code false}.
- */
- public abstract boolean getEnableSessionCreation();
-
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLSocketFactory.java b/x-net/src/main/java/javax/net/ssl/SSLSocketFactory.java
deleted file mode 100644
index b75c218..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLSocketFactory.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.io.IOException;
-import java.net.Socket;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.security.Security;
-// BEGIN android-added
-import java.util.logging.Level;
-import java.util.logging.Logger;
-// END android-added
-
-import javax.net.SocketFactory;
-
-/**
- * The abstract factory implementation to create {@code SSLSocket}s.
- */
-public abstract class SSLSocketFactory extends SocketFactory {
- // FIXME EXPORT CONTROL
-
- // The default SSL socket factory
- private static SocketFactory defaultSocketFactory;
-
- private static String defaultName;
-
- /**
- * Returns the default {@code SSLSocketFactory} instance. The default is
- * defined by the security property {@code 'ssl.SocketFactory.provider'}.
- *
- * @return the default ssl socket factory instance.
- */
- public static synchronized SocketFactory getDefault() {
- if (defaultSocketFactory != null) {
- // BEGIN android-added
- // log("SSLSocketFactory", "Using factory " + defaultSocketFactory, null);
- // END android-added
- return defaultSocketFactory;
- }
- if (defaultName == null) {
- AccessController.doPrivileged(new PrivilegedAction<Void>() {
- public Void run() {
- defaultName = Security.getProperty("ssl.SocketFactory.provider");
- if (defaultName != null) {
- ClassLoader cl = Thread.currentThread().getContextClassLoader();
- if (cl == null) {
- cl = ClassLoader.getSystemClassLoader();
- }
- try {
- final Class<?> sfc = Class.forName(defaultName, true, cl);
- defaultSocketFactory = (SocketFactory) sfc.newInstance();
- } catch (Exception e) {
- // BEGIN android-added
- log("SSLSocketFactory", "Problem creating " + defaultName, e);
- // END android-added
- }
- }
- return null;
- }
- });
- }
-
- if (defaultSocketFactory == null) {
- // Try to find in providers
- SSLContext context = DefaultSSLContext.getContext();
- if (context != null) {
- defaultSocketFactory = context.getSocketFactory();
- }
- }
- if (defaultSocketFactory == null) {
- // Use internal implementation
- defaultSocketFactory = new DefaultSSLSocketFactory("No SSLSocketFactory installed");
- }
- // BEGIN android-added
- // log("SSLSocketFactory", "Using factory " + defaultSocketFactory, null);
- // END android-added
- return defaultSocketFactory;
- }
-
- // BEGIN android-added
- @SuppressWarnings("unchecked")
- private static void log(String tag, String msg, Throwable throwable) {
- Logger.getLogger(tag).log(Level.INFO, msg, throwable);
- }
- // END android-added
-
- /**
- * Creates a new {@code SSLSocketFactory}.
- */
- public SSLSocketFactory() {
- super();
- }
-
- /**
- * Returns the names of the cipher suites that are enabled by default.
- *
- * @return the names of the cipher suites that are enabled by default.
- */
- public abstract String[] getDefaultCipherSuites();
-
- /**
- * Returns the names of the cipher suites that are supported and could be
- * enabled for an SSL connection.
- *
- * @return the names of the cipher suites that are supported.
- */
- public abstract String[] getSupportedCipherSuites();
-
- /**
- * Creates an {@code SSLSocket} over the specified socket that is connected
- * to the specified host at the specified port.
- *
- * @param s
- * the socket.
- * @param host
- * the host.
- * @param port
- * the port number.
- * @param autoClose
- * {@code true} if socket {@code s} should be closed when the
- * created socket is closed, {@code false} if the socket
- * {@code s} should be left open.
- * @return the creates ssl socket.
- * @throws IOException
- * if creating the socket fails.
- * @throws java.net.UnknownHostException
- * if the host is unknown.
- */
- public abstract Socket createSocket(Socket s, String host, int port, boolean autoClose)
- throws IOException;
-}
diff --git a/x-net/src/main/java/javax/net/ssl/TrustManager.java b/x-net/src/main/java/javax/net/ssl/TrustManager.java
deleted file mode 100644
index 9bdb16b..0000000
--- a/x-net/src/main/java/javax/net/ssl/TrustManager.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-/**
- * The marker interface for JSSE trust managers. The purpose is to group trust
- * managers. The responsibility a trust manager is to handle the trust data used to
- * make trust decisions for deciding whether credentials of a peer should be
- * accepted,
- * @see TrustManagerFactory
- */
-public interface TrustManager {
-}
diff --git a/x-net/src/main/java/javax/net/ssl/TrustManagerFactory.java b/x-net/src/main/java/javax/net/ssl/TrustManagerFactory.java
deleted file mode 100644
index 6d9e4c9..0000000
--- a/x-net/src/main/java/javax/net/ssl/TrustManagerFactory.java
+++ /dev/null
@@ -1,229 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.security.AccessController;
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.PrivilegedAction;
-import java.security.Provider;
-import java.security.Security;
-
-import org.apache.harmony.security.fortress.Engine;
-
-/**
- * The factory for {@code TrustManager}s based on {@code KeyStore} or provider
- * specific implementation.
- */
-public class TrustManagerFactory {
- // Store TrustManager service name
- private static final String SERVICE = "TrustManagerFactory";
-
- // Used to access common engine functionality
- private static Engine engine = new Engine(SERVICE);
-
- // Store default property name
- private static final String PROPERTYNAME = "ssl.TrustManagerFactory.algorithm";
-
- /**
- * Returns the default algorithm name for the {@code TrustManagerFactory}. The
- * default algorithm name is specified by the security property
- * {@code 'ssl.TrustManagerFactory.algorithm'}.
- *
- * @return the default algorithm name.
- */
- public static final String getDefaultAlgorithm() {
- return AccessController.doPrivileged(new PrivilegedAction<String>() {
- public String run() {
- return Security.getProperty(PROPERTYNAME);
- }
- });
- }
-
- /**
- * Creates a new {@code TrustManagerFactory} instance for the specified
- * trust management algorithm.
- *
- * @param algorithm
- * the name of the requested trust management algorithm.
- * @return a trust manager factory for the requested algorithm.
- * @throws NoSuchAlgorithmException
- * if no installed provider can provide the requested algorithm.
- * @throws NullPointerException
- * if {@code algorithm} is {@code null} (instead of
- * NoSuchAlgorithmException as in 1.4 release)
- */
- public static final TrustManagerFactory getInstance(String algorithm)
- throws NoSuchAlgorithmException {
- if (algorithm == null) {
- throw new NullPointerException("algorithm is null");
- }
- synchronized (engine) {
- engine.getInstance(algorithm, null);
- return new TrustManagerFactory((TrustManagerFactorySpi) engine.spi, engine.provider,
- algorithm);
- }
- }
-
- /**
- * Creates a new {@code TrustManagerFactory} instance for the specified
- * trust management algorithm from the specified provider.
- *
- * @param algorithm
- * the name of the requested trust management algorithm name.
- * @param provider
- * the name of the provider that provides the requested
- * algorithm.
- * @return a trust manager factory for the requested algorithm.
- * @throws NoSuchAlgorithmException
- * if the specified provider cannot provide the requested
- * algorithm.
- * @throws NoSuchProviderException
- * if the specified provider does not exist.
- * @throws NullPointerException
- * if {@code algorithm} is {@code null} (instead of
- * NoSuchAlgorithmException as in 1.4 release)
- */
- public static final TrustManagerFactory getInstance(String algorithm, String provider)
- throws NoSuchAlgorithmException, NoSuchProviderException {
- if ((provider == null) || (provider.length() == 0)) {
- throw new IllegalArgumentException("Provider is null oe empty");
- }
- Provider impProvider = Security.getProvider(provider);
- if (impProvider == null) {
- throw new NoSuchProviderException(provider);
- }
- return getInstance(algorithm, impProvider);
- }
-
- /**
- * Creates a new {@code TrustManagerFactory} instance for the specified
- * trust management algorithm from the specified provider.
- *
- * @param algorithm
- * the name of the requested key management algorithm name.
- * @param provider
- * the provider that provides the requested algorithm.
- * @return a key manager factory for the requested algorithm.
- * @throws NoSuchAlgorithmException
- * if the specified provider cannot provide the requested
- * algorithm.
- * @throws NullPointerException
- * if {@code algorithm} is {@code null} (instead of
- * NoSuchAlgorithmException as in 1.4 release)
- */
- public static final TrustManagerFactory getInstance(String algorithm, Provider provider)
- throws NoSuchAlgorithmException {
- if (provider == null) {
- throw new IllegalArgumentException("Provider is null");
- }
- if (algorithm == null) {
- throw new NullPointerException("algorithm is null");
- }
- synchronized (engine) {
- engine.getInstance(algorithm, provider, null);
- return new TrustManagerFactory((TrustManagerFactorySpi) engine.spi, provider, algorithm);
- }
- }
-
- // Store used provider
- private final Provider provider;
-
- // Store used TrustManagerFactorySpi implementation
- private final TrustManagerFactorySpi spiImpl;
-
- // Store used algorithm
- private final String algorithm;
-
- /**
- * Creates a new {@code TrustManagerFactory} instance.
- *
- * @param factorySpi
- * the implementation delegate.
- * @param provider
- * the provider
- * @param algorithm
- * the algorithm name.
- */
- protected TrustManagerFactory(TrustManagerFactorySpi factorySpi, Provider provider,
- String algorithm) {
- this.provider = provider;
- this.algorithm = algorithm;
- this.spiImpl = factorySpi;
- }
-
- /**
- * Returns the name of this {@code TrustManagerFactory} algorithm
- * implementation.
- *
- * @return the name of this {@code TrustManagerFactory} algorithm
- * implementation.
- */
- public final String getAlgorithm() {
- return algorithm;
- }
-
- /**
- * Returns the provider for this {@code TrustManagerFactory} instance.
- *
- * @return the provider for this {@code TrustManagerFactory} instance.
- */
- public final Provider getProvider() {
- return provider;
- }
-
- /**
- * Initializes this factory instance with the specified keystore as source
- * of certificate authorities and trust material.
- *
- * @param ks
- * the keystore or {@code null}.
- * @throws KeyStoreException
- * if the initialization fails.
- */
- public final void init(KeyStore ks) throws KeyStoreException {
- spiImpl.engineInit(ks);
- }
-
- /**
- * Initializes this factory instance with the specified provider-specific
- * parameters for a source of trust material.
- *
- * @param spec
- * the provider-specific parameters.
- * @throws InvalidAlgorithmParameterException
- * if the initialization fails.
- */
- public final void init(ManagerFactoryParameters spec) throws InvalidAlgorithmParameterException {
- spiImpl.engineInit(spec);
- }
-
- /**
- * Returns the list of {@code TrustManager}s with one entry for each type
- * of trust material.
- *
- * @return the list of {@code TrustManager}s
- */
- public final TrustManager[] getTrustManagers() {
- return spiImpl.engineGetTrustManagers();
- }
-
-}
diff --git a/x-net/src/main/java/javax/net/ssl/TrustManagerFactorySpi.java b/x-net/src/main/java/javax/net/ssl/TrustManagerFactorySpi.java
deleted file mode 100644
index 1b04c5b..0000000
--- a/x-net/src/main/java/javax/net/ssl/TrustManagerFactorySpi.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-
-/**
- * The <i>Service Provider Interface</i> (SPI) for the
- * {@code TrustManagerFactory} class.
- */
-public abstract class TrustManagerFactorySpi {
-
- /**
- * Creates a new {@code TrustManagerFactorySpi} instance.
- */
- public TrustManagerFactorySpi() {
- super();
- }
-
- /**
- * Initializes this factory instance with the specified keystore as source
- * of certificate authorities and trust material.
- *
- * @param ks
- * the keystore or {@code null}.
- * @throws KeyStoreException
- * if the initialization fails.
- */
- protected abstract void engineInit(KeyStore ks) throws KeyStoreException;
-
- /**
- * Initializes this factory instance with the specified provider-specific
- * parameters for a source of trust material.
- *
- * @param spec
- * the provider-specific parameters.
- * @throws InvalidAlgorithmParameterException
- * if the initialization fails.
- */
- protected abstract void engineInit(ManagerFactoryParameters spec)
- throws InvalidAlgorithmParameterException;
-
- /**
- * Returns the list of {@code TrustManager}s with one entry for each type
- * of trust material.
- *
- * @return the list of {@code TrustManager}s
- */
- protected abstract TrustManager[] engineGetTrustManagers();
-}
diff --git a/x-net/src/main/java/javax/net/ssl/X509ExtendedKeyManager.java b/x-net/src/main/java/javax/net/ssl/X509ExtendedKeyManager.java
deleted file mode 100644
index 3298d8e..0000000
--- a/x-net/src/main/java/javax/net/ssl/X509ExtendedKeyManager.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.security.Principal;
-
-/**
- * The abstract extension for the {@code X509KeyManager} interface.
- */
-public abstract class X509ExtendedKeyManager implements X509KeyManager {
-
- /**
- * To be used by subclasses only.
- * <p>
- * Creates a new {@code X509ExtendedKeyManager} instance.
- */
- protected X509ExtendedKeyManager() {
- super();
- }
-
- /**
- * Chooses an alias for the client side of an SSL connection to authenticate
- * it with the specified public key type and certificate issuers.
- *
- * @param keyType
- * the list of public key algorithm names.
- * @param issuers
- * the list of certificate issuers, or {@code null} if any issuer
- * will do.
- * @param engine
- * the {@code SSLEngine} for the connection, or {@code null} if
- * no engine is predefined.
- * @return the alias name of a matching key or {@code null} if there are no
- * matches.
- */
- public String chooseEngineClientAlias(String[] keyType,
- Principal[] issuers, SSLEngine engine) {
- return null;
- }
-
- /**
- * Chooses an alias for the server side of an SSL connection to authenticate
- * it with the specified public key type and certificate issuers.
- *
- * @param keyType
- * the list of public key algorithm names.
- * @param issuers
- * the list of certificate issuers, or {@code null} if any issuer
- * will do.
- * @param engine
- * the {@code SSLEngine} for the connection, or {@code null} if
- * no engine is predefined.
- * @return the alias name of a matching key or {@code null} if there are no
- * matches.
- */
- public String chooseEngineServerAlias(String keyType, Principal[] issuers,
- SSLEngine engine) {
- return null;
- }
-
-}
diff --git a/x-net/src/main/java/javax/net/ssl/X509KeyManager.java b/x-net/src/main/java/javax/net/ssl/X509KeyManager.java
deleted file mode 100644
index aebc427..0000000
--- a/x-net/src/main/java/javax/net/ssl/X509KeyManager.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.net.Socket;
-import java.security.Principal;
-import java.security.PrivateKey;
-import java.security.cert.X509Certificate;
-
-/**
- * A Key Manager for X509 certificate-based key pairs.
- */
-public interface X509KeyManager extends KeyManager {
-
- /**
- * Chooses an alias for the client side of an SSL connection to authenticate
- * it with the specified public key type and certificate issuers.
- *
- * @param keyType
- * the list of public key algorithm names.
- * @param issuers
- * the list of certificate issuers, or {@code null} if any issuer
- * will do.
- * @param socket
- * the socket for the connection, or {@code null} if
- * the alias selected does not depend on a specific socket.
- * @return the alias name of a matching key or {@code null} if there are no
- * matches.
- */
- public String chooseClientAlias(String[] keyType, Principal[] issuers,
- Socket socket);
-
- /**
- * Chooses an alias for the server side of an SSL connection to authenticate
- * it with the specified public key type and certificate issuers.
- *
- * @param keyType
- * the list of public key algorithm type names.
- * @param issuers
- * the list of certificate issuers, or {@code null} if any issuer
- * will do.
- * @param socket
- * the socket for the connection, or {@code null} if
- * the alias selected does not depend on a specific socket.
- * @return the alias name of a matching key or {@code null} if there are no
- * matches.
- */
- public String chooseServerAlias(String keyType, Principal[] issuers,
- Socket socket);
-
- /**
- * Returns the certificate chain for the specified alias.
- *
- * @param alias
- * the alias to get the certificate chain for.
- * @return the certificate chain for the specified alias, or {@code null} if
- * the alias cannot be found.
- */
- public X509Certificate[] getCertificateChain(String alias);
-
- /**
- * Returns the client aliases for the specified public key type and list of
- * certificate issuers.
- *
- * @param keyType
- * the public key algorithm type name.
- * @param issuers
- * the list of certificate issuers, or {@code null} if any issuer
- * will do.
- * @return the client aliases for the specified public key type, or
- * {@code null} if there are no matching aliases.
- */
- public String[] getClientAliases(String keyType, Principal[] issuers);
-
- /**
- * Returns the server aliases for the specified public key type and list of
- * certificate issuers.
- *
- * @param keyType
- * the public key algorithm type name.
- * @param issuers
- * the list of certificate issuers, or {@code null} if any issuer
- * will do.
- * @return the client aliases for the specified public key type, or
- * {@code null} if there are no matching aliases.
- */
- public String[] getServerAliases(String keyType, Principal[] issuers);
-
- /**
- * Returns the private key for the specified alias.
- *
- * @param alias
- * the alias to get the private key for.
- * @return the private key for the specified alias, or {@code null} if the
- * alias cannot be found.
- */
- public PrivateKey getPrivateKey(String alias);
-}
diff --git a/x-net/src/main/java/javax/net/ssl/X509TrustManager.java b/x-net/src/main/java/javax/net/ssl/X509TrustManager.java
deleted file mode 100644
index 7d7827e..0000000
--- a/x-net/src/main/java/javax/net/ssl/X509TrustManager.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-
-/**
- * The trust manager for X509 certificates to be used to perform authentication
- * for secure sockets.
- */
-public interface X509TrustManager extends TrustManager {
-
- /**
- * Checks whether the specified certificate chain (partial or complete) can
- * be validated and is trusted for client authentication for the specified
- * authentication type.
- *
- * @param chain
- * the certificate chain to validate.
- * @param authType
- * the authentication type used.
- * @throws CertificateException
- * if the certificate chain can't be validated or isn't trusted.
- * @throws IllegalArgumentException
- * if the specified certificate chain is empty or {@code null},
- * or if the specified authentication type is {@code null} or an
- * empty string.
- */
- public void checkClientTrusted(X509Certificate[] chain, String authType)
- throws CertificateException;
-
-
- /**
- * Checks whether the specified certificate chain (partial or complete) can
- * be validated and is trusted for server authentication for the specified
- * key exchange algorithm.
- *
- * @param chain
- * the certificate chain to validate.
- * @param authType
- * the key exchange algorithm name.
- * @throws CertificateException
- * if the certificate chain can't be validated or isn't trusted.
- * @throws IllegalArgumentException
- * if the specified certificate chain is empty or {@code null},
- * or if the specified authentication type is {@code null} or an
- * empty string.
- */
- public void checkServerTrusted(X509Certificate[] chain, String authType)
- throws CertificateException;
-
- /**
- * Returns the list of certificate issuer authorities which are trusted for
- * authentication of peers.
- *
- * @return the list of certificate issuer authorities which are trusted for
- * authentication of peers.
- */
- public X509Certificate[] getAcceptedIssuers();
-}
diff --git a/x-net/src/main/java/javax/net/ssl/package.html b/x-net/src/main/java/javax/net/ssl/package.html
deleted file mode 100644
index 14753c8..0000000
--- a/x-net/src/main/java/javax/net/ssl/package.html
+++ /dev/null
@@ -1,20 +0,0 @@
-<html>
-<head>
-<meta http-equiv="Content-Type" content="text/html; charset=us-ascii">
-</head>
-<html>
-<body>
-<p>
-This package provides all the classes and interfaces needed to implement and program the Secure Socket
-abstraction based on the SSL protocol SSSLv3.0 or TLSv1.2.
-All the details of the SSL handshake protocol are accounted for, and a client or a server can specify the cipher
-set to use.
-
-X.509 certificates are verified, and, if desired, the client and the server each have the option of verifying
-the entire certificate chain until the root Certificate Authority is reached.
-
-Android uses code from The Legion of the Bouncy Castle (http://www.bouncycastle.org) and OpenSSL (http://openssl.org).
-
-</p>
-</body>
-</html>
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/AbstractSessionContext.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/AbstractSessionContext.java
deleted file mode 100644
index 7a0985e..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/AbstractSessionContext.java
+++ /dev/null
@@ -1,221 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.util.*;
-import java.util.logging.Level;
-import java.io.*;
-
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSessionContext;
-import javax.security.cert.X509Certificate;
-import javax.security.cert.CertificateEncodingException;
-import javax.security.cert.CertificateException;
-
-/**
- * Supports SSL session caches.
- */
-abstract class AbstractSessionContext implements SSLSessionContext {
-
- volatile int maximumSize;
- volatile int timeout;
-
- final int sslCtxNativePointer;
-
- /** Identifies OpenSSL sessions. */
- static final int OPEN_SSL = 1;
-
- /**
- * Constructs a new session context.
- *
- * @param sslCtxNativePointer Associated native SSL_CTX
- * @param maximumSize of cache
- * @param timeout for cache entries
- */
- AbstractSessionContext(int sslCtxNativePointer,
- int maximumSize, int timeout) {
- this.sslCtxNativePointer = sslCtxNativePointer;
- this.maximumSize = maximumSize;
- this.timeout = timeout;
- }
-
- /**
- * Returns the collection of sessions ordered by least-recently-used first.
- */
- abstract Iterator<SSLSession> sessionIterator();
-
- public final Enumeration getIds() {
- final Iterator<SSLSession> iterator = sessionIterator();
- return new Enumeration<byte[]>() {
- public boolean hasMoreElements() {
- return iterator.hasNext();
- }
- public byte[] nextElement() {
- return iterator.next().getId();
- }
- };
- }
-
- public final int getSessionCacheSize() {
- return maximumSize;
- }
-
- public final int getSessionTimeout() {
- return timeout;
- }
-
- /**
- * Makes sure cache size is < maximumSize.
- */
- abstract void trimToSize();
-
- public final void setSessionCacheSize(int size)
- throws IllegalArgumentException {
- if (size < 0) {
- throw new IllegalArgumentException("size < 0");
- }
-
- int oldMaximum = maximumSize;
- maximumSize = size;
-
- // Trim cache to size if necessary.
- if (size < oldMaximum) {
- trimToSize();
- }
- }
-
- /**
- * Converts the given session to bytes.
- *
- * @return session data as bytes or null if the session can't be converted
- */
- byte[] toBytes(SSLSession session) {
- // TODO: Support SSLSessionImpl, too.
- if (!(session instanceof OpenSSLSessionImpl)) {
- return null;
- }
-
- OpenSSLSessionImpl sslSession = (OpenSSLSessionImpl) session;
- try {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- DataOutputStream daos = new DataOutputStream(baos);
-
- daos.writeInt(OPEN_SSL); // session type ID
-
- // Session data.
- byte[] data = sslSession.getEncoded();
- daos.writeInt(data.length);
- daos.write(data);
-
- // Certificates.
- X509Certificate[] certs = session.getPeerCertificateChain();
- daos.writeInt(certs.length);
-
- // TODO: Call nativegetpeercertificates()
- for (X509Certificate cert : certs) {
- data = cert.getEncoded();
- daos.writeInt(data.length);
- daos.write(data);
- }
- // TODO: local certificates?
-
- return baos.toByteArray();
- } catch (IOException e) {
- log(e);
- return null;
- } catch (CertificateEncodingException e) {
- log(e);
- return null;
- }
- }
-
- /**
- * Creates a session from the given bytes.
- *
- * @return a session or null if the session can't be converted
- */
- SSLSession toSession(byte[] data, String host, int port) {
- ByteArrayInputStream bais = new ByteArrayInputStream(data);
- DataInputStream dais = new DataInputStream(bais);
- try {
- int type = dais.readInt();
- if (type != OPEN_SSL) {
- log(new AssertionError("Unexpected type ID: " + type));
- return null;
- }
-
- int length = dais.readInt();
- byte[] sessionData = new byte[length];
- dais.readFully(sessionData);
-
- int count = dais.readInt();
- X509Certificate[] certs = new X509Certificate[count];
- for (int i = 0; i < count; i++) {
- length = dais.readInt();
- byte[] certData = new byte[length];
- dais.readFully(certData);
- certs[i] = X509Certificate.getInstance(certData);
- }
-
- return new OpenSSLSessionImpl(sessionData, host, port, certs, this);
- } catch (IOException e) {
- log(e);
- return null;
- } catch (CertificateException e) {
- log(e);
- return null;
- }
- }
-
- /**
- * Puts an SSLSession in the AbstractSessionContext cache
- */
- abstract void putSession(SSLSession session);
-
- static void log(Throwable t) {
- java.util.logging.Logger.global.log(Level.WARNING,
- "Error converting session.", t);
- }
-
- protected void finalize() throws IOException {
- NativeCrypto.SSL_CTX_free(sslCtxNativePointer);
- }
-
- /**
- * Byte array wrapper. Implements equals() and hashCode().
- */
- static class ByteArray {
-
- private final byte[] bytes;
-
- ByteArray(byte[] bytes) {
- this.bytes = bytes;
- }
-
- @Override
- public int hashCode() {
- return Arrays.hashCode(bytes);
- }
-
- @Override
- @SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
- public boolean equals(Object o) {
- ByteArray other = (ByteArray) o;
- return Arrays.equals(bytes, other.bytes);
- }
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/AlertException.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/AlertException.java
deleted file mode 100644
index f607364..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/AlertException.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import javax.net.ssl.SSLException;
-
-/**
- * This exception is used to signal that a fatal alert has occurred while working through the
- * protocol.
- */
-public class AlertException extends RuntimeException {
-
- private static final long serialVersionUID = -4448327177165687581L;
- // SSLException to be thrown to application side
- private final SSLException reason;
- // alert description code
- private final byte description;
-
- /**
- * Constructs the instance.
- *
- * @param description The alert description code from {@link AlertProtocol}
- * @param reason The SSLException to be thrown to application side after alert processing
- * (sending the record with alert, shutdown work, etc).
- * @see AlertProtocol
- */
- protected AlertException(byte description, SSLException reason) {
- super(reason);
- this.reason = reason;
- this.description = description;
- }
-
- /**
- * Returns the reason of alert. This reason should be rethrown after alert processing.
- *
- * @return the reason of alert.
- */
- protected SSLException getReason() {
- return reason;
- }
-
- /**
- * Returns alert's description code.
- *
- * @return alert description code from {@link AlertProtocol}
- * @see AlertProtocol for more information about possible reason codes.
- */
- protected byte getDescriptionCode() {
- return description;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/AlertProtocol.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/AlertProtocol.java
deleted file mode 100644
index a12d00a..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/AlertProtocol.java
+++ /dev/null
@@ -1,286 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.SSLRecordProtocol;
-import org.apache.harmony.xnet.provider.jsse.Logger;
-import org.apache.harmony.xnet.provider.jsse.ContentType;
-
-/**
- * This class encapsulates the functionality of Alert Protocol.
- * Constant values are taken according to the TLS v1 specification
- * (http://www.ietf.org/rfc/rfc2246.txt), p 7.2.
- */
-public class AlertProtocol {
-
- // ------------------------ AlertLevel codes --------------------------
- /**
- * Defines the severity of alert as warning
- */
- protected static final byte WARNING = 1;
- /**
- * Defines the severity of alert as fatal
- */
- protected static final byte FATAL = 2;
-
- // --------------------- AlertDescription codes -----------------------
- /**
- * Defines the description code of the close_notify alert
- */
- protected static final byte CLOSE_NOTIFY = 0;
- /**
- * Defines the description code of the unexpected_message alert
- */
- protected static final byte UNEXPECTED_MESSAGE = 10;
- /**
- * Defines the description code of the bad_record_mac alert
- */
- protected static final byte BAD_RECORD_MAC = 20;
- /**
- * Defines the description code of the decryption_failed alert
- */
- protected static final byte DECRYPTION_FAILED = 21;
- /**
- * Defines the description code of the record_overflow alert
- */
- protected static final byte RECORD_OVERFLOW = 22;
- /**
- * Defines the description code of the decompression_failure alert
- */
- protected static final byte DECOMPRESSION_FAILURE = 30;
- /**
- * Defines the description code of the handshake_failure alert
- */
- protected static final byte HANDSHAKE_FAILURE = 40;
- /**
- * Defines the description code of the bad_certificate alert
- */
- protected static final byte BAD_CERTIFICATE = 42;
- /**
- * Defines the description code of the unsupported_certificate alert
- */
- protected static final byte UNSUPPORTED_CERTIFICATE = 43;
- /**
- * Defines the description code of the certificate_revoked alert
- */
- protected static final byte CERTIFICATE_REVOKED = 44;
- /**
- * Defines the description code of the certificate_expired alert
- */
- protected static final byte CERTIFICATE_EXPIRED = 45;
- /**
- * Defines the description code of the certificate_unknown alert
- */
- protected static final byte CERTIFICATE_UNKNOWN = 46;
- /**
- * Defines the description code of the illegal_parameter alert
- */
- protected static final byte ILLEGAL_PARAMETER = 47;
- /**
- * Defines the description code of the unknown_ca alert
- */
- protected static final byte UNKNOWN_CA = 48;
- /**
- * Defines the description code of the access_denied alert
- */
- protected static final byte ACCESS_DENIED = 49;
- /**
- * Defines the description code of the decode_error alert
- */
- protected static final byte DECODE_ERROR = 50;
- /**
- * Defines the description code of the decrypt_error alert
- */
- protected static final byte DECRYPT_ERROR = 51;
- /**
- * Defines the description code of the export_restriction alert
- */
- protected static final byte EXPORT_RESTRICTION = 60;
- /**
- * Defines the description code of the protocol_version alert
- */
- protected static final byte PROTOCOL_VERSION = 70;
- /**
- * Defines the description code of the insufficient_security alert
- */
- protected static final byte INSUFFICIENT_SECURITY = 71;
- /**
- * Defines the description code of the internal_error alert
- */
- protected static final byte INTERNAL_ERROR = 80;
- /**
- * Defines the description code of the user_canceled alert
- */
- protected static final byte USER_CANCELED = 90;
- /**
- * Defines the description code of the no_renegotiation alert
- */
- protected static final byte NO_RENEGOTIATION = 100;
- // holds level and description codes
- private final byte[] alert = new byte[2];
- // record protocol to be used to wrap the alerts
- private SSLRecordProtocol recordProtocol;
-
- private Logger.Stream logger = Logger.getStream("alert");
-
- /**
- * Creates the instance of AlertProtocol.
- * Note that class is not ready to work without providing of
- * record protocol
- * @see #setRecordProtocol
- */
- protected AlertProtocol() {}
-
- /**
- * Sets up the record protocol to be used by this allert protocol.
- */
- protected void setRecordProtocol(SSLRecordProtocol recordProtocol) {
- this.recordProtocol = recordProtocol;
- }
-
- /**
- * Reports an alert to be sent/received by transport.
- * This method is usually called during processing
- * of the income TSL record: if it contains alert message from another
- * peer, or if warning alert occured during the processing of the
- * message and this warning should be sent to another peer.
- * @param level: alert level code
- * @param description: alert description code
- * @return
- */
- protected void alert(byte level, byte description) {
- if (logger != null) {
- logger.println("Alert.alert: "+level+" "+description);
- }
- this.alert[0] = level;
- this.alert[1] = description;
- }
-
- /**
- * Returns the description code of alert or -100 if there
- * is no alert.
- */
- protected byte getDescriptionCode() {
- return (alert[0] != 0) ? alert[1] : -100;
- }
-
- /**
- * Resets the protocol to be in "no alert" state.
- * This method shoud be called after processing of the reported alert.
- */
- protected void setProcessed() {
- // free the info about alert
- if (logger != null) {
- logger.println("Alert.setProcessed");
- }
- this.alert[0] = 0;
- }
-
- /**
- * Checks if any alert has occured.
- */
- protected boolean hasAlert() {
- return (alert[0] != 0);
- }
-
- /**
- * Checks if occured alert is fatal alert.
- */
- protected boolean isFatalAlert() {
- return (alert[0] == 2);
- }
-
- /**
- * Returns the string representation of occured alert.
- * If no alert has occured null is returned.
- */
- protected String getAlertDescription() {
- switch (alert[1]) {
- case CLOSE_NOTIFY:
- return "close_notify";
- case UNEXPECTED_MESSAGE:
- return "unexpected_message";
- case BAD_RECORD_MAC:
- return "bad_record_mac";
- case DECRYPTION_FAILED:
- return "decryption_failed";
- case RECORD_OVERFLOW:
- return "record_overflow";
- case DECOMPRESSION_FAILURE:
- return "decompression_failure";
- case HANDSHAKE_FAILURE:
- return "handshake_failure";
- case BAD_CERTIFICATE:
- return "bad_certificate";
- case UNSUPPORTED_CERTIFICATE:
- return "unsupported_certificate";
- case CERTIFICATE_REVOKED:
- return "certificate_revoked";
- case CERTIFICATE_EXPIRED:
- return "certificate_expired";
- case CERTIFICATE_UNKNOWN:
- return "certificate_unknown";
- case ILLEGAL_PARAMETER:
- return "illegal_parameter";
- case UNKNOWN_CA:
- return "unknown_ca";
- case ACCESS_DENIED:
- return "access_denied";
- case DECODE_ERROR:
- return "decode_error";
- case DECRYPT_ERROR:
- return "decrypt_error";
- case EXPORT_RESTRICTION:
- return "export_restriction";
- case PROTOCOL_VERSION:
- return "protocol_version";
- case INSUFFICIENT_SECURITY:
- return "insufficient_security";
- case INTERNAL_ERROR:
- return "internal_error";
- case USER_CANCELED:
- return "user_canceled";
- case NO_RENEGOTIATION:
- return "no_renegotiation";
- }
- return null;
- }
-
- /**
- * Returns the record with reported alert message.
- * The returned array of bytes is ready to be sent to another peer.
- * Note, that this method does not automatically set the state of alert
- * protocol in "no alert" state, so after wrapping the method setProcessed
- * should be called.
- */
- protected byte[] wrap() {
- byte[] res = recordProtocol.wrap(ContentType.ALERT, alert, 0, 2);
- return res;
- }
-
- /**
- * Shutdown the protocol. It will be impossible to use the instance
- * after the calling of this method.
- */
- protected void shutdown() {
- alert[0] = 0;
- alert[1] = 0;
- recordProtocol = null;
- }
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Appendable.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Appendable.java
deleted file mode 100644
index 070f42a..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Appendable.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-/**
- * This interface represents the ability of the input stream related classes to provide additional
- * data to be read.
- */
-public interface Appendable {
-
- /**
- * Provides the additional data to be read.
- *
- * @param src the source data to be appended.
- */
- public void append(byte[] src);
-
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateMessage.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateMessage.java
deleted file mode 100644
index 8065860..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateMessage.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.Message;
-import org.apache.harmony.xnet.provider.jsse.Handshake;
-import org.apache.harmony.xnet.provider.jsse.HandshakeIODataStream;
-import org.apache.harmony.xnet.provider.jsse.AlertProtocol;
-
-import java.io.IOException;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateEncodingException;
-import java.security.cert.CertificateException;
-import java.security.cert.CertificateFactory;
-import java.security.cert.X509Certificate;
-import java.util.Vector;
-
-/**
- * Represents server/client certificate message
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS
- * 1.0 spec., 7.4.2. Server certificate; 7.4.6. Client certificate</a>
- *
- */
-public class CertificateMessage extends Message {
-
- /**
- * Certificates
- */
- X509Certificate[] certs;
-
- /**
- * Certificates in encoded form
- */
- byte[][] encoded_certs;
-
- /**
- * Creates inbound message
- *
- * @param in
- * @param length
- * @throws IOException
- */
- public CertificateMessage(HandshakeIODataStream in, int length)
- throws IOException {
- int l = in.readUint24(); // total_length
- if (l == 0) { // message contais no certificates
- if (length != 3) { // no more bytes after total_length
- fatalAlert(AlertProtocol.DECODE_ERROR,
- "DECODE ERROR: incorrect CertificateMessage");
- }
- certs = new X509Certificate[0];
- encoded_certs = new byte[0][0];
- this.length = 3;
- return;
- }
- CertificateFactory cf;
- try {
- cf = CertificateFactory.getInstance("X509");
- } catch (CertificateException e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);
- return;
- }
- Vector<Certificate> certs_vector = new Vector<Certificate>();
- int size = 0;
- int enc_size = 0;
- while (l > 0) {
- size = in.readUint24();
- l -= 3;
- try {
- certs_vector.add(cf.generateCertificate(in));
- } catch (CertificateException e) {
- fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR", e);
- }
- l -= size;
- enc_size += size;
- }
- certs = new X509Certificate[certs_vector.size()];
- for (int i = 0; i < certs.length; i++) {
- certs[i] = (X509Certificate) certs_vector.elementAt(i);
- }
- this.length = 3 + 3 * certs.length + enc_size;
- if (this.length != length) {
- fatalAlert(AlertProtocol.DECODE_ERROR,
- "DECODE ERROR: incorrect CertificateMessage");
- }
-
- }
-
- /**
- * Creates outbound message
- *
- * @param certs
- */
- public CertificateMessage(X509Certificate[] certs) {
- if (certs == null) {
- this.certs = new X509Certificate[0];
- encoded_certs = new byte[0][0];
- length = 3;
- return;
- }
- this.certs = certs;
- if (encoded_certs == null) {
- encoded_certs = new byte[certs.length][];
- for (int i = 0; i < certs.length; i++) {
- try {
- encoded_certs[i] = certs[i].getEncoded();
- } catch (CertificateEncodingException e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR",
- e);
- }
- }
- }
- length = 3 + 3 * encoded_certs.length;
- for (int i = 0; i < encoded_certs.length; i++) {
- length += encoded_certs[i].length;
- }
- }
-
- /**
- * Sends message
- *
- * @param out
- */
- @Override
- public void send(HandshakeIODataStream out) {
-
- int total_length = 0;
- if (encoded_certs == null) {
- encoded_certs = new byte[certs.length][];
- for (int i = 0; i < certs.length; i++) {
- try {
- encoded_certs[i] = certs[i].getEncoded();
- } catch (CertificateEncodingException e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR",
- e);
- }
- }
- }
- total_length = 3 * encoded_certs.length;
- for (int i = 0; i < encoded_certs.length; i++) {
- total_length += encoded_certs[i].length;
- }
- out.writeUint24(total_length);
- for (int i = 0; i < encoded_certs.length; i++) {
- out.writeUint24(encoded_certs[i].length);
- out.write(encoded_certs[i]);
- }
-
- }
-
- /**
- * Returns message type
- *
- * @return
- */
- @Override
- public int getType() {
- return Handshake.CERTIFICATE;
- }
-
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateRequest.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateRequest.java
deleted file mode 100644
index 7246c4d..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateRequest.java
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.Message;
-import org.apache.harmony.xnet.provider.jsse.Handshake;
-import org.apache.harmony.xnet.provider.jsse.HandshakeIODataStream;
-import org.apache.harmony.xnet.provider.jsse.AlertProtocol;
-
-import java.io.IOException;
-import java.security.cert.X509Certificate;
-import java.util.Vector;
-
-import javax.security.auth.x500.X500Principal;
-
-/**
- *
- * Represents certificate request message
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7.4.4.
- * Certificate request</a>
- */
-public class CertificateRequest extends Message {
-
- /**
- * Client certificate types as defined in
- * TLS 1.0 spec., 7.4.4. Certificate request
- */
- public static final byte RSA_SIGN = 1;
- public static final byte DSS_SIGN = 2;
- public static final byte RSA_FIXED_DH = 3;
- public static final byte DSS_FIXED_DH = 4;
-
- /**
- * Requested certificate types
- */
- final byte[] certificate_types;
-
- /**
- * Certificate authorities
- */
- X500Principal[] certificate_authorities;
-
- // Requested certificate types as Strings
- // ("RSA", "DSA", "DH_RSA" or "DH_DSA")
- private String[] types;
-
- // Encoded form of certificate authorities
- private byte[][] encoded_principals;
-
- /**
- * Creates outbound message
- *
- * @param certificate_types
- * @param accepted - array of certificate authority certificates
- */
- public CertificateRequest(byte[] certificate_types,
- X509Certificate[] accepted) {
-
- if (accepted == null) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR,
- "CertificateRequest: array of certificate authority certificates is null");
- }
- this.certificate_types = certificate_types;
-
- int totalPrincipalsLength = 0;
- certificate_authorities = new X500Principal[accepted.length];
- encoded_principals = new byte[accepted.length][];
- for (int i = 0; i < accepted.length; i++) {
- certificate_authorities[i] = accepted[i].getIssuerX500Principal();
- encoded_principals[i] = certificate_authorities[i].getEncoded();
- totalPrincipalsLength += encoded_principals[i].length + 2;
- }
-
- length = 3 + certificate_types.length + totalPrincipalsLength;
- }
-
- /**
- * Creates inbound message
- *
- * @param in
- * @param length
- * @throws IOException
- */
- public CertificateRequest(HandshakeIODataStream in, int length)
- throws IOException {
- int size = in.readUint8();
- certificate_types = new byte[size];
- in.read(certificate_types, 0, size);
- size = in.readUint16();
- certificate_authorities = new X500Principal[size];
- int totalPrincipalsLength = 0;
- int principalLength = 0;
- Vector<X500Principal> principals = new Vector<X500Principal>();
- while (totalPrincipalsLength < size) {
- principalLength = in.readUint16(); // encoded X500Principal size
- principals.add(new X500Principal(in));
- totalPrincipalsLength += 2;
- totalPrincipalsLength += principalLength;
- }
- certificate_authorities = new X500Principal[principals.size()];
- for (int i = 0; i < certificate_authorities.length; i++) {
- certificate_authorities[i] = principals.elementAt(i);
- }
- this.length = 3 + certificate_types.length + totalPrincipalsLength;
- if (this.length != length) {
- fatalAlert(AlertProtocol.DECODE_ERROR,
- "DECODE ERROR: incorrect CertificateRequest");
- }
-
- }
-
- /**
- * Sends message
- *
- * @param out
- */
- @Override
- public void send(HandshakeIODataStream out) {
-
- out.writeUint8(certificate_types.length);
- for (int i = 0; i < certificate_types.length; i++) {
- out.write(certificate_types[i]);
- }
- int authoritiesLength = 0;
- for (int i = 0; i < certificate_authorities.length; i++) {
- authoritiesLength += encoded_principals[i].length +2;
- }
- out.writeUint16(authoritiesLength);
- for (int i = 0; i < certificate_authorities.length; i++) {
- out.writeUint16(encoded_principals[i].length);
- out.write(encoded_principals[i]);
- }
- }
-
- /**
- * Returns message type
- *
- * @return
- */
- @Override
- public int getType() {
- return Handshake.CERTIFICATE_REQUEST;
- }
-
- /**
- * Returns requested certificate types as array of strings
- */
- public String[] getTypesAsString() {
- if (types == null) {
- types = new String[certificate_types.length];
- for (int i = 0; i < types.length; i++) {
- switch (certificate_types[i]) {
- case 1:
- types[i] = "RSA";
- break;
- case 2:
- types[i] = "DSA";
- break;
- case 3:
- types[i] = "DH_RSA";
- break;
- case 4:
- types[i] = "DH_DSA";
- break;
- default:
- fatalAlert(AlertProtocol.DECODE_ERROR,
- "DECODE ERROR: incorrect CertificateRequest");
- }
- }
- }
- return types;
- }
-
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateVerify.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateVerify.java
deleted file mode 100644
index 9b18ecb..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateVerify.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.Message;
-import org.apache.harmony.xnet.provider.jsse.Handshake;
-import org.apache.harmony.xnet.provider.jsse.HandshakeIODataStream;
-import org.apache.harmony.xnet.provider.jsse.AlertProtocol;
-
-import java.io.IOException;
-
-/**
- * Represents certificate verify message
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7.4.8.
- * Certificate verify</a>
- */
-public class CertificateVerify extends Message {
-
- /**
- * Signature
- */
- byte[] signedHash;
-
- /**
- * Creates outbound message
- *
- * @param hash
- */
- public CertificateVerify(byte[] hash) {
- if (hash == null || hash.length == 0) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR,
- "INTERNAL ERROR: incorrect certificate verify hash");
- }
- this.signedHash = hash;
- length = hash.length + 2;
- }
-
- /**
- * Creates inbound message
- *
- * @param in
- * @param length
- * @throws IOException
- */
- public CertificateVerify(HandshakeIODataStream in, int length)
- throws IOException {
- if (length == 0) {
- fatalAlert(AlertProtocol.DECODE_ERROR,
- "DECODE ERROR: incorrect CertificateVerify");
- } else {
- if (in.readUint16() != length - 2) {
- fatalAlert(AlertProtocol.DECODE_ERROR,
- "DECODE ERROR: incorrect CertificateVerify");
- }
- signedHash = in.read(length -2);
- }
- this.length = length;
- }
-
- /**
- * Sends message
- *
- * @param out
- */
- @Override
- public void send(HandshakeIODataStream out) {
- if (signedHash.length != 0) {
- out.writeUint16(signedHash.length);
- out.write(signedHash);
- }
- }
-
- /**
- * Returns message type
- *
- * @return
- */
- @Override
- public int getType() {
- return Handshake.CERTIFICATE_VERIFY;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CipherSuite.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CipherSuite.java
deleted file mode 100644
index f084195..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CipherSuite.java
+++ /dev/null
@@ -1,610 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.security.GeneralSecurityException;
-import java.util.Hashtable;
-
-import javax.crypto.Cipher;
-
-/**
- * Represents Cipher Suite as defined in TLS 1.0 spec.,
- * A.5. The CipherSuite;
- * C. CipherSuite definitions.
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec.</a>
- *
- */
-public class CipherSuite {
-
- /**
- * true if this cipher suite is supported
- */
- boolean supported = true;
-
- /**
- * cipher suite key exchange
- */
- final int keyExchange;
-
- /**
- * cipher
- */
- final String cipherName;
-
- /**
- * Cipher information
- */
- final int keyMaterial;
- final int expandedKeyMaterial;
- final int effectiveKeyBytes;
- final int IVSize;
- final private int blockSize;
-
- // cipher suite code
- private final byte[] cipherSuiteCode;
-
- // cipher suite name
- private final String name;
-
- // true if cipher suite is exportable
- private final boolean isExportable;
-
- // Hash algorithm
- final private String hashName;
-
- // MAC algorithm
- final private String hmacName;
-
- // Hash size
- final private int hashSize;
-
- /**
- * key exchange values
- */
- static int KeyExchange_RSA = 1;
- static int KeyExchange_RSA_EXPORT = 2;
- static int KeyExchange_DHE_DSS = 3;
- static int KeyExchange_DHE_DSS_EXPORT = 4;
- static int KeyExchange_DHE_RSA = 5;
- static int KeyExchange_DHE_RSA_EXPORT = 6;
- static int KeyExchange_DH_DSS = 7;
- static int KeyExchange_DH_RSA = 8;
- static int KeyExchange_DH_anon = 9;
- static int KeyExchange_DH_anon_EXPORT = 10;
- static int KeyExchange_DH_DSS_EXPORT = 11;
- static int KeyExchange_DH_RSA_EXPORT = 12;
-
- /**
- * TLS cipher suite codes
- */
- static byte[] code_TLS_NULL_WITH_NULL_NULL = { 0x00, 0x00 };
- static byte[] code_TLS_RSA_WITH_NULL_MD5 = { 0x00, 0x01 };
- static byte[] code_TLS_RSA_WITH_NULL_SHA = { 0x00, 0x02 };
- static byte[] code_TLS_RSA_EXPORT_WITH_RC4_40_MD5 = { 0x00, 0x03 };
- static byte[] code_TLS_RSA_WITH_RC4_128_MD5 = { 0x00, 0x04 };
- static byte[] code_TLS_RSA_WITH_RC4_128_SHA = { 0x00, 0x05 };
- static byte[] code_TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 = { 0x00, 0x06 };
- static byte[] code_TLS_RSA_WITH_IDEA_CBC_SHA = { 0x00, 0x07 };
- static byte[] code_TLS_RSA_EXPORT_WITH_DES40_CBC_SHA = { 0x00, 0x08 };
- static byte[] code_TLS_RSA_WITH_DES_CBC_SHA = { 0x00, 0x09 };
- static byte[] code_TLS_RSA_WITH_3DES_EDE_CBC_SHA = { 0x00, 0x0A };
- static byte[] code_TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA = { 0x00, 0x0B };
- static byte[] code_TLS_DH_DSS_WITH_DES_CBC_SHA = { 0x00, 0x0C };
- static byte[] code_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA = { 0x00, 0x0D };
- static byte[] code_TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA = { 0x00, 0x0E };
- static byte[] code_TLS_DH_RSA_WITH_DES_CBC_SHA = { 0x00, 0x0F };
- static byte[] code_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA = { 0x00, 0x10 };
- static byte[] code_TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA = { 0x00, 0x11 };
- static byte[] code_TLS_DHE_DSS_WITH_DES_CBC_SHA = { 0x00, 0x12 };
- static byte[] code_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA = { 0x00, 0x13 };
- static byte[] code_TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA = { 0x00, 0x14 };
- static byte[] code_TLS_DHE_RSA_WITH_DES_CBC_SHA = { 0x00, 0x15 };
- static byte[] code_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA = { 0x00, 0x16 };
- static byte[] code_TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 = { 0x00, 0x17 };
- static byte[] code_TLS_DH_anon_WITH_RC4_128_MD5 = { 0x00, 0x18 };
- static byte[] code_TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA = { 0x00, 0x19 };
- static byte[] code_TLS_DH_anon_WITH_DES_CBC_SHA = { 0x00, 0x1A };
- static byte[] code_TLS_DH_anon_WITH_3DES_EDE_CBC_SHA = { 0x00, 0x1B };
-
- static CipherSuite TLS_NULL_WITH_NULL_NULL = new CipherSuite(
- "TLS_NULL_WITH_NULL_NULL", true, 0, null, null,
- code_TLS_NULL_WITH_NULL_NULL);
-
- static CipherSuite TLS_RSA_WITH_NULL_MD5 = new CipherSuite(
- "TLS_RSA_WITH_NULL_MD5", true, KeyExchange_RSA, null, "MD5",
- code_TLS_RSA_WITH_NULL_MD5);
-
- static CipherSuite TLS_RSA_WITH_NULL_SHA = new CipherSuite(
- "TLS_RSA_WITH_NULL_SHA", true, KeyExchange_RSA, null, "SHA",
- code_TLS_RSA_WITH_NULL_SHA);
-
- static CipherSuite TLS_RSA_EXPORT_WITH_RC4_40_MD5 = new CipherSuite(
- "TLS_RSA_EXPORT_WITH_RC4_40_MD5", true, KeyExchange_RSA_EXPORT,
- "RC4_40", "MD5", code_TLS_RSA_EXPORT_WITH_RC4_40_MD5);
-
- static CipherSuite TLS_RSA_WITH_RC4_128_MD5 = new CipherSuite(
- "TLS_RSA_WITH_RC4_128_MD5", false, KeyExchange_RSA, "RC4_128",
- "MD5", code_TLS_RSA_WITH_RC4_128_MD5);
-
- static CipherSuite TLS_RSA_WITH_RC4_128_SHA = new CipherSuite(
- "TLS_RSA_WITH_RC4_128_SHA", false, KeyExchange_RSA, "RC4_128",
- "SHA", code_TLS_RSA_WITH_RC4_128_SHA);
-
- static CipherSuite TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 = new CipherSuite(
- "TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5", true, KeyExchange_RSA_EXPORT,
- "RC2_CBC_40", "MD5", code_TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5);
-
- static CipherSuite TLS_RSA_WITH_IDEA_CBC_SHA = new CipherSuite(
- "TLS_RSA_WITH_IDEA_CBC_SHA", false, KeyExchange_RSA, "IDEA_CBC",
- "SHA", code_TLS_RSA_WITH_IDEA_CBC_SHA);
-
- static CipherSuite TLS_RSA_EXPORT_WITH_DES40_CBC_SHA = new CipherSuite(
- "TLS_RSA_EXPORT_WITH_DES40_CBC_SHA", true, KeyExchange_RSA_EXPORT,
- "DES40_CBC", "SHA", code_TLS_RSA_EXPORT_WITH_DES40_CBC_SHA);
-
- static CipherSuite TLS_RSA_WITH_DES_CBC_SHA = new CipherSuite(
- "TLS_RSA_WITH_DES_CBC_SHA", false, KeyExchange_RSA, "DES_CBC",
- "SHA", code_TLS_RSA_WITH_DES_CBC_SHA);
-
- static CipherSuite TLS_RSA_WITH_3DES_EDE_CBC_SHA = new CipherSuite(
- "TLS_RSA_WITH_3DES_EDE_CBC_SHA", false, KeyExchange_RSA,
- "3DES_EDE_CBC", "SHA", code_TLS_RSA_WITH_3DES_EDE_CBC_SHA);
-
- static CipherSuite TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA = new CipherSuite(
- "TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA", true,
- KeyExchange_DH_DSS_EXPORT, "DES40_CBC", "SHA",
- code_TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA);
-
- static CipherSuite TLS_DH_DSS_WITH_DES_CBC_SHA = new CipherSuite(
- "TLS_DH_DSS_WITH_DES_CBC_SHA", false, KeyExchange_DH_DSS,
- "DES_CBC", "SHA", code_TLS_DH_DSS_WITH_DES_CBC_SHA);
-
- static CipherSuite TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA = new CipherSuite(
- "TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA", false, KeyExchange_DH_DSS,
- "3DES_EDE_CBC", "SHA", code_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA);
-
- static CipherSuite TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA = new CipherSuite(
- "TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA", true,
- KeyExchange_DH_RSA_EXPORT, "DES40_CBC", "SHA",
- code_TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA);
-
- static CipherSuite TLS_DH_RSA_WITH_DES_CBC_SHA = new CipherSuite(
- "TLS_DH_RSA_WITH_DES_CBC_SHA", false, KeyExchange_DH_RSA,
- "DES_CBC", "SHA", code_TLS_DH_RSA_WITH_DES_CBC_SHA);
-
- static CipherSuite TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA = new CipherSuite(
- "TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA", false, KeyExchange_DH_RSA,
- "3DES_EDE_CBC", "SHA", code_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA);
-
- static CipherSuite TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA = new CipherSuite(
- "TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA", true,
- KeyExchange_DHE_DSS_EXPORT, "DES40_CBC", "SHA",
- code_TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA);
-
- static CipherSuite TLS_DHE_DSS_WITH_DES_CBC_SHA = new CipherSuite(
- "TLS_DHE_DSS_WITH_DES_CBC_SHA", false, KeyExchange_DHE_DSS,
- "DES_CBC", "SHA", code_TLS_DHE_DSS_WITH_DES_CBC_SHA);
-
- static CipherSuite TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA = new CipherSuite(
- "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA", false, KeyExchange_DHE_DSS,
- "3DES_EDE_CBC", "SHA", code_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA);
-
- static CipherSuite TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA = new CipherSuite(
- "TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", true,
- KeyExchange_DHE_RSA_EXPORT, "DES40_CBC", "SHA",
- code_TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA);
-
- static CipherSuite TLS_DHE_RSA_WITH_DES_CBC_SHA = new CipherSuite(
- "TLS_DHE_RSA_WITH_DES_CBC_SHA", false, KeyExchange_DHE_RSA,
- "DES_CBC", "SHA", code_TLS_DHE_RSA_WITH_DES_CBC_SHA);
-
- static CipherSuite TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA = new CipherSuite(
- "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA", false, KeyExchange_DHE_RSA,
- "3DES_EDE_CBC", "SHA", code_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA);
-
- static CipherSuite TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 = new CipherSuite(
- "TLS_DH_anon_EXPORT_WITH_RC4_40_MD5", true,
- KeyExchange_DH_anon_EXPORT, "RC4_40", "MD5",
- code_TLS_DH_anon_EXPORT_WITH_RC4_40_MD5);
-
- static CipherSuite TLS_DH_anon_WITH_RC4_128_MD5 = new CipherSuite(
- "TLS_DH_anon_WITH_RC4_128_MD5", false, KeyExchange_DH_anon,
- "RC4_128", "MD5", code_TLS_DH_anon_WITH_RC4_128_MD5);
-
- static CipherSuite TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA = new CipherSuite(
- "TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA", true,
- KeyExchange_DH_anon_EXPORT, "DES40_CBC", "SHA",
- code_TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA);
-
- static CipherSuite TLS_DH_anon_WITH_DES_CBC_SHA = new CipherSuite(
- "TLS_DH_anon_WITH_DES_CBC_SHA", false, KeyExchange_DH_anon,
- "DES_CBC", "SHA", code_TLS_DH_anon_WITH_DES_CBC_SHA);
-
- static CipherSuite TLS_DH_anon_WITH_3DES_EDE_CBC_SHA = new CipherSuite(
- "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA", false, KeyExchange_DH_anon,
- "3DES_EDE_CBC", "SHA", code_TLS_DH_anon_WITH_3DES_EDE_CBC_SHA);
-
- // array for quick access to cipher suite by code
- private static CipherSuite[] cuitesByCode = {
- TLS_NULL_WITH_NULL_NULL,
- TLS_RSA_WITH_NULL_MD5,
- TLS_RSA_WITH_NULL_SHA,
- TLS_RSA_EXPORT_WITH_RC4_40_MD5,
- TLS_RSA_WITH_RC4_128_MD5,
- TLS_RSA_WITH_RC4_128_SHA,
- TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5,
- TLS_RSA_WITH_IDEA_CBC_SHA,
- TLS_RSA_EXPORT_WITH_DES40_CBC_SHA,
- TLS_RSA_WITH_DES_CBC_SHA,
- TLS_RSA_WITH_3DES_EDE_CBC_SHA,
- TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA,
- TLS_DH_DSS_WITH_DES_CBC_SHA,
- TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA,
- TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA,
- TLS_DH_RSA_WITH_DES_CBC_SHA,
- TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA,
- TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA,
- TLS_DHE_DSS_WITH_DES_CBC_SHA,
- TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
- TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA,
- TLS_DHE_RSA_WITH_DES_CBC_SHA,
- TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
- TLS_DH_anon_EXPORT_WITH_RC4_40_MD5,
- TLS_DH_anon_WITH_RC4_128_MD5,
- TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA,
- TLS_DH_anon_WITH_DES_CBC_SHA,
- TLS_DH_anon_WITH_3DES_EDE_CBC_SHA
- };
-
- // hash for quick access to cipher suite by name
- private static Hashtable<String, CipherSuite> cuitesByName;
-
- /**
- * array of supported cipher suites.
- * Set of supported suites is defined at the moment provider's start
- */
-// TODO Dynamically supported suites: new providers may be dynamically
-// added/removed and the set of supported suites may be changed
- static CipherSuite[] supportedCipherSuites;
-
- /**
- * array of supported cipher suites names
- */
- static String[] supportedCipherSuiteNames;
-
- /**
- * default cipher suites
- */
- static CipherSuite[] defaultCipherSuites;
-
- static {
- int count = 0;
- cuitesByName = new Hashtable<String, CipherSuite>();
- for (int i = 0; i < cuitesByCode.length; i++) {
- cuitesByName.put(cuitesByCode[i].getName(), cuitesByCode[i]);
- if (cuitesByCode[i].supported) {
- count++;
- }
- }
- supportedCipherSuites = new CipherSuite[count];
- supportedCipherSuiteNames = new String[count];
- count = 0;
- for (int i = 0; i < cuitesByCode.length; i++) {
- if (cuitesByCode[i].supported) {
- supportedCipherSuites[count] = cuitesByCode[i];
- supportedCipherSuiteNames[count] = supportedCipherSuites[count].getName();
- count++;
- }
- }
-
- CipherSuite[] defaultPretendent = {
- TLS_RSA_WITH_RC4_128_MD5,
- TLS_RSA_WITH_RC4_128_SHA,
- // TLS_RSA_WITH_AES_128_CBC_SHA,
- // TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
- // LS_DHE_DSS_WITH_AES_128_CBC_SHA,
- TLS_RSA_WITH_3DES_EDE_CBC_SHA,
- TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
- TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA, TLS_RSA_WITH_DES_CBC_SHA,
- TLS_DHE_RSA_WITH_DES_CBC_SHA, TLS_DHE_DSS_WITH_DES_CBC_SHA,
- TLS_RSA_EXPORT_WITH_RC4_40_MD5,
- TLS_RSA_EXPORT_WITH_DES40_CBC_SHA,
- TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA,
- TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA
- };
- count = 0;
- for (int i = 0; i < defaultPretendent.length; i++) {
- if (defaultPretendent[i].supported) {
- count++;
- }
- }
- defaultCipherSuites = new CipherSuite[count];
- count = 0;
- for (int i = 0; i < defaultPretendent.length; i++) {
- if (defaultPretendent[i].supported) {
- defaultCipherSuites[count++] = defaultPretendent[i];
- }
- }
- }
-
- /**
- * Returns CipherSuite by name
- * @param name
- * @return
- */
- public static CipherSuite getByName(String name) {
- return cuitesByName.get(name);
- }
-
- /**
- * Returns CipherSuite based on TLS CipherSuite code
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., A.5. The CipherSuite</a>
- * @param b1
- * @param b2
- * @return
- */
- public static CipherSuite getByCode(byte b1, byte b2) {
- if (b1 != 0 || (b2 & 0xFF) > cuitesByCode.length) {
- // Unknown
- return new CipherSuite("UNKNOUN_" + b1 + "_" + b2, false, 0, "",
- "", new byte[] { b1, b2 });
- }
- return cuitesByCode[b2];
- }
-
- /**
- * Returns CipherSuite based on V2CipherSpec code
- * as described in TLS 1.0 spec., E. Backward Compatibility With SSL
- *
- * @param b1
- * @param b2
- * @param b3
- * @return CipherSuite
- */
- public static CipherSuite getByCode(byte b1, byte b2, byte b3) {
- if (b1 == 0 && b2 == 0) {
- if ((b3 & 0xFF) <= cuitesByCode.length) {
- return cuitesByCode[b3];
- }
- }
- // as TLSv1 equivalent of V2CipherSpec should be included in
- // V2ClientHello, ignore V2CipherSpec
- return new CipherSuite("UNKNOUN_" + b1 + "_" + b2 + "_" + b3, false, 0,
- "", "", new byte[] { b1, b2, b3 });
- }
-
- /**
- * Creates CipherSuite
- * @param name
- * @param isExportable
- * @param keyExchange
- * @param cipherName
- * @param hash
- * @param code
- */
- public CipherSuite(String name, boolean isExportable, int keyExchange,
- String cipherName, String hash, byte[] code) {
- this.name = name;
- this.keyExchange = keyExchange;
- this.isExportable = isExportable;
- if (cipherName == null) {
- this.cipherName = null;
- keyMaterial = 0;
- expandedKeyMaterial = 0;
- effectiveKeyBytes = 0;
- IVSize = 0;
- blockSize = 0;
- } else if ("IDEA_CBC".equals(cipherName)) {
- this.cipherName = "IDEA/CBC/NoPadding";
- keyMaterial = 16;
- expandedKeyMaterial = 16;
- effectiveKeyBytes = 16;
- IVSize = 8;
- blockSize = 8;
- } else if ("RC2_CBC_40".equals(cipherName)) {
- this.cipherName = "RC2/CBC/NoPadding";
- keyMaterial = 5;
- expandedKeyMaterial = 16;
- effectiveKeyBytes = 5;
- IVSize = 8;
- blockSize = 8;
- } else if ("RC4_40".equals(cipherName)) {
- this.cipherName = "RC4";
- keyMaterial = 5;
- expandedKeyMaterial = 16;
- effectiveKeyBytes = 5;
- IVSize = 0;
- blockSize = 0;
- } else if ("RC4_128".equals(cipherName)) {
- this.cipherName = "RC4";
- keyMaterial = 16;
- expandedKeyMaterial = 16;
- effectiveKeyBytes = 16;
- IVSize = 0;
- blockSize = 0;
- } else if ("DES40_CBC".equals(cipherName)) {
- this.cipherName = "DES/CBC/NoPadding";
- keyMaterial = 5;
- expandedKeyMaterial = 8;
- effectiveKeyBytes = 5;
- IVSize = 8;
- blockSize = 8;
- } else if ("DES_CBC".equals(cipherName)) {
- this.cipherName = "DES/CBC/NoPadding";
- keyMaterial = 8;
- expandedKeyMaterial = 8;
- effectiveKeyBytes = 7;
- IVSize = 8;
- blockSize = 8;
- } else if ("3DES_EDE_CBC".equals(cipherName)) {
- this.cipherName = "DESede/CBC/NoPadding";
- keyMaterial = 24;
- expandedKeyMaterial = 24;
- effectiveKeyBytes = 24;
- IVSize = 8;
- blockSize = 8;
- } else {
- this.cipherName = cipherName;
- keyMaterial = 0;
- expandedKeyMaterial = 0;
- effectiveKeyBytes = 0;
- IVSize = 0;
- blockSize = 0;
- }
-
- if ("MD5".equals(hash)) {
- this.hmacName = "HmacMD5";
- this.hashName = "MD5";
- hashSize = 16;
- } else if ("SHA".equals(hash)) {
- this.hmacName = "HmacSHA1";
- this.hashName = "SHA-1";
- hashSize = 20;
- } else {
- this.hmacName = null;
- this.hashName = null;
- hashSize = 0;
- }
-
- cipherSuiteCode = code;
-
- if (this.cipherName != null) {
- try {
- Cipher.getInstance(this.cipherName);
- } catch (GeneralSecurityException e) {
- supported = false;
- }
- }
-
- }
-
- /**
- * Returns true if cipher suite is anonymous
- * @return
- */
- public boolean isAnonymous() {
- if (keyExchange == KeyExchange_DH_anon
- || keyExchange == KeyExchange_DH_anon_EXPORT) {
- return true;
- }
- return false;
- }
-
- /**
- * Returns array of supported CipherSuites
- * @return
- */
- public static CipherSuite[] getSupported() {
- return supportedCipherSuites;
- }
-
- /**
- * Returns array of supported cipher suites names
- * @return
- */
- public static String[] getSupportedCipherSuiteNames() {
- return supportedCipherSuiteNames.clone();
- }
-
- /**
- * Returns cipher suite name
- * @return
- */
- public String getName() {
- return name;
- }
-
- /**
- * Returns cipher suite code as byte array
- * @return
- */
- public byte[] toBytes() {
- return cipherSuiteCode;
- }
-
- /**
- * Returns cipher suite description
- */
- @Override
- public String toString() {
- return name + ": " + cipherSuiteCode[0] + " " + cipherSuiteCode[1];
- }
-
- /**
- * Compares this cipher suite to the specified object.
- */
- @Override
- public boolean equals(Object obj) {
- if (obj instanceof CipherSuite
- && this.cipherSuiteCode[0] == ((CipherSuite) obj).cipherSuiteCode[0]
- && this.cipherSuiteCode[1] == ((CipherSuite) obj).cipherSuiteCode[1]) {
- return true;
- }
- return false;
- }
-
- /**
- * Returns cipher algorithm name
- * @return
- */
- public String getBulkEncryptionAlgorithm() {
- return cipherName;
- }
-
- /**
- * Returns cipher block size
- * @return
- */
- public int getBlockSize() {
- return blockSize;
- }
-
- /**
- * Returns MAC algorithm name
- * @return
- */
- public String getHmacName() {
- return hmacName;
- }
-
- /**
- * Returns hash algorithm name
- * @return
- */
- public String getHashName() {
- return hashName;
- }
-
- /**
- * Returns hash size
- * @return
- */
- public int getMACLength() {
- return hashSize;
- }
-
- /**
- * Indicates whether this cipher suite is exportable
- * @return
- */
- public boolean isExportable() {
- return isExportable;
- }
-
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientHandshakeImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientHandshakeImpl.java
deleted file mode 100644
index 34252f0..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientHandshakeImpl.java
+++ /dev/null
@@ -1,629 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.IOException;
-import java.security.AccessController;
-import java.security.Key;
-import java.security.KeyFactory;
-import java.security.KeyPair;
-import java.security.KeyPairGenerator;
-import java.security.NoSuchAlgorithmException;
-import java.security.PrivateKey;
-import java.security.PrivilegedExceptionAction;
-import java.security.PublicKey;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-import java.util.Arrays;
-import java.util.Enumeration;
-
-import javax.crypto.Cipher;
-import javax.crypto.KeyAgreement;
-import javax.crypto.interfaces.DHKey;
-import javax.crypto.interfaces.DHPublicKey;
-import javax.crypto.spec.DHParameterSpec;
-import javax.crypto.spec.DHPublicKeySpec;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSessionContext;
-import javax.net.ssl.X509ExtendedKeyManager;
-
-/**
- * Client side handshake protocol implementation.
- * Handshake protocol operates on top of the Record Protocol.
- * It is responsible for session negotiating.
- *
- * The implementation processes inbound server handshake messages,
- * creates and sends respond messages. Outbound messages are supplied
- * to Record Protocol. Detected errors are reported to the Alert protocol.
- *
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7. The
- * TLS Handshake Protocol</a>
- *
- */
-public class ClientHandshakeImpl extends HandshakeProtocol {
-
- /**
- * Creates Client Handshake Implementation
- *
- * @param owner
- */
- ClientHandshakeImpl(Object owner) {
- super(owner);
- }
-
- /**
- * Starts handshake
- *
- */
- @Override
- public void start() {
- if (session == null) { // initial handshake
- session = findSessionToResume();
- } else { // start session renegotiation
- if (clientHello != null && this.status != FINISHED) {
- // current negotiation has not completed
- return; // ignore
- }
- if (!session.isValid()) {
- session = null;
- }
- }
- if (session != null) {
- isResuming = true;
- } else if (parameters.getEnableSessionCreation()){
- isResuming = false;
- session = new SSLSessionImpl(parameters.getSecureRandom());
- session.setPeer(engineOwner.getPeerHost(), engineOwner.getPeerPort());
- session.protocol = ProtocolVersion.getLatestVersion(parameters
- .getEnabledProtocols());
- recordProtocol.setVersion(session.protocol.version);
- } else {
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "SSL Session may not be created ");
- }
- startSession();
- }
-
- /**
- * Starts renegotiation on a new session
- *
- */
- private void renegotiateNewSession() {
- if (parameters.getEnableSessionCreation()){
- isResuming = false;
- session = new SSLSessionImpl(parameters.getSecureRandom());
- session.setPeer(engineOwner.getPeerHost(), engineOwner.getPeerPort());
- session.protocol = ProtocolVersion.getLatestVersion(parameters
- .getEnabledProtocols());
- recordProtocol.setVersion(session.protocol.version);
- startSession();
- } else {
- status = NOT_HANDSHAKING;
- sendWarningAlert(AlertProtocol.NO_RENEGOTIATION);
- }
- }
-
- /*
- * Starts/resumes session
- */
- private void startSession() {
- CipherSuite[] cipher_suites;
- if (isResuming) {
- cipher_suites = new CipherSuite[] { session.cipherSuite };
- } else {
- // BEGIN android-changed
- cipher_suites = parameters.getEnabledCipherSuitesMember();
- // END android-changed
- }
- clientHello = new ClientHello(parameters.getSecureRandom(),
- session.protocol.version, session.id, cipher_suites);
- session.clientRandom = clientHello.random;
- send(clientHello);
- status = NEED_UNWRAP;
- }
-
- /**
- * Processes inbound handshake messages
- * @param bytes
- */
- @Override
- public void unwrap(byte[] bytes) {
- if (this.delegatedTaskErr != null) {
- Exception e = this.delegatedTaskErr;
- this.delegatedTaskErr = null;
- this.fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "Error in delegated task", e);
- }
- int handshakeType;
- io_stream.append(bytes);
- while (io_stream.available() > 0) {
- io_stream.mark();
- int length;
- try {
- handshakeType = io_stream.read();
- length = io_stream.readUint24();
- if (io_stream.available() < length) {
- io_stream.reset();
- return;
- }
- switch (handshakeType) {
- case 0: // HELLO_REQUEST
- // we don't need to take this message into account
- // during FINISH message verification, so remove it
- io_stream.removeFromMarkedPosition();
- if (clientHello != null
- && (clientFinished == null || serverFinished == null)) {
- //currently negotiating - ignore
- break;
- }
- // renegotiate
- if (session.isValid()) {
- session = (SSLSessionImpl) session.clone();
- isResuming = true;
- startSession();
- } else {
- // if SSLSession is invalidated (e.g. timeout limit is
- // exceeded) connection can't resume the session.
- renegotiateNewSession();
- }
- break;
- case 2: // SERVER_HELLO
- if (clientHello == null || serverHello != null) {
- unexpectedMessage();
- return;
- }
- serverHello = new ServerHello(io_stream, length);
-
- //check protocol version
- ProtocolVersion servProt = ProtocolVersion
- .getByVersion(serverHello.server_version);
- String[] enabled = parameters.getEnabledProtocols();
- find: {
- for (int i = 0; i < enabled.length; i++) {
- if (servProt.equals(ProtocolVersion
- .getByName(enabled[i]))) {
- break find;
- }
- }
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE,
- "Bad server hello protocol version");
- }
-
- // check compression method
- if (serverHello.compression_method != 0) {
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE,
- "Bad server hello compression method");
- }
-
- //check cipher_suite
- // BEGIN android-changed
- CipherSuite[] enabledSuites = parameters.getEnabledCipherSuitesMember();
- // END android-changed
- find: {
- for (int i = 0; i < enabledSuites.length; i++) {
- if (serverHello.cipher_suite
- .equals(enabledSuites[i])) {
- break find;
- }
- }
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE,
- "Bad server hello cipher suite");
- }
-
- if (isResuming) {
- if (serverHello.session_id.length == 0) {
- // server is not willing to establish the new connection
- // using specified session
- isResuming = false;
- } else if (!Arrays.equals(serverHello.session_id, clientHello.session_id)) {
- isResuming = false;
- } else if (!session.protocol.equals(servProt)) {
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE,
- "Bad server hello protocol version");
- } else if (!session.cipherSuite
- .equals(serverHello.cipher_suite)) {
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE,
- "Bad server hello cipher suite");
- }
- if (serverHello.server_version[1] == 1) {
- computerReferenceVerifyDataTLS("server finished");
- } else {
- computerReferenceVerifyDataSSLv3(SSLv3Constants.server);
- }
- }
- session.protocol = servProt;
- recordProtocol.setVersion(session.protocol.version);
- session.cipherSuite = serverHello.cipher_suite;
- session.id = serverHello.session_id.clone();
- session.serverRandom = serverHello.random;
- break;
- case 11: // CERTIFICATE
- if (serverHello == null || serverKeyExchange != null
- || serverCert != null || isResuming) {
- unexpectedMessage();
- return;
- }
- serverCert = new CertificateMessage(io_stream, length);
- break;
- case 12: // SERVER_KEY_EXCHANGE
- if (serverHello == null || serverKeyExchange != null
- || isResuming) {
- unexpectedMessage();
- return;
- }
- serverKeyExchange = new ServerKeyExchange(io_stream,
- length, session.cipherSuite.keyExchange);
- break;
- case 13: // CERTIFICATE_REQUEST
- if (serverCert == null || certificateRequest != null
- || session.cipherSuite.isAnonymous() || isResuming) {
- unexpectedMessage();
- return;
- }
- certificateRequest = new CertificateRequest(io_stream,
- length);
- break;
- case 14: // SERVER_HELLO_DONE
- if (serverHello == null || serverHelloDone != null
- || isResuming) {
- unexpectedMessage();
- return;
- }
- serverHelloDone = new ServerHelloDone(io_stream, length);
- if (this.nonBlocking) {
- delegatedTasks.add(new DelegatedTask(new PrivilegedExceptionAction<Void>() {
- public Void run() throws Exception {
- processServerHelloDone();
- return null;
- }
- }, this, AccessController.getContext()));
- return;
- }
- processServerHelloDone();
- break;
- case 20: // FINISHED
- if (!changeCipherSpecReceived) {
- unexpectedMessage();
- return;
- }
- serverFinished = new Finished(io_stream, length);
- verifyFinished(serverFinished.getData());
- session.lastAccessedTime = System.currentTimeMillis();
- // BEGIN android-added
- session.context = parameters.getClientSessionContext();
- // END android-added
- parameters.getClientSessionContext().putSession(session);
- if (isResuming) {
- sendChangeCipherSpec();
- } else {
- session.lastAccessedTime = System.currentTimeMillis();
- status = FINISHED;
- }
- // XXX there is no cleanup work
- break;
- default:
- unexpectedMessage();
- return;
- }
- } catch (IOException e) {
- // io stream dosn't contain complete handshake message
- io_stream.reset();
- return;
- }
- }
-
- }
-
- /**
- * Processes SSLv2 Hello message.
- * SSLv2 client hello message message is an unexpected message
- * for client side of handshake protocol.
- * @ see TLS 1.0 spec., E.1. Version 2 client hello
- * @param bytes
- */
- @Override
- public void unwrapSSLv2(byte[] bytes) {
- unexpectedMessage();
- }
-
- /**
- * Creates and sends Finished message
- */
- @Override
- protected void makeFinished() {
- byte[] verify_data;
- if (serverHello.server_version[1] == 1) {
- verify_data = new byte[12];
- computerVerifyDataTLS("client finished", verify_data);
- } else {
- verify_data = new byte[36];
- computerVerifyDataSSLv3(SSLv3Constants.client, verify_data);
- }
- clientFinished = new Finished(verify_data);
- send(clientFinished);
- if (isResuming) {
- session.lastAccessedTime = System.currentTimeMillis();
- status = FINISHED;
- } else {
- if (serverHello.server_version[1] == 1) {
- computerReferenceVerifyDataTLS("server finished");
- } else {
- computerReferenceVerifyDataSSLv3(SSLv3Constants.server);
- }
- status = NEED_UNWRAP;
- }
- }
-
- /**
- * Processes ServerHelloDone: makes verification of the server messages; sends
- * client messages, computers masterSecret, sends ChangeCipherSpec
- */
- void processServerHelloDone() {
- PrivateKey clientKey = null;
-
- if (serverCert != null) {
- if (session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DH_anon
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DH_anon_EXPORT) {
- unexpectedMessage();
- return;
- }
- verifyServerCert();
- } else {
- if (session.cipherSuite.keyExchange != CipherSuite.KeyExchange_DH_anon
- && session.cipherSuite.keyExchange != CipherSuite.KeyExchange_DH_anon_EXPORT) {
- unexpectedMessage();
- return;
- }
- }
-
- // Client certificate
- if (certificateRequest != null) {
- X509Certificate[] certs = null;
- String clientAlias = ((X509ExtendedKeyManager) parameters
- .getKeyManager()).chooseClientAlias(certificateRequest
- .getTypesAsString(),
- certificateRequest.certificate_authorities, null);
- if (clientAlias != null) {
- X509ExtendedKeyManager km = (X509ExtendedKeyManager) parameters
- .getKeyManager();
- certs = km.getCertificateChain((clientAlias));
- clientKey = km.getPrivateKey(clientAlias);
- }
- session.localCertificates = certs;
- clientCert = new CertificateMessage(certs);
- send(clientCert);
- }
- // Client key exchange
- if (session.cipherSuite.keyExchange == CipherSuite.KeyExchange_RSA
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_RSA_EXPORT) {
- // RSA encrypted premaster secret message
- Cipher c;
- try {
- c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
- if (serverKeyExchange != null) {
- c.init(Cipher.ENCRYPT_MODE, serverKeyExchange
- .getRSAPublicKey());
- } else {
- c.init(Cipher.ENCRYPT_MODE, serverCert.certs[0]);
- }
- } catch (Exception e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR,
- "Unexpected exception", e);
- return;
- }
- preMasterSecret = new byte[48];
- parameters.getSecureRandom().nextBytes(preMasterSecret);
- System.arraycopy(clientHello.client_version, 0, preMasterSecret, 0,
- 2);
- try {
- clientKeyExchange = new ClientKeyExchange(c
- .doFinal(preMasterSecret),
- serverHello.server_version[1] == 1);
- } catch (Exception e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR,
- "Unexpected exception", e);
- return;
- }
- } else {
- PublicKey serverPublic;
- KeyAgreement agreement = null;
- DHParameterSpec spec;
- try {
- KeyFactory kf = null;
- try {
- kf = KeyFactory.getInstance("DH");
- } catch (NoSuchAlgorithmException e) {
- kf = KeyFactory.getInstance("DiffieHellman");
- }
-
- try {
- agreement = KeyAgreement.getInstance("DH");
- } catch (NoSuchAlgorithmException ee) {
- agreement = KeyAgreement.getInstance("DiffieHellman");
- }
-
- KeyPairGenerator kpg = null;
- try {
- kpg = KeyPairGenerator.getInstance("DH");
- } catch (NoSuchAlgorithmException e) {
- kpg = KeyPairGenerator.getInstance("DiffieHellman");
- }
- if (serverKeyExchange != null) {
- serverPublic = kf.generatePublic(new DHPublicKeySpec(
- serverKeyExchange.par3, serverKeyExchange.par1,
- serverKeyExchange.par2));
- spec = new DHParameterSpec(serverKeyExchange.par1,
- serverKeyExchange.par2);
- } else {
- serverPublic = serverCert.certs[0].getPublicKey();
- spec = ((DHPublicKey) serverPublic).getParams();
- }
- kpg.initialize(spec);
-
- KeyPair kp = kpg.generateKeyPair();
- Key key = kp.getPublic();
- if (clientCert != null
- && serverCert != null
- && (session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DHE_RSA
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DHE_DSS)) {
- PublicKey client_pk = clientCert.certs[0].getPublicKey();
- PublicKey server_pk = serverCert.certs[0].getPublicKey();
- if (client_pk instanceof DHKey
- && server_pk instanceof DHKey) {
- if (((DHKey) client_pk).getParams().getG().equals(
- ((DHKey) server_pk).getParams().getG())
- && ((DHKey) client_pk).getParams().getP()
- .equals(((DHKey) server_pk).getParams().getG())) {
- // client cert message DH public key parameters
- // matched those specified by the
- // server in its certificate,
- clientKeyExchange = new ClientKeyExchange(); // empty
- }
- }
- } else {
- clientKeyExchange = new ClientKeyExchange(
- ((DHPublicKey) key).getY());
- }
- key = kp.getPrivate();
- agreement.init(key);
- agreement.doPhase(serverPublic, true);
- preMasterSecret = agreement.generateSecret();
- } catch (Exception e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR,
- "Unexpected exception", e);
- return;
- }
- }
- if (clientKeyExchange != null) {
- send(clientKeyExchange);
- }
-
- computerMasterSecret();
-
- // send certificate verify for all certificates except those containing
- // fixed DH parameters
- if (clientCert != null && !clientKeyExchange.isEmpty()) {
- // Certificate verify
- DigitalSignature ds = new DigitalSignature(
- session.cipherSuite.keyExchange);
- ds.init(clientKey);
-
- if (session.cipherSuite.keyExchange == CipherSuite.KeyExchange_RSA_EXPORT
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_RSA
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DHE_RSA
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DHE_RSA_EXPORT) {
- ds.setMD5(io_stream.getDigestMD5());
- ds.setSHA(io_stream.getDigestSHA());
- } else if (session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DHE_DSS
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DHE_DSS_EXPORT) {
- ds.setSHA(io_stream.getDigestSHA());
- // The Signature should be empty in case of anonimous signature algorithm:
- // } else if (session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DH_anon ||
- // session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DH_anon_EXPORT) {
- }
- certificateVerify = new CertificateVerify(ds.sign());
- send(certificateVerify);
- }
-
- sendChangeCipherSpec();
- }
-
- /*
- * Verifies certificate path
- */
- private void verifyServerCert() {
- String authType = null;
- switch (session.cipherSuite.keyExchange) {
- case 1: // KeyExchange_RSA
- authType = "RSA";
- break;
- case 2: // KeyExchange_RSA_EXPORT
- if (serverKeyExchange != null ) {
- // ephemeral RSA key is used
- authType = "RSA_EXPORT";
- } else {
- authType = "RSA";
- }
- break;
- case 3: // KeyExchange_DHE_DSS
- case 4: // KeyExchange_DHE_DSS_EXPORT
- authType = "DHE_DSS";
- break;
- case 5: // KeyExchange_DHE_RSA
- case 6: // KeyExchange_DHE_RSA_EXPORT
- authType = "DHE_RSA";
- break;
- case 7: // KeyExchange_DH_DSS
- case 11: // KeyExchange_DH_DSS_EXPORT
- authType = "DH_DSS";
- break;
- case 8: // KeyExchange_DH_RSA
- case 12: // KeyExchange_DH_RSA_EXPORT
- authType = "DH_RSA";
- break;
- case 9: // KeyExchange_DH_anon
- case 10: // KeyExchange_DH_anon_EXPORT
- return;
- }
- try {
- parameters.getTrustManager().checkServerTrusted(serverCert.certs,
- authType);
- } catch (CertificateException e) {
- fatalAlert(AlertProtocol.BAD_CERTIFICATE, "Not trusted server certificate", e);
- return;
- }
- session.peerCertificates = serverCert.certs;
- }
-
- /**
- * Processes ChangeCipherSpec message
- */
- @Override
- public void receiveChangeCipherSpec() {
- if (isResuming) {
- if (serverHello == null) {
- unexpectedMessage();
- }
- } else if (clientFinished == null) {
- unexpectedMessage();
- }
- changeCipherSpecReceived = true;
- }
-
- // Find session to resume in client session context
- private SSLSessionImpl findSessionToResume() {
- // BEGIN android-changed
- String host = null;
- int port = -1;
- if (engineOwner != null) {
- host = engineOwner.getPeerHost();
- port = engineOwner.getPeerPort();
- }
- if (host == null || port == -1) {
- return null; // starts new session
- }
-
- ClientSessionContext context = parameters.getClientSessionContext();
- SSLSessionImpl session
- = (SSLSessionImpl) context.getSession(host, port);
- if (session != null) {
- session = (SSLSessionImpl) session.clone();
- }
- return session;
- // END android-changed
- }
-
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientHello.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientHello.java
deleted file mode 100644
index 5764105..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientHello.java
+++ /dev/null
@@ -1,206 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.IOException;
-import java.security.SecureRandom;
-import java.util.Arrays;
-
-/**
- * Represents Client Hello message
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7.4.1.2.
- * Client hello</a>
- *
- */
-public class ClientHello extends Message {
-
- /**
- * Client version
- */
- final byte[] client_version;
-
- /**
- * Random bytes
- */
- final byte[] random = new byte[32];
-
- /**
- * Session id
- */
- final byte[] session_id;
-
- /**
- * Cipher suites supported by the client
- */
- final CipherSuite[] cipher_suites;
-
- /**
- * Compression methods supported by the client
- */
- final byte[] compression_methods;
-
- /**
- * Creates outbound message
- * @param sr
- * @param version
- * @param ses_id
- * @param cipher_suite
- */
- public ClientHello(SecureRandom sr, byte[] version, byte[] ses_id,
- CipherSuite[] cipher_suite) {
- client_version = version;
- long gmt_unix_time = System.currentTimeMillis()/1000;
- sr.nextBytes(random);
- random[0] = (byte) (gmt_unix_time & 0xFF000000 >>> 24);
- random[1] = (byte) (gmt_unix_time & 0xFF0000 >>> 16);
- random[2] = (byte) (gmt_unix_time & 0xFF00 >>> 8);
- random[3] = (byte) (gmt_unix_time & 0xFF);
- session_id = ses_id;
- this.cipher_suites = cipher_suite;
- compression_methods = new byte[] { 0 }; // CompressionMethod.null
- length = 38 + session_id.length + (this.cipher_suites.length << 1)
- + compression_methods.length;
- }
-
- /**
- * Creates inbound message
- * @param in
- * @param length
- * @throws IOException
- */
- public ClientHello(HandshakeIODataStream in, int length) throws IOException {
- client_version = new byte[2];
- client_version[0] = (byte) in.readUint8();
- client_version[1] = (byte) in.readUint8();
- in.read(random, 0, 32);
- int size = in.read();
- session_id = new byte[size];
- in.read(session_id, 0, size);
- int l = in.readUint16();
- if ((l & 0x01) == 0x01) { // cipher suites length must be an even number
- fatalAlert(AlertProtocol.DECODE_ERROR,
- "DECODE ERROR: incorrect ClientHello");
- }
- size = l >> 1;
- cipher_suites = new CipherSuite[size];
- for (int i = 0; i < size; i++) {
- byte b0 = (byte) in.read();
- byte b1 = (byte) in.read();
- cipher_suites[i] = CipherSuite.getByCode(b0, b1);
- }
- size = in.read();
- compression_methods = new byte[size];
- in.read(compression_methods, 0, size);
- this.length = 38 + session_id.length + (cipher_suites.length << 1)
- + compression_methods.length;
- if (this.length > length) {
- fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR: incorrect ClientHello");
- }
- // for forward compatibility, extra data is permitted;
- // must be ignored
- if (this.length < length) {
- in.skip(length - this.length);
- this.length = length;
- }
- }
- /**
- * Parse V2ClientHello
- * @param in
- * @throws IOException
- */
- public ClientHello(HandshakeIODataStream in) throws IOException {
- if (in.readUint8() != 1) {
- fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR: incorrect V2ClientHello");
- }
- client_version = new byte[2];
- client_version[0] = (byte) in.readUint8();
- client_version[1] = (byte) in.readUint8();
- int cipher_spec_length = in.readUint16();
- if (in.readUint16() != 0) { // session_id_length
- // as client already knows the protocol known to a server it should
- // initiate the connection in that native protocol
- fatalAlert(AlertProtocol.DECODE_ERROR,
- "DECODE ERROR: incorrect V2ClientHello, cannot be used for resuming");
- }
- int challenge_length = in.readUint16();
- if (challenge_length < 16) {
- fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR: incorrect V2ClientHello, short challenge data");
- }
- session_id = new byte[0];
- cipher_suites = new CipherSuite[cipher_spec_length/3];
- for (int i = 0; i < cipher_suites.length; i++) {
- byte b0 = (byte) in.read();
- byte b1 = (byte) in.read();
- byte b2 = (byte) in.read();
- cipher_suites[i] = CipherSuite.getByCode(b0, b1, b2);
- }
- compression_methods = new byte[] { 0 }; // CompressionMethod.null
-
- if (challenge_length < 32) {
- Arrays.fill(random, 0, 32 - challenge_length, (byte)0);
- System.arraycopy(in.read(challenge_length), 0, random, 32 - challenge_length, challenge_length);
- } else if (challenge_length == 32) {
- System.arraycopy(in.read(32), 0, random, 0, 32);
- } else {
- System.arraycopy(in.read(challenge_length), challenge_length - 32, random, 0, 32);
- }
- if (in.available() > 0) {
- fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR: incorrect V2ClientHello, extra data");
- }
- this.length = 38 + session_id.length + (cipher_suites.length << 1)
- + compression_methods.length;
- }
-
- /**
- * Sends message
- * @param out
- */
- @Override
- public void send(HandshakeIODataStream out) {
- out.write(client_version);
- out.write(random);
- out.writeUint8(session_id.length);
- out.write(session_id);
- int size = cipher_suites.length << 1;
- out.writeUint16(size);
- for (int i = 0; i < cipher_suites.length; i++) {
- out.write(cipher_suites[i].toBytes());
- }
- out.writeUint8(compression_methods.length);
- for (int i = 0; i < compression_methods.length; i++) {
- out.write(compression_methods[i]);
- }
- }
-
- /**
- * Returns client random
- * @return client random
- */
- public byte[] getRandom() {
- return random;
- }
-
- /**
- * Returns message type
- * @return
- */
- @Override
- public int getType() {
- return Handshake.CLIENT_HELLO;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientKeyExchange.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientKeyExchange.java
deleted file mode 100644
index af751c2..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientKeyExchange.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.Message;
-import org.apache.harmony.xnet.provider.jsse.Handshake;
-import org.apache.harmony.xnet.provider.jsse.HandshakeIODataStream;
-
-import java.io.IOException;
-import java.math.BigInteger;
-
-/**
- * Represents client key exchange message
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7.4.7.
- * Client key exchange message</a>
- *
- */
-public class ClientKeyExchange extends Message {
-
- /**
- * Exchange keys
- */
- final byte[] exchange_keys;
-
- /**
- * Equals true if TLS1.0 protocol is used
- */
- boolean isTLS;
-
- /**
- * Equals true if key exchange algorithm is RSA
- */
- final boolean isRSA;
-
- /**
- * Creates outbound message
- * @param encrypted_pre_master_secret
- * @param isTLS
- */
- public ClientKeyExchange(byte[] encrypted_pre_master_secret, boolean isTLS) {
- this.exchange_keys = encrypted_pre_master_secret;
- length = this.exchange_keys.length;
- if (isTLS) {
- length += 2;
- }
- this.isTLS = isTLS;
- isRSA = true;
- }
-
- /**
- * Creates outbound message
- * @param dh_Yc
- */
- public ClientKeyExchange(BigInteger dh_Yc) {
- byte[] bb = dh_Yc.toByteArray();
- if (bb[0] == 0) {
- exchange_keys = new byte[bb.length-1];
- System.arraycopy(bb, 1, exchange_keys, 0, exchange_keys.length);
- } else {
- exchange_keys = bb;
- }
- length = exchange_keys.length +2;
- isRSA = false;
- }
-
- /**
- * Creates empty message
- *
- */
- public ClientKeyExchange() {
- exchange_keys = new byte[0];
- length = 0;
- isRSA = false;
- }
-
- /**
- * Creates inbound message
- * @param length
- * @param isTLS
- * @param isRSA
- * @throws IOException
- */
- public ClientKeyExchange(HandshakeIODataStream in, int length, boolean isTLS, boolean isRSA)
- throws IOException {
- this.isTLS = isTLS;
- this.isRSA = isRSA;
- if (length == 0) {
- this.length = 0;
- exchange_keys = new byte[0];
- } else {
- int size;
- if (isRSA && !isTLS) {// SSL3.0 RSA
- size = length;
- this.length = size;
- } else { // DH or TLSv1 RSA
- size = in.readUint16();
- this.length = 2 + size;
- }
- exchange_keys = new byte[size];
- in.read(exchange_keys, 0, size);
- if (this.length != length) {
- fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR: incorrect ClientKeyExchange");
- }
- }
- }
-
- /**
- * Sends message
- * @param out
- */
- @Override
- public void send(HandshakeIODataStream out) {
- if (exchange_keys.length != 0) {
- if (!isRSA || isTLS) {// DH or TLSv1 RSA
- out.writeUint16(exchange_keys.length);
- }
- out.write(exchange_keys);
- }
- }
-
- /**
- * Returns message type
- * @return
- */
- @Override
- public int getType() {
- return Handshake.CLIENT_KEY_EXCHANGE;
- }
-
- /**
- * Returns true if the message is empty (in case of implicit DH Yc)
- * @return
- */
- public boolean isEmpty() {
- return (exchange_keys.length == 0);
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientSessionContext.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientSessionContext.java
deleted file mode 100644
index 66e8d03..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientSessionContext.java
+++ /dev/null
@@ -1,229 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.HashMap;
-import java.util.ArrayList;
-import java.util.Arrays;
-
-import javax.net.ssl.SSLSession;
-
-/**
- * Caches client sessions. Indexes by host and port. Users are typically
- * looking to reuse any session for a given host and port. Users of the
- * standard API are forced to iterate over the sessions semi-linearly as
- * opposed to in constant time.
- */
-public class ClientSessionContext extends AbstractSessionContext {
-
- /*
- * We don't care about timeouts in the client implementation. Trying
- * to reuse an expired session and having to start a new one requires no
- * more effort than starting a new one, so you might as well try to reuse
- * one on the off chance it's still valid.
- */
-
- /** Sessions indexed by host and port in access order. */
- final Map<HostAndPort, SSLSession> sessions
- = new LinkedHashMap<HostAndPort, SSLSession>() {
- @Override
- protected boolean removeEldestEntry(
- Map.Entry<HostAndPort, SSLSession> eldest) {
- // Called while lock is held on sessions.
- boolean remove = maximumSize > 0 && size() > maximumSize;
- if (remove) {
- removeById(eldest.getValue());
- }
- return remove;
- }
- };
-
- /**
- * Sessions indexed by ID. Initialized on demand. Protected from concurrent
- * access by holding a lock on sessions.
- */
- Map<ByteArray, SSLSession> sessionsById;
-
- final SSLClientSessionCache persistentCache;
-
- public ClientSessionContext(int sslCtxNativePointer,
- SSLClientSessionCache persistentCache) {
- super(sslCtxNativePointer, 10, 0);
- this.persistentCache = persistentCache;
- }
-
- public final void setSessionTimeout(int seconds)
- throws IllegalArgumentException {
- if (seconds < 0) {
- throw new IllegalArgumentException("seconds < 0");
- }
- timeout = seconds;
- }
-
- Iterator<SSLSession> sessionIterator() {
- synchronized (sessions) {
- SSLSession[] array = sessions.values().toArray(
- new SSLSession[sessions.size()]);
- return Arrays.asList(array).iterator();
- }
- }
-
- void trimToSize() {
- synchronized (sessions) {
- int size = sessions.size();
- if (size > maximumSize) {
- int removals = size - maximumSize;
- Iterator<SSLSession> i = sessions.values().iterator();
- do {
- removeById(i.next());
- i.remove();
- } while (--removals > 0);
- }
- }
- }
-
- void removeById(SSLSession session) {
- if (sessionsById != null) {
- sessionsById.remove(new ByteArray(session.getId()));
- }
- }
-
- /**
- * {@inheritDoc}
- *
- * @see #getSession(String, int) for an implementation-specific but more
- * efficient approach
- */
- public SSLSession getSession(byte[] sessionId) {
- /*
- * This method is typically used in conjunction with getIds() to
- * iterate over the sessions linearly, so it doesn't make sense for
- * it to impact access order.
- *
- * It also doesn't load sessions from the persistent cache as doing
- * so would likely force every session to load.
- */
-
- ByteArray id = new ByteArray(sessionId);
- synchronized (sessions) {
- indexById();
- return sessionsById.get(id);
- }
- }
-
- /**
- * Ensures that the ID-based index is initialized.
- */
- private void indexById() {
- if (sessionsById == null) {
- sessionsById = new HashMap<ByteArray, SSLSession>();
- for (SSLSession session : sessions.values()) {
- sessionsById.put(new ByteArray(session.getId()), session);
- }
- }
- }
-
- /**
- * Adds the given session to the ID-based index if the index has already
- * been initialized.
- */
- private void indexById(byte[] id, SSLSession session) {
- if (sessionsById != null) {
- sessionsById.put(new ByteArray(id), session);
- }
- }
-
- /**
- * Finds a cached session for the given host name and port.
- *
- * @param host of server
- * @param port of server
- * @return cached session or null if none found
- */
- public SSLSession getSession(String host, int port) {
- synchronized (sessions) {
- SSLSession session = sessions.get(new HostAndPort(host, port));
- if (session != null) {
- return session;
- }
- }
-
- // Look in persistent cache.
- if (persistentCache != null) {
- byte[] data = persistentCache.getSessionData(host, port);
- if (data != null) {
- SSLSession session = toSession(data, host, port);
- if (session != null) {
- synchronized (sessions) {
- sessions.put(new HostAndPort(host, port), session);
- indexById(session.getId(), session);
- }
- return session;
- }
- }
- }
-
- return null;
- }
-
- @Override
- void putSession(SSLSession session) {
- byte[] id = session.getId();
- if (id.length == 0) {
- return;
- }
- HostAndPort key = new HostAndPort(session.getPeerHost(),
- session.getPeerPort());
- synchronized (sessions) {
- sessions.put(key, session);
- indexById(id, session);
- }
-
- // TODO: This in a background thread.
- if (persistentCache != null) {
- byte[] data = toBytes(session);
- if (data != null) {
- persistentCache.putSessionData(session, data);
- }
- }
- }
-
- static class HostAndPort {
- final String host;
- final int port;
-
- HostAndPort(String host, int port) {
- this.host = host;
- this.port = port;
- }
-
- @Override
- public int hashCode() {
- return host.hashCode() * 31 + port;
- }
-
- @Override
- @SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
- public boolean equals(Object o) {
- HostAndPort other = (HostAndPort) o;
- return host.equals(other.host) && port == other.port;
- }
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ConnectionState.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ConnectionState.java
deleted file mode 100644
index 49a7af9..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ConnectionState.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.Logger;
-
-import javax.crypto.Cipher;
-
-/**
- * This abstract class is a base for Record Protocol operating environmet
- * of different SSL protocol versions.
- */
-public abstract class ConnectionState {
-
- /**
- * The cipher used for encode operations
- */
- protected Cipher encCipher;
-
- /**
- * The cipher used for decode operations
- */
- protected Cipher decCipher;
-
- /**
- * The cipher type
- */
- protected boolean is_block_cipher;
-
- /**
- * The size of MAC used under this connection state
- */
- protected int hash_size;
-
- /**
- * Write sequence number which is incremented after each
- * encrypt call
- */
- protected final byte[] write_seq_num = {0, 0, 0, 0, 0, 0, 0, 0};
-
- /**
- * Read sequence number which is incremented after each
- * decrypt call
- */
- protected final byte[] read_seq_num = {0, 0, 0, 0, 0, 0, 0, 0};
-
- protected Logger.Stream logger = Logger.getStream("conn_state");
-
- /**
- * Returns the minimal possible size of the
- * Generic[Stream|Generic]Cipher structure under this
- * connection state.
- */
- protected int getMinFragmentSize() {
- // block ciphers return value with padding included
- return encCipher.getOutputSize(1+hash_size); // 1 byte for data
- }
-
- /**
- * Returns the size of the Generic[Stream|Generic]Cipher structure
- * corresponding to the content data of specified size.
- */
- protected int getFragmentSize(int content_size) {
- return encCipher.getOutputSize(content_size+hash_size);
- }
-
- /**
- * Returns the minimal upper bound of the content size enclosed
- * into the Generic[Stream|Generic]Cipher structure of specified size.
- * For stream ciphers the returned value will be exact value.
- */
- protected int getContentSize(int generic_cipher_size) {
- //it does not take the padding of block ciphered structures
- //into account (so returned value can be greater than actual)
- return decCipher.getOutputSize(generic_cipher_size)-hash_size;
- }
-
- /**
- * Creates the GenericStreamCipher or GenericBlockCipher
- * data structure for specified data of specified type.
- * @param type - the ContentType of the provided data
- * @param fragment - the byte array containing the
- * data to be encrypted under the current connection state.
- */
- protected byte[] encrypt(byte type, byte[] fragment) {
- return encrypt(type, fragment, 0, fragment.length);
- }
-
- /**
- * Creates the GenericStreamCipher or GenericBlockCipher
- * data structure for specified data of specified type.
- * @param type - the ContentType of the provided data
- * @param fragment - the byte array containing the
- * data to be encrypted under the current connection state.
- * @param offset - the offset from which the data begins with.
- * @param len - the length of the data.
- */
- protected abstract byte[] encrypt
- (byte type, byte[] fragment, int offset, int len);
-
- /**
- * Retrieves the fragment of the Plaintext structure of
- * the specified type from the provided data.
- * @param type - the ContentType of the data to be decrypted.
- * @param fragment - the byte array containing the
- * data to be encrypted under the current connection state.
- */
- protected byte[] decrypt(byte type, byte[] fragment) {
- return decrypt(type, fragment, 0, fragment.length);
- }
-
- /**
- * Retrieves the fragment of the Plaintext structure of
- * the specified type from the provided data.
- * @param type - the ContentType of the data to be decrypted.
- * @param fragment - the byte array containing the
- * data to be encrypted under the current connection state.
- * @param offset - the offset from which the data begins with.
- * @param len - the length of the data.
- */
- protected abstract byte[] decrypt
- (byte type, byte[] fragment, int offset, int len);
-
- /**
- * Increments the sequence number.
- */
- protected static void incSequenceNumber(byte[] seq_num) {
- int octet = 7;
- while (octet >= 0) {
- seq_num[octet] ++;
- if (seq_num[octet] == 0) {
- // characteristic overflow, so
- // carrying a number in adding
- octet --;
- } else {
- return;
- }
- }
- }
-
- /**
- * Shutdownes the protocol. It will be impossiblke to use the instance
- * after the calling of this method.
- */
- protected void shutdown() {
- encCipher = null;
- decCipher = null;
- for (int i=0; i<write_seq_num.length; i++) {
- write_seq_num[i] = 0;
- read_seq_num[i] = 0;
- }
- }
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ConnectionStateSSLv3.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ConnectionStateSSLv3.java
deleted file mode 100644
index 07bd340..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ConnectionStateSSLv3.java
+++ /dev/null
@@ -1,354 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.security.GeneralSecurityException;
-import java.security.MessageDigest;
-import java.util.Arrays;
-import javax.crypto.Cipher;
-import javax.crypto.spec.IvParameterSpec;
-import javax.crypto.spec.SecretKeySpec;
-import javax.net.ssl.SSLProtocolException;
-
-/**
- * This class encapsulates the operating environment of the SSL v3
- * (http://wp.netscape.com/eng/ssl3) Record Protocol and provides
- * relating encryption/decryption functionality.
- * The work functionality is based on the security
- * parameters negotiated during the handshake.
- */
-public class ConnectionStateSSLv3 extends ConnectionState {
-
- // digest to create and check the message integrity info
- private final MessageDigest messageDigest;
- private final byte[] mac_write_secret;
- private final byte[] mac_read_secret;
-
- // paddings
- private final byte[] pad_1;
- private final byte[] pad_2;
- // array will hold the part of the MAC material:
- // length of 3 == 1(SSLCompressed.type) + 2(SSLCompressed.length)
- // (more on SSLv3 MAC computation and payload protection see
- // SSL v3 specification, p. 5.2.3)
- private final byte[] mac_material_part = new byte[3];
-
- /**
- * Creates the instance of SSL v3 Connection State. All of the
- * security parameters are provided by session object.
- * @param session: the sessin object which incapsulates
- * all of the security parameters established by handshake protocol.
- * The key calculation for the state is done according
- * to the SSL v3 Protocol specification.
- * (http://www.mozilla.org/projects/security/pki/nss/ssl/draft302.txt)
- */
- protected ConnectionStateSSLv3(SSLSessionImpl session) {
- try {
- CipherSuite cipherSuite = session.cipherSuite;
-
- boolean is_exportabe = cipherSuite.isExportable();
- hash_size = cipherSuite.getMACLength();
- int key_size = (is_exportabe)
- ? cipherSuite.keyMaterial
- : cipherSuite.expandedKeyMaterial;
- int iv_size = cipherSuite.getBlockSize();
-
- String algName = cipherSuite.getBulkEncryptionAlgorithm();
- String hashName = cipherSuite.getHashName();
- if (logger != null) {
- logger.println("ConnectionStateSSLv3.create:");
- logger.println(" cipher suite name: "
- + session.getCipherSuite());
- logger.println(" encryption alg name: " + algName);
- logger.println(" hash alg name: " + hashName);
- logger.println(" hash size: " + hash_size);
- logger.println(" block size: " + iv_size);
- logger.println(" IV size (== block size):" + iv_size);
- logger.println(" key size: " + key_size);
- }
-
- byte[] clientRandom = session.clientRandom;
- byte[] serverRandom = session.serverRandom;
- // so we need PRF value of size of
- // 2*hash_size + 2*key_size + 2*iv_size
- byte[] key_block = new byte[2*hash_size + 2*key_size + 2*iv_size];
- byte[] seed = new byte[clientRandom.length + serverRandom.length];
- System.arraycopy(serverRandom, 0, seed, 0, serverRandom.length);
- System.arraycopy(clientRandom, 0, seed, serverRandom.length,
- clientRandom.length);
-
- PRF.computePRF_SSLv3(key_block, session.master_secret, seed);
-
- byte[] client_mac_secret = new byte[hash_size];
- byte[] server_mac_secret = new byte[hash_size];
- byte[] client_key = new byte[key_size];
- byte[] server_key = new byte[key_size];
-
- boolean is_client = !session.isServer;
-
- is_block_cipher = (iv_size > 0);
-
- System.arraycopy(key_block, 0, client_mac_secret, 0, hash_size);
- System.arraycopy(key_block, hash_size,
- server_mac_secret, 0, hash_size);
- System.arraycopy(key_block, 2*hash_size, client_key, 0, key_size);
- System.arraycopy(key_block, 2*hash_size+key_size,
- server_key, 0, key_size);
-
- IvParameterSpec clientIV = null;
- IvParameterSpec serverIV = null;
-
- if (is_exportabe) {
- if (logger != null) {
- logger.println("ConnectionStateSSLv3: is_exportable");
- }
-
- MessageDigest md5 = MessageDigest.getInstance("MD5");
- md5.update(client_key);
- md5.update(clientRandom);
- md5.update(serverRandom);
- client_key = md5.digest();
-
- md5.update(server_key);
- md5.update(serverRandom);
- md5.update(clientRandom);
- server_key = md5.digest();
-
- key_size = cipherSuite.expandedKeyMaterial;
-
- if (is_block_cipher) {
- md5.update(clientRandom);
- md5.update(serverRandom);
- clientIV = new IvParameterSpec(md5.digest(), 0, iv_size);
- md5.update(serverRandom);
- md5.update(clientRandom);
- serverIV = new IvParameterSpec(md5.digest(), 0, iv_size);
- }
- } else if (is_block_cipher) {
- clientIV = new IvParameterSpec(key_block,
- 2*hash_size+2*key_size, iv_size);
- serverIV = new IvParameterSpec(key_block,
- 2*hash_size+2*key_size+iv_size, iv_size);
- }
-
- if (logger != null) {
- logger.println("is exportable: "+is_exportabe);
- logger.println("master_secret");
- logger.print(session.master_secret);
- logger.println("client_random");
- logger.print(clientRandom);
- logger.println("server_random");
- logger.print(serverRandom);
- //logger.println("key_block");
- //logger.print(key_block);
- logger.println("client_mac_secret");
- logger.print(client_mac_secret);
- logger.println("server_mac_secret");
- logger.print(server_mac_secret);
- logger.println("client_key");
- logger.print(client_key, 0, key_size);
- logger.println("server_key");
- logger.print(server_key, 0, key_size);
- if (clientIV != null) {
- logger.println("client_iv");
- logger.print(clientIV.getIV());
- logger.println("server_iv");
- logger.print(serverIV.getIV());
- } else {
- logger.println("no IV.");
- }
- }
- encCipher = Cipher.getInstance(algName);
- decCipher = Cipher.getInstance(algName);
- messageDigest = MessageDigest.getInstance(hashName);
- if (is_client) { // client side
- encCipher.init(Cipher.ENCRYPT_MODE,
- new SecretKeySpec(client_key, 0, key_size, algName),
- clientIV);
- decCipher.init(Cipher.DECRYPT_MODE,
- new SecretKeySpec(server_key, 0, key_size, algName),
- serverIV);
- mac_write_secret = client_mac_secret;
- mac_read_secret = server_mac_secret;
- } else { // server side
- encCipher.init(Cipher.ENCRYPT_MODE,
- new SecretKeySpec(server_key, 0, key_size, algName),
- serverIV);
- decCipher.init(Cipher.DECRYPT_MODE,
- new SecretKeySpec(client_key, 0, key_size, algName),
- clientIV);
- mac_write_secret = server_mac_secret;
- mac_read_secret = client_mac_secret;
- }
- if (hashName.equals("MD5")) {
- pad_1 = SSLv3Constants.MD5pad1;
- pad_2 = SSLv3Constants.MD5pad2;
- } else {
- pad_1 = SSLv3Constants.SHApad1;
- pad_2 = SSLv3Constants.SHApad2;
- }
- } catch (Exception e) {
- e.printStackTrace();
- throw new AlertException(AlertProtocol.INTERNAL_ERROR,
- new SSLProtocolException(
- "Error during computation of security parameters"));
- }
- }
-
- /**
- * Creates the GenericStreamCipher or GenericBlockCipher
- * data structure for specified data of specified type.
- * @throws AlertException if alert was occurred.
- */
- @Override
- protected byte[] encrypt(byte type, byte[] fragment, int offset, int len) {
- try {
- int content_mac_length = len + hash_size;
- int padding_length = is_block_cipher
- ? padding_length =
- ((8 - (++content_mac_length & 0x07)) & 0x07)
- : 0;
- byte[] res = new byte[content_mac_length + padding_length];
- System.arraycopy(fragment, offset, res, 0, len);
-
- mac_material_part[0] = type;
- mac_material_part[1] = (byte) ((0x00FF00 & len) >> 8);
- mac_material_part[2] = (byte) (0x0000FF & len);
-
- messageDigest.update(mac_write_secret);
- messageDigest.update(pad_1);
- messageDigest.update(write_seq_num);
- messageDigest.update(mac_material_part);
- messageDigest.update(fragment, offset, len);
- byte[] digest = messageDigest.digest();
- messageDigest.update(mac_write_secret);
- messageDigest.update(pad_2);
- messageDigest.update(digest);
- digest = messageDigest.digest();
- System.arraycopy(digest, 0, res, len, hash_size);
-
- //if (logger != null) {
- // logger.println("MAC Material:");
- // logger.print(write_seq_num);
- // logger.print(mac_material_header);
- // logger.print(fragment, offset, len);
- //}
-
- if (is_block_cipher) {
- // do padding:
- Arrays.fill(res, content_mac_length-1,
- res.length, (byte) (padding_length));
- }
- if (logger != null) {
- logger.println("SSLRecordProtocol.encrypt: "
- + (is_block_cipher
- ? "GenericBlockCipher with padding["
- +padding_length+"]:"
- : "GenericStreamCipher:"));
- logger.print(res);
- }
- byte[] rez = new byte[encCipher.getOutputSize(res.length)];
- encCipher.update(res, 0, res.length, rez);
- incSequenceNumber(write_seq_num);
- return rez;
- } catch (GeneralSecurityException e) {
- e.printStackTrace();
- throw new AlertException(AlertProtocol.INTERNAL_ERROR,
- new SSLProtocolException("Error during the encryption"));
- }
- }
-
- /**
- * Retrieves the fragment of the Plaintext structure of
- * the specified type from the provided data.
- * @throws AlertException if alert was occured.
- */
- @Override
- protected byte[] decrypt(byte type, byte[] fragment,
- int offset, int len) {
- // plain data of the Generic[Stream|Block]Cipher structure
- byte[] data = decCipher.update(fragment, offset, len);
- // the 'content' part of the structure
- byte[] content;
- if (is_block_cipher) {
- // check padding
- int padding_length = data[data.length-1];
- for (int i=0; i<padding_length; i++) {
- if (data[data.length-2-i] != padding_length) {
- throw new AlertException(
- AlertProtocol.DECRYPTION_FAILED,
- new SSLProtocolException(
- "Received message has bad padding"));
- }
- }
- content = new byte[data.length - hash_size - padding_length - 1];
- } else {
- content = new byte[data.length - hash_size];
- }
-
- byte[] mac_value;
-
- mac_material_part[0] = type;
- mac_material_part[1] = (byte) ((0x00FF00 & content.length) >> 8);
- mac_material_part[2] = (byte) (0x0000FF & content.length);
-
- messageDigest.update(mac_read_secret);
- messageDigest.update(pad_1);
- messageDigest.update(read_seq_num);
- messageDigest.update(mac_material_part);
- messageDigest.update(data, 0, content.length);
- mac_value = messageDigest.digest();
- messageDigest.update(mac_read_secret);
- messageDigest.update(pad_2);
- messageDigest.update(mac_value);
- mac_value = messageDigest.digest();
-
- if (logger != null) {
- logger.println("Decrypted:");
- logger.print(data);
- //logger.println("MAC Material:");
- //logger.print(read_seq_num);
- //logger.print(mac_material_header);
- //logger.print(data, 0, content.length);
- logger.println("Expected mac value:");
- logger.print(mac_value);
- }
- // checking the mac value
- for (int i=0; i<hash_size; i++) {
- if (mac_value[i] != data[i+content.length]) {
- throw new AlertException(AlertProtocol.BAD_RECORD_MAC,
- new SSLProtocolException("Bad record MAC"));
- }
- }
- System.arraycopy(data, 0, content, 0, content.length);
- incSequenceNumber(read_seq_num);
- return content;
- }
-
- /**
- * Shutdown the protocol. It will be impossible to use the instance
- * after the calling of this method.
- */
- @Override
- protected void shutdown() {
- Arrays.fill(mac_write_secret, (byte) 0);
- Arrays.fill(mac_read_secret, (byte) 0);
- super.shutdown();
- }
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ConnectionStateTLS.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ConnectionStateTLS.java
deleted file mode 100644
index 949e655..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ConnectionStateTLS.java
+++ /dev/null
@@ -1,352 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.AlertException;
-import org.apache.harmony.xnet.provider.jsse.SSLSessionImpl;
-import org.apache.harmony.xnet.provider.jsse.PRF;
-import org.apache.harmony.xnet.provider.jsse.ConnectionState;
-
-import java.security.GeneralSecurityException;
-import java.util.Arrays;
-import javax.crypto.Cipher;
-import javax.crypto.Mac;
-import javax.crypto.spec.IvParameterSpec;
-import javax.crypto.spec.SecretKeySpec;
-import javax.net.ssl.SSLProtocolException;
-
-/**
- * This class encapsulates the operating environment of the TLS v1
- * (http://www.ietf.org/rfc/rfc2246.txt) Record Protocol and provides
- * relating encryption/decryption functionality.
- * The work functionality is based on the security
- * parameters negotiated during the handshake.
- */
-public class ConnectionStateTLS extends ConnectionState {
-
- // Pre-calculated prf label values:
- // "key expansion".getBytes()
- private static byte[] KEY_EXPANSION_LABEL = {
- (byte) 0x6B, (byte) 0x65, (byte) 0x79, (byte) 0x20, (byte) 0x65,
- (byte) 0x78, (byte) 0x70, (byte) 0x61, (byte) 0x6E, (byte) 0x73,
- (byte) 0x69, (byte) 0x6F, (byte) 0x6E };
-
- // "client write key".getBytes()
- private static byte[] CLIENT_WRITE_KEY_LABEL = {
- (byte) 0x63, (byte) 0x6C, (byte) 0x69, (byte) 0x65, (byte) 0x6E,
- (byte) 0x74, (byte) 0x20, (byte) 0x77, (byte) 0x72, (byte) 0x69,
- (byte) 0x74, (byte) 0x65, (byte) 0x20, (byte) 0x6B, (byte) 0x65,
- (byte) 0x79 };
-
- // "server write key".getBytes()
- private static byte[] SERVER_WRITE_KEY_LABEL = {
- (byte) 0x73, (byte) 0x65, (byte) 0x72, (byte) 0x76, (byte) 0x65,
- (byte) 0x72, (byte) 0x20, (byte) 0x77, (byte) 0x72, (byte) 0x69,
- (byte) 0x74, (byte) 0x65, (byte) 0x20, (byte) 0x6B, (byte) 0x65,
- (byte) 0x79 };
-
- // "IV block".getBytes()
- private static byte[] IV_BLOCK_LABEL = {
- (byte) 0x49, (byte) 0x56, (byte) 0x20, (byte) 0x62, (byte) 0x6C,
- (byte) 0x6F, (byte) 0x63, (byte) 0x6B };
-
- // MACs to create and check the message integrity info
- private final Mac encMac;
- private final Mac decMac;
-
- // Once created permanently used array:
- // is used to create the header of the MAC material value:
- // 5 == 1(TLSCompressed.type) + 2(TLSCompressed.version) +
- // 2(TLSCompressed.length)
- private final byte[] mac_material_header = new byte[] {0, 3, 1, 0, 0};
-
- /**
- * Creates the instance of TLS v1 Connection State. All of the
- * security parameters are provided by session object.
- * @param session: the sessin object which incapsulates
- * all of the security parameters established by handshake protocol.
- * The key calculation for the state is done according
- * to the TLS v 1.0 Protocol specification.
- * (http://www.ietf.org/rfc/rfc2246.txt)
- */
- protected ConnectionStateTLS(SSLSessionImpl session) {
- try {
- CipherSuite cipherSuite = session.cipherSuite;
-
- hash_size = cipherSuite.getMACLength();
- boolean is_exportabe = cipherSuite.isExportable();
- int key_size = (is_exportabe)
- ? cipherSuite.keyMaterial
- : cipherSuite.expandedKeyMaterial;
- int iv_size = cipherSuite.getBlockSize();
-
- String algName = cipherSuite.getBulkEncryptionAlgorithm();
- String macName = cipherSuite.getHmacName();
- if (logger != null) {
- logger.println("ConnectionStateTLS.create:");
- logger.println(" cipher suite name: "
- + cipherSuite.getName());
- logger.println(" encryption alg name: " + algName);
- logger.println(" mac alg name: " + macName);
- logger.println(" hash size: " + hash_size);
- logger.println(" block size: " + iv_size);
- logger.println(" IV size (== block size):" + iv_size);
- logger.println(" key size: " + key_size);
- }
-
- byte[] clientRandom = session.clientRandom;
- byte[] serverRandom = session.serverRandom;
- // so we need PRF value of size of
- // 2*hash_size + 2*key_size + 2*iv_size
- byte[] key_block = new byte[2*hash_size + 2*key_size + 2*iv_size];
- byte[] seed = new byte[clientRandom.length + serverRandom.length];
- System.arraycopy(serverRandom, 0, seed, 0, serverRandom.length);
- System.arraycopy(clientRandom, 0, seed, serverRandom.length,
- clientRandom.length);
-
- PRF.computePRF(key_block, session.master_secret,
- KEY_EXPANSION_LABEL, seed);
-
- byte[] client_mac_secret = new byte[hash_size];
- byte[] server_mac_secret = new byte[hash_size];
- byte[] client_key = new byte[key_size];
- byte[] server_key = new byte[key_size];
-
- boolean is_client = !session.isServer;
-
- is_block_cipher = (iv_size > 0);
- // do not count, as block_size is always 8
- // block_size = iv_size;
-
- System.arraycopy(key_block, 0, client_mac_secret, 0, hash_size);
- System.arraycopy(key_block, hash_size,
- server_mac_secret, 0, hash_size);
- System.arraycopy(key_block, 2*hash_size, client_key, 0, key_size);
- System.arraycopy(key_block, 2*hash_size+key_size,
- server_key, 0, key_size);
-
- IvParameterSpec clientIV = null;
- IvParameterSpec serverIV = null;
-
- if (is_exportabe) {
- System.arraycopy(clientRandom, 0,
- seed, 0, clientRandom.length);
- System.arraycopy(serverRandom, 0,
- seed, clientRandom.length, serverRandom.length);
- byte[] final_client_key =
- new byte[cipherSuite.expandedKeyMaterial];
- byte[] final_server_key =
- new byte[cipherSuite.expandedKeyMaterial];
- PRF.computePRF(final_client_key, client_key,
- CLIENT_WRITE_KEY_LABEL, seed);
- PRF.computePRF(final_server_key, server_key,
- SERVER_WRITE_KEY_LABEL, seed);
- client_key = final_client_key;
- server_key = final_server_key;
- if (is_block_cipher) {
- byte[] iv_block = new byte[2*iv_size];
- PRF.computePRF(iv_block, null, IV_BLOCK_LABEL, seed);
- clientIV = new IvParameterSpec(iv_block, 0, iv_size);
- serverIV = new IvParameterSpec(iv_block, iv_size, iv_size);
- }
- } else if (is_block_cipher) {
- clientIV = new IvParameterSpec(key_block,
- 2*(hash_size+key_size), iv_size);
- serverIV = new IvParameterSpec(key_block,
- 2*(hash_size+key_size)+iv_size, iv_size);
- }
-
- if (logger != null) {
- logger.println("is exportable: "+is_exportabe);
- logger.println("master_secret");
- logger.print(session.master_secret);
- logger.println("client_random");
- logger.print(clientRandom);
- logger.println("server_random");
- logger.print(serverRandom);
- //logger.println("key_block");
- //logger.print(key_block);
- logger.println("client_mac_secret");
- logger.print(client_mac_secret);
- logger.println("server_mac_secret");
- logger.print(server_mac_secret);
- logger.println("client_key");
- logger.print(client_key);
- logger.println("server_key");
- logger.print(server_key);
- if (clientIV == null) {
- logger.println("no IV.");
- } else {
- logger.println("client_iv");
- logger.print(clientIV.getIV());
- logger.println("server_iv");
- logger.print(serverIV.getIV());
- }
- }
-
- encCipher = Cipher.getInstance(algName);
- decCipher = Cipher.getInstance(algName);
- encMac = Mac.getInstance(macName);
- decMac = Mac.getInstance(macName);
-
- if (is_client) { // client side
- encCipher.init(Cipher.ENCRYPT_MODE,
- new SecretKeySpec(client_key, algName), clientIV);
- decCipher.init(Cipher.DECRYPT_MODE,
- new SecretKeySpec(server_key, algName), serverIV);
- encMac.init(new SecretKeySpec(client_mac_secret, macName));
- decMac.init(new SecretKeySpec(server_mac_secret, macName));
- } else { // server side
- encCipher.init(Cipher.ENCRYPT_MODE,
- new SecretKeySpec(server_key, algName), serverIV);
- decCipher.init(Cipher.DECRYPT_MODE,
- new SecretKeySpec(client_key, algName), clientIV);
- encMac.init(new SecretKeySpec(server_mac_secret, macName));
- decMac.init(new SecretKeySpec(client_mac_secret, macName));
- }
- } catch (Exception e) {
- e.printStackTrace();
- throw new AlertException(AlertProtocol.INTERNAL_ERROR,
- new SSLProtocolException(
- "Error during computation of security parameters"));
- }
- }
-
- /**
- * Creates the GenericStreamCipher or GenericBlockCipher
- * data structure for specified data of specified type.
- * @throws AlertException if alert was occurred.
- */
- @Override
- protected byte[] encrypt(byte type, byte[] fragment, int offset, int len) {
- try {
- int content_mac_length = len + hash_size;
- int padding_length = is_block_cipher
- ? ((8 - (++content_mac_length & 0x07)) & 0x07)
- : 0;
- byte[] res = new byte[content_mac_length + padding_length];
- System.arraycopy(fragment, offset, res, 0, len);
-
- mac_material_header[0] = type;
- mac_material_header[3] = (byte) ((0x00FF00 & len) >> 8);
- mac_material_header[4] = (byte) (0x0000FF & len);
-
- encMac.update(write_seq_num);
- encMac.update(mac_material_header);
- encMac.update(fragment, offset, len);
- encMac.doFinal(res, len);
-
- //if (logger != null) {
- // logger.println("MAC Material:");
- // logger.print(write_seq_num);
- // logger.print(mac_material_header);
- // logger.print(fragment, offset, len);
- //}
-
- if (is_block_cipher) {
- // do padding:
- Arrays.fill(res, content_mac_length-1,
- res.length, (byte) (padding_length));
- }
- if (logger != null) {
- logger.println("SSLRecordProtocol.do_encryption: Generic"
- + (is_block_cipher
- ? "BlockCipher with padding["+padding_length+"]:"
- : "StreamCipher:"));
- logger.print(res);
- }
- byte[] rez = new byte[encCipher.getOutputSize(res.length)];
- // We should not call just doFinal because it reinitialize
- // the cipher, but as says rfc 2246:
- // "For stream ciphers that do not use a synchronization
- // vector (such as RC4), the stream cipher state from the end
- // of one record is simply used on the subsequent packet."
- // and for block ciphers:
- // "The IV for subsequent records is the last ciphertext block from
- // the previous record."
- // i.e. we should keep the cipher state.
- encCipher.update(res, 0, res.length, rez);
- incSequenceNumber(write_seq_num);
- return rez;
- } catch (GeneralSecurityException e) {
- e.printStackTrace();
- throw new AlertException(AlertProtocol.INTERNAL_ERROR,
- new SSLProtocolException("Error during the encryption"));
- }
- }
-
- /**
- * Retrieves the fragment of the Plaintext structure of
- * the specified type from the provided data representing
- * the Generic[Stream|Block]Cipher structure.
- * @throws AlertException if alert was occurred.
- */
- @Override
- protected byte[] decrypt(byte type, byte[] fragment,
- int offset, int len) {
- // plain data of the Generic[Stream|Block]Cipher structure
- byte[] data = decCipher.update(fragment, offset, len);
- // the 'content' part of the structure
- byte[] content;
- if (is_block_cipher) {
- // check padding
- int padding_length = data[data.length-1];
- for (int i=0; i<padding_length; i++) {
- if (data[data.length-2-i] != padding_length) {
- throw new AlertException(
- AlertProtocol.DECRYPTION_FAILED,
- new SSLProtocolException(
- "Received message has bad padding"));
- }
- }
- content = new byte[data.length - hash_size - padding_length - 1];
- } else {
- content = new byte[data.length - hash_size];
- }
-
- mac_material_header[0] = type;
- mac_material_header[3] = (byte) ((0x00FF00 & content.length) >> 8);
- mac_material_header[4] = (byte) (0x0000FF & content.length);
-
- decMac.update(read_seq_num);
- decMac.update(mac_material_header);
- decMac.update(data, 0, content.length); // mac.update(fragment);
- byte[] mac_value = decMac.doFinal();
- if (logger != null) {
- logger.println("Decrypted:");
- logger.print(data);
- //logger.println("MAC Material:");
- //logger.print(read_seq_num);
- //logger.print(mac_material_header);
- //logger.print(data, 0, content.length);
- logger.println("Expected mac value:");
- logger.print(mac_value);
- }
- // checking the mac value
- for (int i=0; i<hash_size; i++) {
- if (mac_value[i] != data[i+content.length]) {
- throw new AlertException(AlertProtocol.BAD_RECORD_MAC,
- new SSLProtocolException("Bad record MAC"));
- }
- }
- System.arraycopy(data, 0, content, 0, content.length);
- incSequenceNumber(read_seq_num);
- return content;
- }
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ContentType.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ContentType.java
deleted file mode 100644
index 69704f5..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ContentType.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-/**
- * This class incapsulates the constants determining the
- * types of SSL/TLS record's content data.
- * Constant values are taken according to the TLS v1 specification
- * (http://www.ietf.org/rfc/rfc2246.txt).
- */
-public class ContentType {
-
- /**
- * Identifies change cipher spec message
- */
- protected static final byte CHANGE_CIPHER_SPEC = 20;
-
- /**
- * Identifies alert message
- */
- protected static final byte ALERT = 21;
-
- /**
- * Identifies handshake message
- */
- protected static final byte HANDSHAKE = 22;
-
- /**
- * Identifies application data message
- */
- protected static final byte APPLICATION_DATA = 23;
-
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DHParameters.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DHParameters.java
deleted file mode 100644
index 441fc5f..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DHParameters.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.harmony.xnet.provider.jsse;
-
-/**
- * This class contains well-known primes
- */
-public class DHParameters {
-
- // Well-known 512 bit prime
- // http://news.hping.org/sci.crypt.archive/2370.html
- private static byte[] prime512 = new byte[] { (byte) 0xF5, (byte) 0x2A, (byte) 0xFF,
- (byte) 0x3C, (byte) 0xE1, (byte) 0xB1, (byte) 0x29, (byte) 0x40,
- (byte) 0x18, (byte) 0x11, (byte) 0x8D, (byte) 0x7C, (byte) 0x84,
- (byte) 0xA7, (byte) 0x0A, (byte) 0x72, (byte) 0xD6, (byte) 0x86,
- (byte) 0xC4, (byte) 0x03, (byte) 0x19, (byte) 0xC8, (byte) 0x07,
- (byte) 0x29, (byte) 0x7A, (byte) 0xCA, (byte) 0x95, (byte) 0x0C,
- (byte) 0xD9, (byte) 0x96, (byte) 0x9F, (byte) 0xAB, (byte) 0xD0,
- (byte) 0x0A, (byte) 0x50, (byte) 0x9B, (byte) 0x02, (byte) 0x46,
- (byte) 0xD3, (byte) 0x08, (byte) 0x3D, (byte) 0x66, (byte) 0xA4,
- (byte) 0x5D, (byte) 0x41, (byte) 0x9F, (byte) 0x9C, (byte) 0x7C,
- (byte) 0xBD, (byte) 0x89, (byte) 0x4B, (byte) 0x22, (byte) 0x19,
- (byte) 0x26, (byte) 0xBA, (byte) 0xAB, (byte) 0xA2, (byte) 0x5E,
- (byte) 0xC3, (byte) 0x55, (byte) 0xE9, (byte) 0x2A, (byte) 0x05,
- (byte) 0x5F };
-
- // Well-Known Group 1: A 768 bit prime rfc 2539
- // (http://www.ietf.org/rfc/rfc2539.txt?number=2539)
- private static byte[] primeGroup1 = { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
- (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xC9,
- (byte) 0x0F, (byte) 0xDA, (byte) 0xA2, (byte) 0x21, (byte) 0x68,
- (byte) 0xC2, (byte) 0x34, (byte) 0xC4, (byte) 0xC6, (byte) 0x62,
- (byte) 0x8B, (byte) 0x80, (byte) 0xDC, (byte) 0x1C, (byte) 0xD1,
- (byte) 0x29, (byte) 0x02, (byte) 0x4E, (byte) 0x08, (byte) 0x8A,
- (byte) 0x67, (byte) 0xCC, (byte) 0x74, (byte) 0x02, (byte) 0x0B,
- (byte) 0xBE, (byte) 0xA6, (byte) 0x3B, (byte) 0x13, (byte) 0x9B,
- (byte) 0x22, (byte) 0x51, (byte) 0x4A, (byte) 0x08, (byte) 0x79,
- (byte) 0x8E, (byte) 0x34, (byte) 0x04, (byte) 0xDD, (byte) 0xEF,
- (byte) 0x95, (byte) 0x19, (byte) 0xB3, (byte) 0xCD, (byte) 0x3A,
- (byte) 0x43, (byte) 0x1B, (byte) 0x30, (byte) 0x2B, (byte) 0x0A,
- (byte) 0x6D, (byte) 0xF2, (byte) 0x5F, (byte) 0x14, (byte) 0x37,
- (byte) 0x4F, (byte) 0xE1, (byte) 0x35, (byte) 0x6D, (byte) 0x6D,
- (byte) 0x51, (byte) 0xC2, (byte) 0x45, (byte) 0xE4, (byte) 0x85,
- (byte) 0xB5, (byte) 0x76, (byte) 0x62, (byte) 0x5E, (byte) 0x7E,
- (byte) 0xC6, (byte) 0xF4, (byte) 0x4C, (byte) 0x42, (byte) 0xE9,
- (byte) 0xA6, (byte) 0x3A, (byte) 0x36, (byte) 0x20, (byte) 0xFF,
- (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
- (byte) 0xFF, (byte) 0xFF };
-
- // Well-Known Group 2: A 1024 bit prime rfc 2539
- // (http://www.ietf.org/rfc/rfc2539.txt?number=2539)
- private static byte[] primeGroup2 = { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
- (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xC9,
- (byte) 0x0F, (byte) 0xDA, (byte) 0xA2, (byte) 0x21, (byte) 0x68,
- (byte) 0xC2, (byte) 0x34, (byte) 0xC4, (byte) 0xC6, (byte) 0x62,
- (byte) 0x8B, (byte) 0x80, (byte) 0xDC, (byte) 0x1C, (byte) 0xD1,
- (byte) 0x29, (byte) 0x02, (byte) 0x4E, (byte) 0x08, (byte) 0x8A,
- (byte) 0x67, (byte) 0xCC, (byte) 0x74, (byte) 0x02, (byte) 0x0B,
- (byte) 0xBE, (byte) 0xA6, (byte) 0x3B, (byte) 0x13, (byte) 0x9B,
- (byte) 0x22, (byte) 0x51, (byte) 0x4A, (byte) 0x08, (byte) 0x79,
- (byte) 0x8E, (byte) 0x34, (byte) 0x04, (byte) 0xDD, (byte) 0xEF,
- (byte) 0x95, (byte) 0x19, (byte) 0xB3, (byte) 0xCD, (byte) 0x3A,
- (byte) 0x43, (byte) 0x1B, (byte) 0x30, (byte) 0x2B, (byte) 0x0A,
- (byte) 0x6D, (byte) 0xF2, (byte) 0x5F, (byte) 0x14, (byte) 0x37,
- (byte) 0x4F, (byte) 0xE1, (byte) 0x35, (byte) 0x6D, (byte) 0x6D,
- (byte) 0x51, (byte) 0xC2, (byte) 0x45, (byte) 0xE4, (byte) 0x85,
- (byte) 0xB5, (byte) 0x76, (byte) 0x62, (byte) 0x5E, (byte) 0x7E,
- (byte) 0xC6, (byte) 0xF4, (byte) 0x4C, (byte) 0x42, (byte) 0xE9,
- (byte) 0xA6, (byte) 0x37, (byte) 0xED, (byte) 0x6B, (byte) 0x0B,
- (byte) 0xFF, (byte) 0x5C, (byte) 0xB6, (byte) 0xF4, (byte) 0x06,
- (byte) 0xB7, (byte) 0xED, (byte) 0xEE, (byte) 0x38, (byte) 0x6B,
- (byte) 0xFB, (byte) 0x5A, (byte) 0x89, (byte) 0x9F, (byte) 0xA5,
- (byte) 0xAE, (byte) 0x9F, (byte) 0x24, (byte) 0x11, (byte) 0x7C,
- (byte) 0x4B, (byte) 0x1F, (byte) 0xE6, (byte) 0x49, (byte) 0x28,
- (byte) 0x66, (byte) 0x51, (byte) 0xEC, (byte) 0xE6, (byte) 0x53,
- (byte) 0x81, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
- (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF
- };
-
- private static byte[] prime;
-
- static {
-//TODO set prime depand on some system or security property
- prime = prime512;
- }
-
- /**
- * Returns prime bytes
- * @return
- */
- public static byte[] getPrime() {
- return prime;
- }
-} \ No newline at end of file
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DataStream.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DataStream.java
deleted file mode 100644
index ffc8612..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DataStream.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-/**
- * This interface represents the ability of the
- * classes to provide the chunks of data.
- */
-public interface DataStream {
-
- /**
- * Checks if there is data to be read.
- * @return true if there is the input data in the stream,
- * false otherwise
- */
- public boolean hasData();
-
- /**
- * Retrieves the data of specified length from the stream.
- * If the data size in the stream is less than specified length,
- * method returns all the data contained in the stream.
- * @return byte array containing the demanded data.
- */
- public byte[] getData(int length);
-
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DelegatedTask.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DelegatedTask.java
deleted file mode 100644
index 3b2e103..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DelegatedTask.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.HandshakeProtocol;
-
-import java.security.AccessControlContext;
-import java.security.AccessController;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-
-/**
- * Delegated Runnable task for SSLEngine
- */
-public class DelegatedTask implements Runnable {
-
- private final HandshakeProtocol handshaker;
- private final PrivilegedExceptionAction<Void> action;
- private final AccessControlContext context;
-
- /**
- * Creates DelegatedTask
- * @param action
- * @param handshaker
- * @param context
- */
- public DelegatedTask(PrivilegedExceptionAction<Void> action, HandshakeProtocol handshaker, AccessControlContext context) {
- this.action = action;
- this.handshaker = handshaker;
- this.context = context;
- }
-
- /**
- * Executes DelegatedTask
- */
- public void run() {
- synchronized (handshaker) {
- try {
- AccessController.doPrivileged(action, context);
- } catch (PrivilegedActionException e) {
- // pass exception to HandshakeProtocol
- handshaker.delegatedTaskErr = e.getException();
- } catch (RuntimeException e) {
- // pass exception to HandshakeProtocol
- handshaker.delegatedTaskErr = e;
- }
- }
-
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DigitalSignature.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DigitalSignature.java
deleted file mode 100644
index a0f18b4..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DigitalSignature.java
+++ /dev/null
@@ -1,254 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.security.DigestException;
-import java.security.InvalidKeyException;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.security.PrivateKey;
-import java.security.Signature;
-import java.security.SignatureException;
-import java.security.cert.Certificate;
-import java.util.Arrays;
-
-import javax.crypto.BadPaddingException;
-import javax.crypto.Cipher;
-import javax.crypto.IllegalBlockSizeException;
-import javax.crypto.NoSuchPaddingException;
-import javax.net.ssl.SSLException;
-
-/**
- * This class represents Signature type, as described in TLS v 1.0 Protocol
- * specification, 7.4.3. It allow to init, update and sign hash. Hash algorithm
- * depends on SignatureAlgorithm.
- *
- * select (SignatureAlgorithm)
- * { case anonymous: struct { };
- * case rsa:
- * digitally-signed struct {
- * opaque md5_hash[16];
- * opaque sha_hash[20];
- * };
- * case dsa:
- * digitally-signed struct {
- * opaque sha_hash[20];
- * };
- * } Signature;
- *
- * Digital signing description see in TLS spec., 4.7.
- * (http://www.ietf.org/rfc/rfc2246.txt)
- *
- */
-public class DigitalSignature {
-
- private final MessageDigest md5;
- private final MessageDigest sha;
- private final Signature signature;
- private final Cipher cipher;
-
- private byte[] md5_hash;
- private byte[] sha_hash;
-
- /**
- * Create Signature type
- * @param keyExchange
- */
- public DigitalSignature(int keyExchange) {
- try {
- sha = MessageDigest.getInstance("SHA-1");
-
- if (keyExchange == CipherSuite.KeyExchange_RSA_EXPORT ||
- keyExchange == CipherSuite.KeyExchange_RSA ||
- keyExchange == CipherSuite.KeyExchange_DHE_RSA ||
- keyExchange == CipherSuite.KeyExchange_DHE_RSA_EXPORT) {
- // SignatureAlgorithm is rsa
- md5 = MessageDigest.getInstance("MD5");
- cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
- signature = null;
- } else if (keyExchange == CipherSuite.KeyExchange_DHE_DSS ||
- keyExchange == CipherSuite.KeyExchange_DHE_DSS_EXPORT ) {
- // SignatureAlgorithm is dsa
- signature = Signature.getInstance("NONEwithDSA");
- cipher = null;
- md5 = null;
- } else {
- cipher = null;
- signature = null;
- md5 = null;
- }
- } catch (NoSuchAlgorithmException e) {
- // this should never happen
- throw new AssertionError(e);
- } catch (NoSuchPaddingException e) {
- // this should never happen
- throw new AssertionError(e);
- }
- }
-
- /**
- * Initiate Signature type by private key
- * @param key
- */
- public void init(PrivateKey key) {
- try {
- if (signature != null) {
- signature.initSign(key);
- } else if (cipher != null) {
- cipher.init(Cipher.ENCRYPT_MODE, key);
- }
- } catch (InvalidKeyException e){
- throw new AlertException(AlertProtocol.BAD_CERTIFICATE,
- new SSLException("init - invalid private key", e));
- }
- }
-
- /**
- * Initiate Signature type by certificate
- * @param cert
- */
- public void init(Certificate cert) {
- try {
- if (signature != null) {
- signature.initVerify(cert);
- } else if (cipher != null) {
- cipher.init(Cipher.DECRYPT_MODE, cert);
- }
- } catch (InvalidKeyException e){
- throw new AlertException(AlertProtocol.BAD_CERTIFICATE,
- new SSLException("init - invalid certificate", e));
- }
- }
-
- /**
- * Update Signature hash
- * @param data
- */
- public void update(byte[] data) {
- if (sha != null) {
- sha.update(data);
- }
- if (md5 != null) {
- md5.update(data);
- }
- }
-
- /**
- * Sets MD5 hash
- * @param data
- */
- public void setMD5(byte[] data) {
- md5_hash = data;
- }
-
- /**
- * Sets SHA hash
- * @param data
- */
- public void setSHA(byte[] data) {
- sha_hash = data;
- }
-
- /**
- * Sign hash
- * @return Signature bytes
- */
- public byte[] sign() {
- try {
- if (md5 != null && md5_hash == null) {
- md5_hash = new byte[16];
- md5.digest(md5_hash, 0, md5_hash.length);
- }
- if (md5_hash != null) {
- if (signature != null) {
- signature.update(md5_hash);
- } else if (cipher != null) {
- cipher.update(md5_hash);
- }
- }
- if (sha != null && sha_hash == null) {
- sha_hash = new byte[20];
- sha.digest(sha_hash, 0, sha_hash.length);
- }
- if (sha_hash != null) {
- if (signature != null) {
- signature.update(sha_hash);
- } else if (cipher != null) {
- cipher.update(sha_hash);
- }
- }
- if (signature != null) {
- return signature.sign();
- } else if (cipher != null) {
- return cipher.doFinal();
- }
- return new byte[0];
- } catch (DigestException e){
- return new byte[0];
- } catch (SignatureException e){
- return new byte[0];
- } catch (BadPaddingException e){
- return new byte[0];
- } catch (IllegalBlockSizeException e){
- return new byte[0];
- }
- }
-
- /**
- * Verifies the signature data.
- * @param data - the signature bytes
- * @return true if verified
- */
- public boolean verifySignature(byte[] data) {
- if (signature != null) {
- try {
- return signature.verify(data);
- } catch (SignatureException e) {
- return false;
- }
- }
-
- if (cipher != null) {
- final byte[] decrypt;
- try {
- decrypt = cipher.doFinal(data);
- } catch (IllegalBlockSizeException e) {
- return false;
- } catch (BadPaddingException e) {
- return false;
- }
-
- final byte[] md5_sha;
- if (md5_hash != null && sha_hash != null) {
- md5_sha = new byte[md5_hash.length + sha_hash.length];
- System.arraycopy(md5_hash, 0, md5_sha, 0, md5_hash.length);
- System.arraycopy(sha_hash, 0, md5_sha, md5_hash.length, sha_hash.length);
- } else if (md5_hash != null) {
- md5_sha = md5_hash;
- } else {
- md5_sha = sha_hash;
- }
-
- return Arrays.equals(decrypt, md5_sha);
- } else if (data == null || data.length == 0) {
- return true;
- } else {
- return false;
- }
- }
-
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/EndOfBufferException.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/EndOfBufferException.java
deleted file mode 100644
index 1dcdd20..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/EndOfBufferException.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.IOException;
-
-/**
- * This exception indicates that data could not be read from the stream because the underlying input
- * stream reached its end.
- */
-public class EndOfBufferException extends IOException {
-
- private static final long serialVersionUID = 1838636631255369519L;
-
- public EndOfBufferException() {
- super();
- }
-
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/EndOfSourceException.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/EndOfSourceException.java
deleted file mode 100644
index 631679a..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/EndOfSourceException.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.IOException;
-
-/**
- * This exception indicates that data could not be read from the buffered stream because underlying
- * data buffer was exhausted.
- */
-public class EndOfSourceException extends IOException {
-
- private static final long serialVersionUID = -4673611435974054413L;
-
- public EndOfSourceException() {
- super();
- }
-
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/FileClientSessionCache.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/FileClientSessionCache.java
deleted file mode 100644
index d438779..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/FileClientSessionCache.java
+++ /dev/null
@@ -1,374 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import javax.net.ssl.SSLSession;
-import java.util.Map;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.Set;
-import java.util.TreeSet;
-import java.util.Iterator;
-import java.util.Arrays;
-import java.util.logging.Level;
-import java.io.DataInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-
-/**
- * File-based cache implementation. Only one process should access the
- * underlying directory at a time.
- */
-public class FileClientSessionCache {
-
- static final int MAX_SIZE = 12; // ~72k
-
- static final java.util.logging.Logger logger
- = java.util.logging.Logger.getLogger(
- FileClientSessionCache.class.getName());
-
- private FileClientSessionCache() {}
-
- /**
- * This cache creates one file per SSL session using "host.port" for
- * the file name. Files are created or replaced when session data is put
- * in the cache (see {@link #putSessionData}). Files are read on
- * cache hits, but not on cache misses.
- *
- * <p>When the number of session files exceeds MAX_SIZE, we delete the
- * least-recently-used file. We don't current persist the last access time,
- * so the ordering actually ends up being least-recently-modified in some
- * cases and even just "not accessed in this process" if the filesystem
- * doesn't track last modified times.
- */
- static class Impl implements SSLClientSessionCache {
-
- /** Directory to store session files in. */
- final File directory;
-
- /**
- * Map of name -> File. Keeps track of the order files were accessed in.
- */
- Map<String, File> accessOrder = newAccessOrder();
-
- /** The number of files on disk. */
- int size;
-
- /**
- * The initial set of files. We use this to defer adding information
- * about all files to accessOrder until necessary.
- */
- String[] initialFiles;
-
- /**
- * Constructs a new cache backed by the given directory.
- */
- Impl(File directory) throws IOException {
- boolean exists = directory.exists();
- if (exists && !directory.isDirectory()) {
- throw new IOException(directory
- + " exists but is not a directory.");
- }
-
- if (exists) {
- // Read and sort initial list of files. We defer adding
- // information about these files to accessOrder until necessary
- // (see indexFiles()). Sorting the list enables us to detect
- // cache misses in getSessionData().
- // Note: Sorting an array here was faster than creating a
- // HashSet on Dalvik.
- initialFiles = directory.list();
- Arrays.sort(initialFiles);
- size = initialFiles.length;
- } else {
- // Create directory.
- if (!directory.mkdirs()) {
- throw new IOException("Creation of " + directory
- + " directory failed.");
- }
- size = 0;
- }
-
- this.directory = directory;
- }
-
- /**
- * Creates a new access-ordered linked hash map.
- */
- private static Map<String, File> newAccessOrder() {
- return new LinkedHashMap<String, File>(
- MAX_SIZE, 0.75f, true /* access order */);
- }
-
- /**
- * Gets the file name for the given host and port.
- */
- private static String fileName(String host, int port) {
- if (host == null) {
- throw new NullPointerException("host");
- }
- return host + "." + port;
- }
-
- public synchronized byte[] getSessionData(String host, int port) {
- /*
- * Note: This method is only called when the in-memory cache
- * in SSLSessionContext misses, so it would be unnecesarily
- * rendundant for this cache to store data in memory.
- */
-
- String name = fileName(host, port);
- File file = accessOrder.get(name);
-
- if (file == null) {
- // File wasn't in access order. Check initialFiles...
- if (initialFiles == null) {
- // All files are in accessOrder, so it doesn't exist.
- return null;
- }
-
- // Look in initialFiles.
- if (Arrays.binarySearch(initialFiles, name) < 0) {
- // Not found.
- return null;
- }
-
- // The file is on disk but not in accessOrder yet.
- file = new File(directory, name);
- accessOrder.put(name, file);
- }
-
- FileInputStream in;
- try {
- in = new FileInputStream(file);
- } catch (FileNotFoundException e) {
- logReadError(host, e);
- return null;
- }
- try {
- int size = (int) file.length();
- byte[] data = new byte[size];
- new DataInputStream(in).readFully(data);
- logger.log(Level.FINE, "Read session for " + host + ".");
- return data;
- } catch (IOException e) {
- logReadError(host, e);
- return null;
- } finally {
- try {
- in.close();
- } catch (IOException e) { /* ignore */ }
- }
- }
-
- static void logReadError(String host, Throwable t) {
- logger.log(Level.INFO, "Error reading session data for " + host
- + ".", t);
- }
-
- public synchronized void putSessionData(SSLSession session,
- byte[] sessionData) {
- String host = session.getPeerHost();
- if (sessionData == null) {
- throw new NullPointerException("sessionData");
- }
-
- String name = fileName(host, session.getPeerPort());
- File file = new File(directory, name);
-
- // Used to keep track of whether or not we're expanding the cache.
- boolean existedBefore = file.exists();
-
- FileOutputStream out;
- try {
- out = new FileOutputStream(file);
- } catch (FileNotFoundException e) {
- // We can't write to the file.
- logWriteError(host, e);
- return;
- }
-
- // If we expanded the cache (by creating a new file)...
- if (!existedBefore) {
- size++;
-
- // Delete an old file if necessary.
- makeRoom();
- }
-
- boolean writeSuccessful = false;
- try {
- out.write(sessionData);
- writeSuccessful = true;
- } catch (IOException e) {
- logWriteError(host, e);
- } finally {
- boolean closeSuccessful = false;
- try {
- out.close();
- closeSuccessful = true;
- } catch (IOException e) {
- logWriteError(host, e);
- } finally {
- if (!writeSuccessful || !closeSuccessful) {
- // Storage failed. Clean up.
- delete(file);
- } else {
- // Success!
- accessOrder.put(name, file);
- logger.log(Level.FINE, "Stored session for " + host
- + ".");
- }
- }
- }
- }
-
- /**
- * Deletes old files if necessary.
- */
- private void makeRoom() {
- if (size <= MAX_SIZE) {
- return;
- }
-
- indexFiles();
-
- // Delete LRUed files.
- int removals = size - MAX_SIZE;
- Iterator<File> i = accessOrder.values().iterator();
- do {
- delete(i.next());
- i.remove();
- } while (--removals > 0);
- }
-
- /**
- * Lazily updates accessOrder to know about all files as opposed to
- * just the files accessed since this process started.
- */
- private void indexFiles() {
- String[] initialFiles = this.initialFiles;
- if (initialFiles != null) {
- this.initialFiles = null;
-
- // Files on disk only, sorted by last modified time.
- // TODO: Use last access time.
- Set<CacheFile> diskOnly = new TreeSet<CacheFile>();
- for (String name : initialFiles) {
- // If the file hasn't been accessed in this process...
- if (!accessOrder.containsKey(name)) {
- diskOnly.add(new CacheFile(directory, name));
- }
- }
-
- if (!diskOnly.isEmpty()) {
- // Add files not accessed in this process to the beginning
- // of accessOrder.
- Map<String, File> newOrder = newAccessOrder();
- for (CacheFile cacheFile : diskOnly) {
- newOrder.put(cacheFile.name, cacheFile);
- }
- newOrder.putAll(accessOrder);
-
- this.accessOrder = newOrder;
- }
- }
- }
-
- @SuppressWarnings("ThrowableInstanceNeverThrown")
- private void delete(File file) {
- if (!file.delete()) {
- logger.log(Level.INFO, "Failed to delete " + file + ".",
- new IOException());
- }
- size--;
- }
-
- static void logWriteError(String host, Throwable t) {
- logger.log(Level.INFO, "Error writing session data for "
- + host + ".", t);
- }
- }
-
- /**
- * Maps directories to the cache instances that are backed by those
- * directories. We synchronize access using the cache instance, so it's
- * important that everyone shares the same instance.
- */
- static final Map<File, FileClientSessionCache.Impl> caches
- = new HashMap<File, FileClientSessionCache.Impl>();
-
- /**
- * Returns a cache backed by the given directory. Creates the directory
- * (including parent directories) if necessary. This cache should have
- * exclusive access to the given directory.
- *
- * @param directory to store files in
- * @return a cache backed by the given directory
- * @throws IOException if the file exists and is not a directory or if
- * creating the directories fails
- */
- public static synchronized SSLClientSessionCache usingDirectory(
- File directory) throws IOException {
- FileClientSessionCache.Impl cache = caches.get(directory);
- if (cache == null) {
- cache = new FileClientSessionCache.Impl(directory);
- caches.put(directory, cache);
- }
- return cache;
- }
-
- /** For testing. */
- static synchronized void reset() {
- caches.clear();
- }
-
- /** A file containing a piece of cached data. */
- static class CacheFile extends File {
-
- final String name;
-
- CacheFile(File dir, String name) {
- super(dir, name);
- this.name = name;
- }
-
- long lastModified = -1;
-
- @Override
- public long lastModified() {
- long lastModified = this.lastModified;
- if (lastModified == -1) {
- lastModified = this.lastModified = super.lastModified();
- }
- return lastModified;
- }
-
- @Override
- public int compareTo(File another) {
- // Sort by last modified time.
- long result = lastModified() - another.lastModified();
- if (result == 0) {
- return super.compareTo(another);
- }
- return result < 0 ? -1 : 1;
- }
- }
-} \ No newline at end of file
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Finished.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Finished.java
deleted file mode 100644
index 6b555c6..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Finished.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.Message;
-
-import java.io.IOException;
-
-/**
- *
- * Represents Finished message
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7.4.9.
- * Finished</a>
- *
- */
-public class Finished extends Message {
-
- // verify data
- private byte[] data;
-
- /**
- * Creates outbound message
- * @param bytes
- */
- public Finished(byte[] bytes) {
- data = bytes;
- length = data.length;
- }
-
- /**
- * Creates inbound message
- * @param in
- * @param length
- * @throws IOException
- */
- public Finished(HandshakeIODataStream in, int length)
- throws IOException {
- if (length == 12 || length == 36) {
- data = in.read(length);
- length = data.length;
- } else {
- fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR: incorrect Finished");
- }
- }
-
- @Override
- public void send(HandshakeIODataStream out) {
- out.write(data);
- }
-
- /**
- * Returns message type
- * @return
- */
- @Override
- public int getType() {
- return Handshake.FINISHED;
- }
-
- /**
- * Returns verify data
- * @return
- */
- public byte[] getData() {
- return data;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Handshake.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Handshake.java
deleted file mode 100644
index 64e73dd..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Handshake.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-/**
- *
- * This class incapsulates the constants determining the types of handshake
- * messages as defined in TLS 1.0 spec., 7.4. Handshake protocol.
- * (http://www.ietf.org/rfc/rfc2246.txt)
- *
- */
-public class Handshake {
-
- /**
- *
- * hello_request handshake type
- */
- public static final byte HELLO_REQUEST = 0;
-
- /**
- *
- * client_hello handshake type
- */
- public static final byte CLIENT_HELLO = 1;
-
- /**
- *
- * server_hello handshake type
- */
- public static final byte SERVER_HELLO = 2;
-
- /**
- *
- * certificate handshake type
- */
- public static final byte CERTIFICATE = 11;
-
- /**
- *
- * server_key_exchange handshake type
- */
- public static final byte SERVER_KEY_EXCHANGE = 12;
-
- /**
- *
- * certificate_request handshake type
- */
- public static final byte CERTIFICATE_REQUEST = 13;
-
- /**
- *
- * server_hello_done handshake type
- */
- public static final byte SERVER_HELLO_DONE = 14;
-
- /**
- *
- * certificate_verify handshake type
- */
- public static final byte CERTIFICATE_VERIFY = 15;
-
- /**
- *
- * client_key_exchange handshake type
- */
- public static final byte CLIENT_KEY_EXCHANGE = 16;
-
- /**
- *
- * finished handshake type
- */
- public static final byte FINISHED = 20;
-
-} \ No newline at end of file
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/HandshakeIODataStream.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/HandshakeIODataStream.java
deleted file mode 100644
index 74cc27d..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/HandshakeIODataStream.java
+++ /dev/null
@@ -1,464 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.AlertException;
-import org.apache.harmony.xnet.provider.jsse.SSLInputStream;
-
-import java.io.IOException;
-import java.io.PrintStream;
-import java.security.MessageDigest;
-import java.util.Arrays;
-import javax.net.ssl.SSLHandshakeException;
-
-/**
- * This class provides Input/Output data functionality
- * for handshake layer. It provides read and write operations
- * and accumulates all sent/received handshake's data.
- * This class can be presented as a combination of 2 data pipes.
- * The first data pipe is a pipe of income data: append method
- * places the data at the beginning of the pipe, and read methods
- * consume the data from the pipe. The second pipe is an outcoming
- * data pipe: write operations plases the data into the pipe,
- * and getData methods consume the data.
- * It is important to note that work with pipe cound not be
- * started if there is unconsumed data in another pipe. It is
- * reasoned by the following: handshake protocol performs read
- * and write operations consecuently. I.e. it first reads all
- * income data and only than produces the responce and places it
- * into the stream.
- * The read operations of the stream presented by the methods
- * of SSLInputStream which in its turn is an extension of InputStream.
- * So this stream can be used as an InputStream parameter for
- * certificate generation.
- * Also input stream functionality supports marks. The marks
- * help to reset the position of the stream in case of incompleate
- * handshake records. Note that in case of exhausting
- * of income data the EndOfBufferException is thown which implies
- * the following:
- * 1. the stream contains scrappy handshake record,
- * 2. the read position should be reseted to marked,
- * 3. and more income data is expected.
- * The throwing of the exception (instead of returning of -1 value
- * or incompleate filling of destination buffer)
- * helps to speed up the process of scrappy data recognition and
- * processing.
- * For more information about TLS handshake process see
- * TLS v 1 specification at http://www.ietf.org/rfc/rfc2246.txt.
- */
-public class HandshakeIODataStream
- extends SSLInputStream implements org.apache.harmony.xnet.provider.jsse.Appendable, DataStream {
-
- // Objects are used to compute digests of data passed
- // during the handshake phase
- private static final MessageDigest md5;
- private static final MessageDigest sha;
-
- static {
- try {
- md5 = MessageDigest.getInstance("MD5");
- sha = MessageDigest.getInstance("SHA-1");
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException(
- "Could not initialize the Digest Algorithms.");
- }
- }
-
- public HandshakeIODataStream() {}
-
- // buffer is used to keep the handshaking data;
- private int buff_size = 1024;
- private int inc_buff_size = 1024;
- private byte[] buffer = new byte[buff_size];
-
-
- // ---------------- Input related functionality -----------------
-
- // position of the next byte to read
- private int read_pos;
- private int marked_pos;
- // position of the last byte to read + 1
- private int read_pos_end;
-
- @Override
- public int available() {
- return read_pos_end - read_pos;
- }
-
- @Override
- public boolean markSupported() {
- return true;
- }
-
- @Override
- public void mark(int limit) {
- marked_pos = read_pos;
- }
-
- public void mark() {
- marked_pos = read_pos;
- }
-
- @Override
- public void reset() {
- read_pos = marked_pos;
- }
-
- /**
- * Removes the data from the marked position to
- * the current read position. The method is usefull when it is needed
- * to delete one message from the internal buffer.
- */
- protected void removeFromMarkedPosition() {
- System.arraycopy(buffer, read_pos,
- buffer, marked_pos, read_pos_end - read_pos);
- read_pos_end -= (read_pos - marked_pos);
- read_pos = marked_pos;
- }
-
- /**
- * read an opaque value;
- * @param byte: byte
- * @return
- */
- @Override
- public int read() throws IOException {
- if (read_pos == read_pos_end) {
- //return -1;
- throw new EndOfBufferException();
- }
- return buffer[read_pos++] & 0xFF;
- }
-
- /**
- * reads vector of opaque values
- * @param new: long
- * @return
- */
- @Override
- public byte[] read(int length) throws IOException {
- if (length > available()) {
- throw new EndOfBufferException();
- }
- byte[] res = new byte[length];
- System.arraycopy(buffer, read_pos, res, 0, length);
- read_pos = read_pos + length;
- return res;
- }
-
- @Override
- public int read(byte[] dest, int offset, int length) throws IOException {
- if (length > available()) {
- throw new EndOfBufferException();
- }
- System.arraycopy(buffer, read_pos, dest, offset, length);
- read_pos = read_pos + length;
- return length;
- }
-
- // ------------------- Extending of the input data ---------------------
-
- /**
- * Appends the income data to be read by handshake protocol.
- * The attempts to overflow the buffer by means of this methods
- * seem to be futile because of:
- * 1. The SSL protocol specifies the maximum size of the record
- * and record protocol does not pass huge messages.
- * (see TLS v1 specification http://www.ietf.org/rfc/rfc2246.txt ,
- * p 6.2)
- * 2. After each call of this method, handshake protocol should
- * start (and starts) the operations on received data and recognize
- * the fake data if such was provided (to check the size of certificate
- * for example).
- */
- public void append(byte[] src) {
- append(src, 0, src.length);
- }
-
- private void append(byte[] src, int from, int length) {
- if (read_pos == read_pos_end) {
- // start reading state after writing
- if (write_pos_beg != write_pos) {
- // error: outboud handshake data was not sent,
- // but inbound handshake data has been received.
- throw new AlertException(
- AlertProtocol.UNEXPECTED_MESSAGE,
- new SSLHandshakeException(
- "Handshake message has been received before "
- + "the last oubound message had been sent."));
- }
- if (read_pos < write_pos) {
- read_pos = write_pos;
- read_pos_end = read_pos;
- }
- }
- if (read_pos_end + length > buff_size) {
- enlargeBuffer(read_pos_end+length-buff_size);
- }
- System.arraycopy(src, from, buffer, read_pos_end, length);
- read_pos_end += length;
- }
-
- private void enlargeBuffer(int size) {
- buff_size = (size < inc_buff_size)
- ? buff_size + inc_buff_size
- : buff_size + size;
- byte[] new_buff = new byte[buff_size];
- System.arraycopy(buffer, 0, new_buff, 0, buffer.length);
- buffer = new_buff;
- }
-
- protected void clearBuffer() {
- read_pos = 0;
- marked_pos = 0;
- read_pos_end = 0;
- write_pos = 0;
- write_pos_beg = 0;
- Arrays.fill(buffer, (byte) 0);
- }
-
- // ------------------- Output related functionality --------------------
-
- // position in the buffer available for write
- private int write_pos;
- // position in the buffer where the last write session has begun
- private int write_pos_beg;
-
- // checks if the data can be written in the buffer
- private void check(int length) {
- // (write_pos == write_pos_beg) iff:
- // 1. there were not write operations yet
- // 2. all written data was demanded by getData methods
- if (write_pos == write_pos_beg) {
- // just started to write after the reading
- if (read_pos != read_pos_end) {
- // error: attempt to write outbound data into the stream before
- // all the inbound handshake data had been read
- throw new AlertException(
- AlertProtocol.INTERNAL_ERROR,
- new SSLHandshakeException("Data was not fully read: "
- + read_pos + " " + read_pos_end));
- }
- // set up the write positions
- if (write_pos_beg < read_pos_end) {
- write_pos_beg = read_pos_end;
- write_pos = write_pos_beg;
- }
- }
- // if there is not enought free space in the buffer - enlarge it:
- if (write_pos + length >= buff_size) {
- enlargeBuffer(length);
- }
- }
-
- /**
- * Writes an opaque value
- * @param byte: byte
- */
- public void write(byte b) {
- check(1);
- buffer[write_pos++] = b;
- }
-
- /**
- * Writes Uint8 value
- * @param long: the value to be written (last byte)
- */
- public void writeUint8(long n) {
- check(1);
- buffer[write_pos++] = (byte) (n & 0x00ff);
- }
-
- /**
- * Writes Uint16 value
- * @param long: the value to be written (last 2 bytes)
- */
- public void writeUint16(long n) {
- check(2);
- buffer[write_pos++] = (byte) ((n & 0x00ff00) >> 8);
- buffer[write_pos++] = (byte) (n & 0x00ff);
- }
-
- /**
- * Writes Uint24 value
- * @param long: the value to be written (last 3 bytes)
- */
- public void writeUint24(long n) {
- check(3);
- buffer[write_pos++] = (byte) ((n & 0x00ff0000) >> 16);
- buffer[write_pos++] = (byte) ((n & 0x00ff00) >> 8);
- buffer[write_pos++] = (byte) (n & 0x00ff);
- }
-
- /**
- * Writes Uint32 value
- * @param long: the value to be written (last 4 bytes)
- */
- public void writeUint32(long n) {
- check(4);
- buffer[write_pos++] = (byte) ((n & 0x00ff000000) >> 24);
- buffer[write_pos++] = (byte) ((n & 0x00ff0000) >> 16);
- buffer[write_pos++] = (byte) ((n & 0x00ff00) >> 8);
- buffer[write_pos++] = (byte) (n & 0x00ff);
- }
-
- /**
- * Writes Uint64 value
- * @param long: the value to be written
- */
- public void writeUint64(long n) {
- check(8);
- buffer[write_pos++] = (byte) ((n & 0x00ff00000000000000L) >> 56);
- buffer[write_pos++] = (byte) ((n & 0x00ff000000000000L) >> 48);
- buffer[write_pos++] = (byte) ((n & 0x00ff0000000000L) >> 40);
- buffer[write_pos++] = (byte) ((n & 0x00ff00000000L) >> 32);
- buffer[write_pos++] = (byte) ((n & 0x00ff000000) >> 24);
- buffer[write_pos++] = (byte) ((n & 0x00ff0000) >> 16);
- buffer[write_pos++] = (byte) ((n & 0x00ff00) >> 8);
- buffer[write_pos++] = (byte) (n & 0x00ff);
- }
-
- /**
- * writes vector of opaque values
- * @param vector the vector to be written
- */
- public void write(byte[] vector) {
- check(vector.length);
- System.arraycopy(vector, 0, buffer, write_pos, vector.length);
- write_pos += vector.length;
- }
-
- // ------------------- Retrieve the written bytes ----------------------
-
- public boolean hasData() {
- return (write_pos > write_pos_beg);
- }
-
- /**
- * returns the chunk of stored data with the length no more than specified.
- * @param length: int
- * @return
- */
- public byte[] getData(int length) {
- byte[] res;
- if (write_pos - write_pos_beg < length) {
- res = new byte[write_pos - write_pos_beg];
- System.arraycopy(buffer, write_pos_beg,
- res, 0, write_pos-write_pos_beg);
- write_pos_beg = write_pos;
- } else {
- res = new byte[length];
- System.arraycopy(buffer, write_pos_beg, res, 0, length);
- write_pos_beg += length;
- }
- return res;
- }
-
- // ---------------------- Debud functionality -------------------------
-
- protected void printContent(PrintStream outstream) {
- int perLine = 20;
- String prefix = " ";
- String delimiter = "";
-
- for (int i=write_pos_beg; i<write_pos; i++) {
- String tail = Integer.toHexString(
- 0x00ff & buffer[i]).toUpperCase();
- if (tail.length() == 1) {
- tail = "0" + tail;
- }
- outstream.print(prefix + tail + delimiter);
-
- if (((i-write_pos_beg+1)%10) == 0) {
- outstream.print(" ");
- }
-
- if (((i-write_pos_beg+1)%perLine) == 0) {
- outstream.println();
- }
- }
- outstream.println();
- }
-
- // ---------------------- Message Digest Functionality ----------------
-
- /**
- * Returns the MD5 digest of the data passed throught the stream
- * @return MD5 digest
- */
- protected byte[] getDigestMD5() {
- synchronized (md5) {
- int len = (read_pos_end > write_pos)
- ? read_pos_end
- : write_pos;
- md5.update(buffer, 0, len);
- return md5.digest();
- }
- }
-
- /**
- * Returns the SHA-1 digest of the data passed throught the stream
- * @return SHA-1 digest
- */
- protected byte[] getDigestSHA() {
- synchronized (sha) {
- int len = (read_pos_end > write_pos)
- ? read_pos_end
- : write_pos;
- sha.update(buffer, 0, len);
- return sha.digest();
- }
- }
-
- /**
- * Returns the MD5 digest of the data passed throught the stream
- * except last message
- * @return MD5 digest
- */
- protected byte[] getDigestMD5withoutLast() {
- synchronized (md5) {
- md5.update(buffer, 0, marked_pos);
- return md5.digest();
- }
- }
-
- /**
- * Returns the SHA-1 digest of the data passed throught the stream
- * except last message
- * @return SHA-1 digest
- */
- protected byte[] getDigestSHAwithoutLast() {
- synchronized (sha) {
- sha.update(buffer, 0, marked_pos);
- return sha.digest();
- }
- }
-
- /**
- * Returns all the data passed throught the stream
- * @return all the data passed throught the stream at the moment
- */
- protected byte[] getMessages() {
- int len = (read_pos_end > write_pos) ? read_pos_end : write_pos;
- byte[] res = new byte[len];
- System.arraycopy(buffer, 0, res, 0, len);
- return res;
- }
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/HandshakeProtocol.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/HandshakeProtocol.java
deleted file mode 100644
index 6579398..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/HandshakeProtocol.java
+++ /dev/null
@@ -1,534 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.math.BigInteger;
-import java.security.GeneralSecurityException;
-import java.security.KeyFactory;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.security.PublicKey;
-import java.security.interfaces.RSAKey;
-import java.security.spec.InvalidKeySpecException;
-import java.security.spec.RSAPublicKeySpec;
-import java.util.Arrays;
-import java.util.Vector;
-
-import javax.net.ssl.SSLEngineResult;
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLHandshakeException;
-
-/**
- * Base class for ClientHandshakeImpl and ServerHandshakeImpl classes.
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7.4.
- * Handshake protocol</a>
- *
- */
-public abstract class HandshakeProtocol {
-
- /**
- * Handshake status NEED_UNWRAP - HandshakeProtocol needs to receive data
- */
- public final static int NEED_UNWRAP = 1;
-
- /**
- * Handshake status NOT_HANDSHAKING - is not currently handshaking
- */
- public final static int NOT_HANDSHAKING = 2;
-
- /**
- * Handshake status FINISHED - HandshakeProtocol has just finished
- */
- public final static int FINISHED = 3;
-
- /**
- * Handshake status NEED_TASK - HandshakeProtocol needs the results of delegated task
- */
- public final static int NEED_TASK = 4;
-
- /**
- * Current handshake status
- */
- protected int status = NOT_HANDSHAKING;
-
- /**
- * IO stream for income/outcome handshake data
- */
- protected HandshakeIODataStream io_stream = new HandshakeIODataStream();
-
- /**
- * SSL Record Protocol implementation.
- */
- protected SSLRecordProtocol recordProtocol;
-
- /**
- * SSLParameters suplied by SSLSocket or SSLEngine
- */
- protected SSLParameters parameters;
-
- /**
- * Delegated tasks for this handshake implementation
- */
- protected Vector<DelegatedTask> delegatedTasks = new Vector<DelegatedTask>();
-
- /**
- * Indicates non-blocking handshake
- */
- protected boolean nonBlocking;
-
- /**
- * Pending session
- */
- protected SSLSessionImpl session;
-
- /**
- * Sended and received handshake messages
- */
- protected ClientHello clientHello;
- protected ServerHello serverHello;
- protected CertificateMessage serverCert;
- protected ServerKeyExchange serverKeyExchange;
- protected CertificateRequest certificateRequest;
- protected ServerHelloDone serverHelloDone;
- protected CertificateMessage clientCert;
- protected ClientKeyExchange clientKeyExchange;
- protected CertificateVerify certificateVerify;
- protected Finished clientFinished;
- protected Finished serverFinished;
-
- /**
- * Indicates that change cipher spec message has been received
- */
- protected boolean changeCipherSpecReceived = false;
-
- /**
- * Indicates previous session resuming
- */
- protected boolean isResuming = false;
-
- /**
- * Premaster secret
- */
- protected byte[] preMasterSecret;
-
- /**
- * Exception occured in delegated task
- */
- protected Exception delegatedTaskErr;
-
- // reference verify_data used to verify finished message
- private byte[] verify_data = new byte[12];
-
- // Encoding of "master secret" string: "master secret".getBytes()
- private byte[] master_secret_bytes =
- {109, 97, 115, 116, 101, 114, 32, 115, 101, 99, 114, 101, 116 };
-
- // indicates whether protocol needs to send change cipher spec message
- private boolean needSendCCSpec = false;
-
- // indicates whether protocol needs to send change cipher spec message
- protected boolean needSendHelloRequest = false;
-
- /**
- * SSLEngine owning this HandshakeProtocol
- */
- public SSLEngineImpl engineOwner;
-
- /**
- * SSLSocket owning this HandshakeProtocol
- */
- // BEGIN android-removed
- // public SSLSocketImpl socketOwner;
- // END android-removed
-
- /**
- * Creates HandshakeProtocol instance
- * @param owner
- */
- protected HandshakeProtocol(Object owner) {
- if (owner instanceof SSLEngineImpl) {
- engineOwner = (SSLEngineImpl) owner;
- nonBlocking = true;
- this.parameters = engineOwner.sslParameters;
- }
- // BEGIN android-removed
- // else if (owner instanceof SSLSocketImpl) {
- // socketOwner = (SSLSocketImpl) owner;
- // nonBlocking = false;
- // this.parameters = socketOwner.sslParameters;
- // }
- // END android-removed
- }
-
- /**
- * Sets SSL Record Protocol
- * @param recordProtocol
- */
- public void setRecordProtocol(SSLRecordProtocol recordProtocol) {
- this.recordProtocol = recordProtocol;
- }
-
- /**
- * Start session negotiation
- * @param session
- */
- public abstract void start();
-
- /**
- * Stops the current session renegotiation process.
- * Such functionality is needed when it is session renegotiation
- * process and no_renegotiation alert message is received
- * from another peer.
- * @param session
- */
- protected void stop() {
- clearMessages();
- status = NOT_HANDSHAKING;
- }
-
- /**
- * Returns handshake status
- * @return
- */
- public SSLEngineResult.HandshakeStatus getStatus() {
- if (io_stream.hasData() || needSendCCSpec ||
- needSendHelloRequest || delegatedTaskErr != null) {
- return SSLEngineResult.HandshakeStatus.NEED_WRAP;
- }
- if (!delegatedTasks.isEmpty()) {
- return SSLEngineResult.HandshakeStatus.NEED_TASK;
- }
-
- switch (status) {
- case HandshakeProtocol.NEED_UNWRAP:
- return SSLEngineResult.HandshakeStatus.NEED_UNWRAP;
- case HandshakeProtocol.FINISHED:
- status = NOT_HANDSHAKING;
- clearMessages();
- return SSLEngineResult.HandshakeStatus.FINISHED;
- default: // HandshakeProtocol.NOT_HANDSHAKING:
- return SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING;
- }
- }
-
- /**
- * Returns pending session
- * @return session
- */
- public SSLSessionImpl getSession() {
- return session;
- }
-
- protected void sendChangeCipherSpec() {
- needSendCCSpec = true;
- }
-
- protected void sendHelloRequest() {
- needSendHelloRequest = true;
- }
-
- /**
- * Proceses inbound ChangeCipherSpec message
- */
- abstract void receiveChangeCipherSpec();
-
- /**
- * Creates and sends finished message
- */
- abstract void makeFinished();
-
- /**
- * Proceses inbound handshake messages
- * @param bytes
- */
- public abstract void unwrap(byte[] bytes);
-
- /**
- * Processes SSLv2 Hello message
- * @param bytes
- */
- public abstract void unwrapSSLv2(byte[] bytes);
-
- /**
- * Proceses outbound handshake messages
- * @return
- */
- public byte[] wrap() {
- if (delegatedTaskErr != null) {
- // process error occured in delegated task
- Exception e = delegatedTaskErr;
- delegatedTaskErr = null;
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE,
- "Error occured in delegated task:" + e.getMessage(), e);
- }
- if (io_stream.hasData()) {
- return recordProtocol.wrap(ContentType.HANDSHAKE, io_stream);
- } else if (needSendCCSpec) {
- makeFinished();
- needSendCCSpec = false;
- return recordProtocol.getChangeCipherSpecMesage(getSession());
- } else if (needSendHelloRequest) {
- needSendHelloRequest = false;
- return recordProtocol.wrap(ContentType.HANDSHAKE,
- // hello request message
- // (see TLS v 1 specification:
- // http://www.ietf.org/rfc/rfc2246.txt)
- new byte[] {0, 0, 0, 0}, 0, 4);
- } else {
- return null; // nothing to send;
- }
- }
-
- /**
- * Sends fatal alert, breaks execution
- *
- * @param description
- */
- protected void sendWarningAlert(byte description) {
- recordProtocol.alert(AlertProtocol.WARNING, description);
- }
-
- /**
- * Sends fatal alert, breaks execution
- *
- * @param description
- * @param reason
- */
- protected void fatalAlert(byte description, String reason) {
- throw new AlertException(description, new SSLHandshakeException(reason));
- }
-
- /**
- * Sends fatal alert, breaks execution
- *
- * @param description
- * @param reason
- * @param cause
- */
- protected void fatalAlert(byte description, String reason, Exception cause) {
- throw new AlertException(description, new SSLException(reason, cause));
- }
-
- /**
- * Sends fatal alert, breaks execution
- *
- * @param description
- * @param cause
- */
- protected void fatalAlert(byte description, SSLException cause) {
- throw new AlertException(description, cause);
- }
-
- /**
- * Computers reference TLS verify_data that is used to verify finished message
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS spec. 7.4.9. Finished</a>
- * @param label
- */
- protected void computerReferenceVerifyDataTLS(String label) {
- computerVerifyDataTLS(label, verify_data);
- }
-
- /**
- * Computer TLS verify_data
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS spec. 7.4.9. Finished</a>
- * @param label
- * @param buf
- */
- protected void computerVerifyDataTLS(String label, byte[] buf) {
- byte[] md5_digest = io_stream.getDigestMD5();
- byte[] sha_digest = io_stream.getDigestSHA();
-
- byte[] digest = new byte[md5_digest.length + sha_digest.length];
- System.arraycopy(md5_digest, 0, digest, 0, md5_digest.length);
- System.arraycopy(sha_digest, 0, digest, md5_digest.length,
- sha_digest.length);
- try {
- PRF.computePRF(buf, session.master_secret,
- label.getBytes(), digest);
- } catch (GeneralSecurityException e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR, "PRF error", e);
- }
- }
-
- /**
- * Computer reference SSLv3 verify_data that is used to verify finished message
- * @see "SSLv3 spec. 7.6.9. Finished"
- * @param label
- */
- protected void computerReferenceVerifyDataSSLv3(byte[] sender) {
- verify_data = new byte[36];
- computerVerifyDataSSLv3(sender, verify_data);
- }
-
- /**
- * Computer SSLv3 verify_data
- * @see "SSLv3 spec. 7.6.9. Finished"
- * @param label
- * @param buf
- */
- protected void computerVerifyDataSSLv3(byte[] sender, byte[] buf) {
- MessageDigest md5;
- MessageDigest sha;
- try {
- md5 = MessageDigest.getInstance("MD5");
- sha = MessageDigest.getInstance("SHA-1");
- } catch (Exception e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR, "Could not initialize the Digest Algorithms.", e);
- return;
- }
- try {
- byte[] hanshake_messages = io_stream.getMessages();
- md5.update(hanshake_messages);
- md5.update(sender);
- md5.update(session.master_secret);
- byte[] b = md5.digest(SSLv3Constants.MD5pad1);
- md5.update(session.master_secret);
- md5.update(SSLv3Constants.MD5pad2);
- System.arraycopy(md5.digest(b), 0, buf, 0, 16);
-
- sha.update(hanshake_messages);
- sha.update(sender);
- sha.update(session.master_secret);
- b = sha.digest(SSLv3Constants.SHApad1);
- sha.update(session.master_secret);
- sha.update(SSLv3Constants.SHApad2);
- System.arraycopy(sha.digest(b), 0, buf, 16, 20);
- } catch (Exception e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);
-
- }
- }
-
- /**
- * Verifies finished data
- *
- * @param data
- * @param isServer
- */
- protected void verifyFinished(byte[] data) {
- if (!Arrays.equals(verify_data, data)) {
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "Incorrect FINISED");
- }
- }
-
- /**
- * Sends fatal alert "UNEXPECTED MESSAGE"
- *
- */
- protected void unexpectedMessage() {
- fatalAlert(AlertProtocol.UNEXPECTED_MESSAGE, "UNEXPECTED MESSAGE");
- }
-
- /**
- * Writes message to HandshakeIODataStream
- *
- * @param message
- */
- public void send(Message message) {
- io_stream.writeUint8(message.getType());
- io_stream.writeUint24(message.length());
- message.send(io_stream);
- }
-
- /**
- * Computers master secret
- *
- */
- public void computerMasterSecret() {
- byte[] seed = new byte[64];
- System.arraycopy(clientHello.getRandom(), 0, seed, 0, 32);
- System.arraycopy(serverHello.getRandom(), 0, seed, 32, 32);
- session.master_secret = new byte[48];
- if (serverHello.server_version[1] == 1) { // TLSv1
- try {
- PRF.computePRF(session.master_secret, preMasterSecret,
- master_secret_bytes, seed);
- } catch (GeneralSecurityException e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR, "PRF error", e);
- }
- } else { // SSL3.0
- PRF.computePRF_SSLv3(session.master_secret, preMasterSecret, seed);
- }
-
- //delete preMasterSecret from memory
- Arrays.fill(preMasterSecret, (byte)0);
- preMasterSecret = null;
- }
-
- /**
- * Returns a delegated task.
- * @return Delegated task or null
- */
- public Runnable getTask() {
- if (delegatedTasks.isEmpty()) {
- return null;
- }
- return delegatedTasks.remove(0);
- }
-
- /**
- *
- * Clears previously sended and received handshake messages
- */
- protected void clearMessages() {
- io_stream.clearBuffer();
- clientHello = null;
- serverHello = null;
- serverCert = null;
- serverKeyExchange = null;
- certificateRequest = null;
- serverHelloDone = null;
- clientCert = null;
- clientKeyExchange = null;
- certificateVerify = null;
- clientFinished = null;
- serverFinished = null;
- }
-
- /**
- * Returns RSA key length
- * @param pk
- * @return
- * @throws NoSuchAlgorithmException
- * @throws InvalidKeySpecException
- */
- protected static int getRSAKeyLength(PublicKey pk)
- throws NoSuchAlgorithmException, InvalidKeySpecException {
-
- BigInteger mod;
- if (pk instanceof RSAKey) {
- mod = ((RSAKey) pk).getModulus();
- } else {
- KeyFactory kf = KeyFactory.getInstance("RSA");
- mod = kf.getKeySpec(pk, RSAPublicKeySpec.class)
- .getModulus();
- }
- return mod.bitLength();
- }
-
- /**
- * Shutdownes the protocol. It will be impossiblke to use the instance
- * after the calling of this method.
- */
- protected void shutdown() {
- clearMessages();
- session = null;
- preMasterSecret = null;
- delegatedTasks.clear();
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/HelloRequest.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/HelloRequest.java
deleted file mode 100644
index 40d4a71..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/HelloRequest.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.Message;
-import org.apache.harmony.xnet.provider.jsse.Handshake;
-import org.apache.harmony.xnet.provider.jsse.HandshakeIODataStream;
-
-import java.io.IOException;
-
-/**
- *
- * Represents Hello Request message
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7.4.1.1.
- * Hello request</a>
- *
- */
-public class HelloRequest extends Message {
-
- /**
- * Creates outbound message
- *
- */
- public HelloRequest() {
- }
-
- /**
- * Creates inbound message
- * @param in
- * @param length
- * @throws IOException
- */
- public HelloRequest(HandshakeIODataStream in, int length)
- throws IOException {
- if (length != 0) {
- fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR: incorrect HelloRequest");
- }
- }
-
- /**
- * Sends message
- * @param out
- */
- @Override
- public void send(HandshakeIODataStream out) {
- }
-
- @Override
- public int length() {
- return 0;
- }
-
- /**
- * Returns message type
- * @return
- */
- @Override
- public int getType() {
- return Handshake.HELLO_REQUEST;
- }
-
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/JSSEProvider.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/JSSEProvider.java
deleted file mode 100644
index 083a342..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/JSSEProvider.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.security.Provider;
-
-/**
- * JSSE Provider implementation.
- *
- * This implementation is based on TLS v 1.0 and SSL v3 protocol specifications.
- *
- * <ul>
- * <li><a href="http://www.ietf.org/rfc/rfc2246.txt">TLS v 1.0 Protocol
- * specification</a></li>
- * <li><a href="http://wp.netscape.com/eng/ssl3">SSL v3 Protocol
- * specification</a></li>
- * </ul>
- *
- * Provider implementation supports the following cipher suites:
- * TLS_NULL_WITH_NULL_NULL
- * TLS_RSA_WITH_NULL_MD5
- * TLS_RSA_WITH_NULL_SHA
- * TLS_RSA_EXPORT_WITH_RC4_40_MD5
- * TLS_RSA_WITH_RC4_128_MD5
- * TLS_RSA_WITH_RC4_128_SHA
- * TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5
- * TLS_RSA_WITH_IDEA_CBC_SHA
- * TLS_RSA_EXPORT_WITH_DES40_CBC_SHA
- * TLS_RSA_WITH_DES_CBC_SHA
- * TLS_RSA_WITH_3DES_EDE_CBC_SHA
- * TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA
- * TLS_DH_DSS_WITH_DES_CBC_SHA
- * TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA
- * TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA
- * TLS_DH_RSA_WITH_DES_CBC_SHA
- * TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA
- * TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA
- * TLS_DHE_DSS_WITH_DES_CBC_SHA
- * TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA
- * TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA
- * TLS_DHE_RSA_WITH_DES_CBC_SHA
- * TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
- * TLS_DH_anon_EXPORT_WITH_RC4_40_MD5
- * TLS_DH_anon_WITH_RC4_128_MD5
- * TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA
- * TLS_DH_anon_WITH_DES_CBC_SHA
- * TLS_DH_anon_WITH_3DES_EDE_CBC_SHA
- *
- * The real set of available cipher suites depends on set of available
- * crypto algorithms. These algorithms must be provided by some crypto
- * provider.
- *
- * The following cipher algorithms are used by different cipher suites:
- * IDEA/CBC/NoPadding
- * RC2/CBC/NoPadding
- * RC4
- * DES/CBC/NoPadding
- * DES/CBC/NoPadding
- * DESede/CBC/NoPadding
- *
- * Also the current JSSE provider implementation uses the following
- * crypto algorithms:
- *
- * Algorithms that MUST be provided by crypto provider:
- * Mac HmacMD5
- * Mac HmacSHA1
- * MessageDigest MD5
- * MessageDigest SHA-1
- * CertificateFactory X509
- *
- * The cipher suites with RSA key exchange may also require:
- * Cipher RSA
- * KeyPairGenerator RSA
- * KeyFactory RSA
- *
- * The cipher suites with DH key exchange may also require:
- * Signature NONEwithDSA
- * KeyPairGenerator DiffieHellman or DH
- * KeyFactory DiffieHellman or DH
- * KeyAgreement DiffieHellman or DH
- * KeyPairGenerator DiffieHellman or DH
- *
- * Trust manager implementation requires:
- * CertPathValidator PKIX
- * CertificateFactory X509
- *
- */
-public final class JSSEProvider extends Provider {
-
- private static final long serialVersionUID = 3075686092260669675L;
-
- public JSSEProvider() {
- super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
- AccessController.doPrivileged(new PrivilegedAction<Void>() {
- public Void run() {
- put("SSLContext.TLS", SSLContextImpl.class.getName());
- put("Alg.Alias.SSLContext.TLSv1", "TLS");
- put("KeyManagerFactory.X509", KeyManagerFactoryImpl.class.getName());
- put("TrustManagerFactory.X509", TrustManagerFactoryImpl.class.getName());
- // BEGIN android-added
- put("SSLContext.SSL", SSLContextImpl.class.getName());
- put("Alg.Alias.SSLContext.SSLv3", "SSL");
- put("MessageDigest.SHA-1", "org.apache.harmony.xnet.provider.jsse.OpenSSLMessageDigestJDK$SHA1");
- put("Alg.Alias.MessageDigest.SHA1", "SHA-1");
- put("Alg.Alias.MessageDigest.SHA", "SHA-1");
- put("Alg.Alias.MessageDigest.1.3.14.3.2.26", "SHA-1");
- put("MessageDigest.SHA-224", "org.apache.harmony.xnet.provider.jsse.OpenSSLMessageDigestJDK$SHA224");
- put("Alg.Alias.MessageDigest.SHA224", "SHA-224");
- put("Alg.Alias.MessageDigest.2.16.840.1.101.3.4.2.4", "SHA-224");
- put("MessageDigest.SHA-256", "org.apache.harmony.xnet.provider.jsse.OpenSSLMessageDigestJDK$SHA256");
- put("Alg.Alias.MessageDigest.SHA256", "SHA-256");
- put("Alg.Alias.MessageDigest.2.16.840.1.101.3.4.2.1", "SHA-256");
- put("MessageDigest.MD5", "org.apache.harmony.xnet.provider.jsse.OpenSSLMessageDigestJDK$MD5");
- put("Alg.Alias.MessageDigest.1.2.840.113549.2.5", "MD5");
- // END android-added
- return null;
- }
- });
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/KeyManagerFactoryImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/KeyManagerFactoryImpl.java
deleted file mode 100644
index 3b55299..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/KeyManagerFactoryImpl.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.security.AccessController;
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-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;
-
-/**
- * KeyManagerFactory implementation.
- * @see javax.net.ssl.KeyManagerFactorySpi
- */
-public class KeyManagerFactoryImpl extends KeyManagerFactorySpi {
-
- // source of key material
- private KeyStore keyStore;
-
- //password
- private char[] pwd;
-
- /**
- * @see javax.net.ssl.KeyManagerFactorySpi#engineInit(KeyStore ks, char[]
- * password)
- */
- @Override
- public void engineInit(KeyStore ks, char[] password)
- throws KeyStoreException, NoSuchAlgorithmException,
- UnrecoverableKeyException {
- if (ks != null) {
- keyStore = ks;
- if (password != null) {
- pwd = password.clone();
- } else {
- pwd = new char[0];
- }
- } else {
- keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
- String keyStoreName = AccessController
- .doPrivileged(new java.security.PrivilegedAction<String>() {
- public String run() {
- return System.getProperty("javax.net.ssl.keyStore");
- }
- });
- String keyStorePwd = null;
- if (keyStoreName == null || keyStoreName.equalsIgnoreCase("NONE")
- || keyStoreName.length() == 0) {
- try {
- keyStore.load(null, null);
- } catch (IOException e) {
- throw new KeyStoreException(e);
- } catch (CertificateException e) {
- throw new KeyStoreException(e);
- }
- } else {
- keyStorePwd = AccessController
- .doPrivileged(new java.security.PrivilegedAction<String>() {
- public String run() {
- return System
- .getProperty("javax.net.ssl.keyStorePassword");
- }
- });
- if (keyStorePwd == null) {
- pwd = new char[0];
- } else {
- pwd = keyStorePwd.toCharArray();
- }
- try {
- keyStore.load(new FileInputStream(new File(keyStoreName)),
- pwd);
-
- } catch (FileNotFoundException e) {
- throw new KeyStoreException(e);
- } catch (IOException e) {
- throw new KeyStoreException(e);
- } catch (CertificateException e) {
- throw new KeyStoreException(e);
- }
- }
-
- }
-
- }
-
- /**
- * @see javax.net.ssl.KeyManagerFactorySpi#engineInit(ManagerFactoryParameters
- * spec)
- */
- @Override
- public void engineInit(ManagerFactoryParameters spec)
- throws InvalidAlgorithmParameterException {
- throw new InvalidAlgorithmParameterException(
- "ManagerFactoryParameters not supported");
-
- }
-
- /**
- * @see javax.net.ssl.KeyManagerFactorySpi#engineGetKeyManagers()
- */
- @Override
- public KeyManager[] engineGetKeyManagers() {
- if (keyStore == null) {
- throw new IllegalStateException("KeyManagerFactory is not initialized");
- }
- return new KeyManager[] { new KeyManagerImpl(keyStore, pwd) };
- }
-
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/KeyManagerImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/KeyManagerImpl.java
deleted file mode 100644
index f63170f..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/KeyManagerImpl.java
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.net.Socket;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.Principal;
-import java.security.PrivateKey;
-import java.security.UnrecoverableEntryException;
-import java.security.KeyStore.PrivateKeyEntry;
-import java.security.cert.Certificate;
-import java.security.cert.X509Certificate;
-import java.util.Enumeration;
-import java.util.Hashtable;
-import java.util.Vector;
-
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.X509ExtendedKeyManager;
-import javax.security.auth.x500.X500Principal;
-
-/**
- * KeyManager implementation.
- *
- * This implementation uses hashed key store information. It works faster than retrieving all of the
- * data from the key store. Any key store changes, that happen after key manager was created, have
- * no effect. The implementation does not use peer information (host, port) that may be obtained
- * from socket or engine.
- *
- * @see javax.net.ssl.KeyManager
- *
- */
-public class KeyManagerImpl extends X509ExtendedKeyManager {
-
- // hashed key store information
- private final Hashtable<String, PrivateKeyEntry> hash;
-
- /**
- * Creates Key manager
- *
- * @param keyStore
- * @param pwd
- */
- public KeyManagerImpl(KeyStore keyStore, char[] pwd) {
- super();
- this.hash = new Hashtable<String, PrivateKeyEntry>();
- final Enumeration<String> aliases;
- try {
- aliases = keyStore.aliases();
- } catch (KeyStoreException e) {
- return;
- }
- for (; aliases.hasMoreElements();) {
- final String alias = aliases.nextElement();
- try {
- if (keyStore.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)) {
- final KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore
- .getEntry(alias, new KeyStore.PasswordProtection(pwd));
- hash.put(alias, entry);
- }
- } catch (KeyStoreException e) {
- continue;
- } catch (UnrecoverableEntryException e) {
- continue;
- } catch (NoSuchAlgorithmException e) {
- continue;
- }
- }
- }
-
- public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) {
- final String[] al = chooseAlias(keyType, issuers);
- return (al == null ? null : al[0]);
- }
-
- public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
- final String[] al = chooseAlias(new String[] { keyType }, issuers);
- return (al == null ? null : al[0]);
- }
-
- public X509Certificate[] getCertificateChain(String alias) {
- // BEGIN android-changed
- if (alias == null) {
- return null;
- }
- // END android-changed
- if (hash.containsKey(alias)) {
- Certificate[] certs = hash.get(alias).getCertificateChain();
- if (certs[0] instanceof X509Certificate) {
- X509Certificate[] xcerts = new X509Certificate[certs.length];
- for (int i = 0; i < certs.length; i++) {
- xcerts[i] = (X509Certificate) certs[i];
- }
- return xcerts;
- }
- }
- return null;
-
- }
-
- public String[] getClientAliases(String keyType, Principal[] issuers) {
- return chooseAlias(new String[] { keyType }, issuers);
- }
-
- public String[] getServerAliases(String keyType, Principal[] issuers) {
- return chooseAlias(new String[] { keyType }, issuers);
- }
-
- public PrivateKey getPrivateKey(String alias) {
- // BEGIN android-changed
- if (alias == null) {
- return null;
- }
- // END android-changed
- if (hash.containsKey(alias)) {
- return hash.get(alias).getPrivateKey();
- }
- return null;
- }
-
- @Override
- public String chooseEngineClientAlias(String[] keyType, Principal[] issuers, SSLEngine engine) {
- final String[] al = chooseAlias(keyType, 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);
- return (al == null ? null : al[0]);
- }
-
- private String[] chooseAlias(String[] keyType, Principal[] issuers) {
- if (keyType == null || keyType.length == 0) {
- return null;
- }
- Vector<String> found = new Vector<String>();
- for (Enumeration<String> aliases = hash.keys(); aliases.hasMoreElements();) {
- final String alias = aliases.nextElement();
- final KeyStore.PrivateKeyEntry entry = hash.get(alias);
- final Certificate[] certs = entry.getCertificateChain();
- final String alg = certs[0].getPublicKey().getAlgorithm();
- for (int i = 0; i < keyType.length; i++) {
- if (alg.equals(keyType[i])) {
- if (issuers != null && issuers.length != 0) {
- // check that certificate was issued by specified issuer
- loop: for (int ii = 0; ii < certs.length; ii++) {
- if (certs[ii] instanceof X509Certificate) {
- X500Principal issuer = ((X509Certificate) certs[ii])
- .getIssuerX500Principal();
- for (int iii = 0; iii < issuers.length; iii++) {
- if (issuer.equals(issuers[iii])) {
- found.add(alias);
- break loop;
- }
- }
- }
-
- }
- } else {
- found.add(alias);
- }
- }
- }
- }
- if (!found.isEmpty()) {
- return found.toArray(new String[found.size()]);
- }
- return null;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Logger.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Logger.java
deleted file mode 100644
index c06aa7e..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Logger.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.PrintStream;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-
-/**
- * This class provides debug logging for JSSE provider implementation
- * TODO: Use java.util.logging
- */
-public class Logger {
-
- public static class Stream extends PrintStream {
- private final String prefix;
- private static int indent = 0;
-
- public Stream(String name) {
- super(System.err);
- prefix = name + "["+Thread.currentThread().getName()+"] ";
- }
-
- @Override
- public void print(String msg) {
- for (int i=0; i<indent; i++) {
- super.print(" ");
- }
- super.print(msg);
- }
-
- public void newIndent() {
- indent ++;
- }
-
- public void endIndent() {
- indent --;
- }
-
- @Override
- public void println(String msg) {
- print(prefix);
- super.println(msg);
- }
-
- public void print(byte[] data) {
- printAsHex(16, " ", "", data, 0, data.length);
- }
-
- public void print(byte[] data, int offset, int len) {
- printAsHex(16, " ", "", data, offset, len);
- }
-
- public void printAsHex(int perLine,
- String prefix,
- String delimiter,
- byte[] data) {
- printAsHex(perLine, prefix, delimiter, data, 0, data.length);
- }
-
- public void printAsHex(int perLine,
- String prefix,
- String delimiter,
- byte[] data, int offset, int len) {
- String line = "";
- for (int i=0; i<len; i++) {
- String tail =
- Integer.toHexString(0x00ff & data[i+offset]).toUpperCase();
- if (tail.length() == 1) {
- tail = "0" + tail;
- }
- line += prefix + tail + delimiter;
-
- if (((i+1)%perLine) == 0) {
- super.println(line);
- line = "";
- }
- }
- super.println(line);
- }
- }
-
- private static String[] names;
-
- static {
- try {
- names = AccessController
- .doPrivileged(new PrivilegedAction<String[]>() {
- public String[] run() {
- return System.getProperty("jsse", "").split(",");
- }
- });
- } catch (Exception e) {
- names = new String[0];
- }
- }
-
- public static Stream getStream(String name) {
- for (int i=0; i<names.length; i++) {
- if (names[i].equals(name)) {
- return new Stream(name);
- }
- }
- return null;
- }
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Message.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Message.java
deleted file mode 100644
index f1b2515..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Message.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.AlertException;
-
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLHandshakeException;
-
-/**
- *
- * Base class for handshake messages
- */
-public abstract class Message {
-
- /*
- * Message length
- */
- protected int length;
-
- /**
- * Returns message type
- * @return
- */
- abstract int getType();
-
- /**
- * Returns message length
- * @return
- */
- public int length() {
- return length;
- }
-
- /**
- * Sends message
- * @param out
- */
- abstract void send(HandshakeIODataStream out);
-
- /**
- * Sends fatal alert
- * @param description
- * @param reason
- */
- protected void fatalAlert(byte description, String reason) {
- throw new AlertException(description, new SSLHandshakeException(reason));
- }
-
- /**
- * Sends fatal alert
- * @param description
- * @param reason
- * @param cause
- */
- protected void fatalAlert(byte description, String reason, Throwable cause) {
- throw new AlertException(description, new SSLException(reason, cause));
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/NativeCrypto.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/NativeCrypto.java
deleted file mode 100644
index 2220d36..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/NativeCrypto.java
+++ /dev/null
@@ -1,330 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.OutputStreamWriter;
-import java.net.Socket;
-import java.security.PrivateKey;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-
-import org.bouncycastle.openssl.PEMWriter;
-
-/**
- * Provides the Java side of our JNI glue for OpenSSL. Currently only hashing
- * and verifying are covered. Is expected to grow over time. Also needs to move
- * into libcore/openssl at some point.
- */
-public class NativeCrypto {
-
- // --- OpenSSL library initialization --------------------------------------
- static {
- clinit();
- }
-
- private native static void clinit();
-
- // --- DSA/RSA public/private key handling functions -----------------------
-
- public static native int EVP_PKEY_new_DSA(byte[] p, byte[] q, byte[] g, byte[] priv_key, byte[] pub_key);
-
- public static native int EVP_PKEY_new_RSA(byte[] n, byte[] e, byte[] d, byte[] p, byte[] q);
-
- public static native void EVP_PKEY_free(int pkey);
-
- // --- General context handling functions (despite the names) --------------
-
- public static native int EVP_new();
-
- public static native void EVP_free(int ctx);
-
- // --- Digest handling functions -------------------------------------------
-
- public static native void EVP_DigestInit(int ctx, String algorithm);
-
- public static native void EVP_DigestUpdate(int ctx, byte[] buffer, int offset, int length);
-
- public static native int EVP_DigestFinal(int ctx, byte[] hash, int offset);
-
- public static native int EVP_DigestSize(int ctx);
-
- public static native int EVP_DigestBlockSize(int ctx);
-
- // --- Signature handling functions ----------------------------------------
-
- public static native void EVP_VerifyInit(int ctx, String algorithm);
-
- public static native void EVP_VerifyUpdate(int ctx, byte[] buffer, int offset, int length);
-
- public static native int EVP_VerifyFinal(int ctx, byte[] signature, int offset, int length, int key);
-
- // --- SSL handling --------------------------------------------------------
-
- private static final String SUPPORTED_PROTOCOL_SSLV3 = "SSLv3";
- private static final String SUPPORTED_PROTOCOL_TLSV1 = "TLSv1";
-
- // SSL mode
- public static long SSL_MODE_HANDSHAKE_CUTTHROUGH = 0x00000040L;
-
- // SSL options
- public static long SSL_OP_NO_SSLv3 = 0x02000000L;
- public static long SSL_OP_NO_TLSv1 = 0x04000000L;
-
- public static native int SSL_CTX_new();
-
- public static native String[] SSL_CTX_get_ciphers(int ssl_ctx);
-
- public static String[] getDefaultCipherSuites() {
- int ssl_ctx = SSL_CTX_new();
- String[] supportedCiphers = SSL_CTX_get_ciphers(ssl_ctx);
- SSL_CTX_free(ssl_ctx);
- return supportedCiphers;
- }
-
- public static String[] getSupportedCipherSuites() {
- // TODO really return full cipher list
- return getDefaultCipherSuites();
- }
-
- public static native void SSL_CTX_free(int ssl_ctx);
-
- public static native int SSL_new(int ssl_ctx, String privatekey, String certificate, byte[] seed) throws IOException;
-
- /**
- * Initialize the SSL socket and set the certificates for the
- * future handshaking.
- */
- public static int SSL_new(SSLParameters sslParameters) throws IOException {
- boolean client = sslParameters.getUseClientMode();
-
- final int ssl_ctx = (client) ?
- sslParameters.getClientSessionContext().sslCtxNativePointer :
- sslParameters.getServerSessionContext().sslCtxNativePointer;
-
- // TODO support more than RSA certificates? non-openssl
- // SSLEngine implementation did these callbacks during
- // handshake after selecting cipher suite, not before
- // handshake. Should do the same via SSL_CTX_set_client_cert_cb
- final String alias = (client) ?
- sslParameters.getKeyManager().chooseClientAlias(new String[] { "RSA" }, null, null) :
- sslParameters.getKeyManager().chooseServerAlias("RSA", null, null);
-
- final String privateKeyString;
- final String certificateString;
- if (alias == null) {
- privateKeyString = null;
- certificateString = null;
- } else {
- PrivateKey privateKey = sslParameters.getKeyManager().getPrivateKey(alias);
- X509Certificate[] certificates = sslParameters.getKeyManager().getCertificateChain(alias);
-
- ByteArrayOutputStream privateKeyOS = new ByteArrayOutputStream();
- PEMWriter privateKeyPEMWriter = new PEMWriter(new OutputStreamWriter(privateKeyOS));
- privateKeyPEMWriter.writeObject(privateKey);
- privateKeyPEMWriter.close();
- privateKeyString = privateKeyOS.toString();
-
- ByteArrayOutputStream certificateOS = new ByteArrayOutputStream();
- PEMWriter certificateWriter = new PEMWriter(new OutputStreamWriter(certificateOS));
-
- for (X509Certificate certificate : certificates) {
- certificateWriter.writeObject(certificate);
- }
- certificateWriter.close();
- certificateString = certificateOS.toString();
- }
-
- final byte[] seed = (sslParameters.getSecureRandomMember() != null) ?
- sslParameters.getSecureRandomMember().generateSeed(1024) :
- null;
-
- return SSL_new(ssl_ctx,
- privateKeyString,
- certificateString,
- seed);
- }
-
-
- public static native long SSL_get_mode(int ssl);
-
- public static native long SSL_set_mode(int ssl, long options);
-
- public static native long SSL_clear_mode(int ssl, long options);
-
- public static native long SSL_get_options(int ssl);
-
- public static native long SSL_set_options(int ssl, long options);
-
- public static native long SSL_clear_options(int ssl, long options);
-
- public static String[] getSupportedProtocols() {
- return new String[] { SUPPORTED_PROTOCOL_SSLV3, SUPPORTED_PROTOCOL_TLSV1 };
- }
-
- public static String[] getEnabledProtocols(int ssl) {
- long options = SSL_get_options(ssl);
- ArrayList<String> array = new ArrayList<String>();
- if ((options & NativeCrypto.SSL_OP_NO_SSLv3) == 0) {
- array.add(SUPPORTED_PROTOCOL_SSLV3);
- }
- if ((options & NativeCrypto.SSL_OP_NO_TLSv1) == 0) {
- array.add(SUPPORTED_PROTOCOL_TLSV1);
- }
- return array.toArray(new String[array.size()]);
- }
-
- public static void setEnabledProtocols(int ssl, String[] protocols) {
- if (protocols == null) {
- throw new IllegalArgumentException("protocols == null");
- }
-
- // openssl uses negative logic letting you disable protocols.
- // so first, assume we need to set all (disable all ) and clear none (enable none).
- // in the loop, selectively move bits from set to clear (from disable to enable)
- long optionsToSet = (SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1);
- long optionsToClear = 0;
- for (int i = 0; i < protocols.length; i++) {
- String protocol = protocols[i];
- if (protocol == null) {
- throw new IllegalArgumentException("protocols[" + i + "] == null");
- }
- if (protocol.equals(SUPPORTED_PROTOCOL_SSLV3)) {
- optionsToSet &= ~SSL_OP_NO_SSLv3;
- optionsToClear |= SSL_OP_NO_SSLv3;
- } else if (protocol.equals(SUPPORTED_PROTOCOL_TLSV1)) {
- optionsToSet &= ~SSL_OP_NO_TLSv1;
- optionsToClear |= SSL_OP_NO_TLSv1;
- } else {
- throw new IllegalArgumentException("Protocol " + protocol +
- " is not supported");
- }
- }
-
- SSL_set_options(ssl, optionsToSet);
- SSL_clear_options(ssl, optionsToClear);
- }
-
- public static String[] checkEnabledProtocols(String[] protocols) {
- if (protocols == null) {
- throw new IllegalArgumentException("protocols parameter is null");
- }
- for (int i = 0; i < protocols.length; i++) {
- String protocol = protocols[i];
- if (protocol == null) {
- throw new IllegalArgumentException("protocols[" + i + "] == null");
- }
- if ((!protocol.equals(SUPPORTED_PROTOCOL_SSLV3))
- && (!protocol.equals(SUPPORTED_PROTOCOL_TLSV1))) {
- throw new IllegalArgumentException("Protocol " + protocol +
- " is not supported");
- }
- }
- return protocols;
- }
-
- public static native String[] SSL_get_ciphers(int ssl);
-
- public static native void SSL_set_cipher_list(int ssl, String ciphers);
-
- public static void setEnabledCipherSuites(int ssl, String[] cipherSuites) {
- checkEnabledCipherSuites(cipherSuites);
- String controlString = "";
- for (int i = 0; i < cipherSuites.length; i++) {
- String cipherSuite = cipherSuites[i];
- if (i == 0) {
- controlString = cipherSuite;
- } else {
- controlString += ":" + cipherSuite;
- }
- }
- SSL_set_cipher_list(ssl, controlString);
- }
-
- public static String[] checkEnabledCipherSuites(String[] cipherSuites) {
- if (cipherSuites == null) {
- throw new IllegalArgumentException("cipherSuites == null");
- }
- // makes sure all suites are valid, throwing on error
- String[] supportedCipherSuites = getSupportedCipherSuites();
- for (int i = 0; i < cipherSuites.length; i++) {
- String cipherSuite = cipherSuites[i];
- if (cipherSuite == null) {
- throw new IllegalArgumentException("cipherSuites[" + i + "] == null");
- }
- findSuite(supportedCipherSuites, cipherSuite);
- }
- return cipherSuites;
- }
-
- private static void findSuite(String[] supportedCipherSuites, String suite) {
- for (String supportedCipherSuite : supportedCipherSuites) {
- if (supportedCipherSuite.equals(suite)) {
- return;
- }
- }
- throw new IllegalArgumentException("Protocol " + suite + " is not supported.");
- }
-
- /*
- * See the OpenSSL ssl.h header file for more information.
- */
- public static final int SSL_VERIFY_NONE = 0x00;
- public static final int SSL_VERIFY_PEER = 0x01;
- public static final int SSL_VERIFY_FAIL_IF_NO_PEER_CERT = 0x02;
- public static final int SSL_VERIFY_CLIENT_ONCE = 0x04;
-
- public static native void SSL_set_verify(int sslNativePointer, int mode) throws IOException;
-
- public static native void SSL_set_session(int sslNativePointer, int sslSessionNativePointer) throws IOException;
-
- public static native void SSL_set_session_creation_enabled(int sslNativePointer, boolean creationEnabled) throws IOException;
-
- /**
- * Returns the sslSessionNativePointer of the negotiated session
- */
- public static native int SSL_do_handshake(int sslNativePointer, Socket sock,
- CertificateChainVerifier ccv, HandshakeCompletedCallback hcc,
- int timeout, boolean client_mode) throws IOException, CertificateException;
-
- public static native byte[][] SSL_get_certificate(int sslNativePointer);
-
- public static native void SSL_free(int sslNativePointer);
-
- public interface CertificateChainVerifier {
- /**
- * Verify that we trust the certificate chain is trusted.
- *
- * @param bytes An array of certficates in PEM encode bytes
- * @param authMethod auth algorithm name
- *
- * @throws CertificateException if the certificate is untrusted
- */
- public void verifyCertificateChain(byte[][] bytes, String authMethod) throws CertificateException;
- }
-
- public interface HandshakeCompletedCallback {
- /**
- * Called when SSL handshake is completed. Note that this can
- * be after SSL_do_handshake returns when handshake cutthrough
- * is enabled.
- */
- public void handshakeCompleted();
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLMessageDigest.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLMessageDigest.java
deleted file mode 100644
index 919d9e1..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLMessageDigest.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.bouncycastle.crypto.ExtendedDigest;
-
-import java.security.NoSuchAlgorithmException;
-
-/**
- * Implements the BouncyCastle Digest interface using OpenSSL's EVP API.
- */
-public class OpenSSLMessageDigest implements ExtendedDigest {
-
- /**
- * Holds the name of the hashing algorithm, e.g. "SHA-1";
- */
- private String algorithm;
-
- /**
- * Holds a pointer to the native message digest context.
- */
- private int ctx;
-
- /**
- * Holds a dummy buffer for writing single bytes to the digest.
- */
- private byte[] singleByte = new byte[1];
-
- /**
- * Creates a new OpenSSLMessageDigest instance for the given algorithm
- * name.
- *
- * @param algorithm The name of the algorithm, e.g. "SHA1".
- *
- * @return The new OpenSSLMessageDigest instance.
- *
- * @throws RuntimeException In case of problems.
- */
- public static OpenSSLMessageDigest getInstance(String algorithm) {
- return new OpenSSLMessageDigest(algorithm);
- }
-
- /**
- * Creates a new OpenSSLMessageDigest instance for the given algorithm
- * name.
- *
- * @param algorithm The name of the algorithm, e.g. "SHA1".
- */
- private OpenSSLMessageDigest(String algorithm) {
- this.algorithm = algorithm;
-
- // We don't support MD2 anymore. This needs to also check for aliases
- // and OIDs.
- if ("MD2".equalsIgnoreCase(algorithm) || "1.2.840.113549.2.2"
- .equalsIgnoreCase(algorithm)) {
- throw new RuntimeException(algorithm + " not supported");
- }
-
- ctx = NativeCrypto.EVP_new();
- try {
- NativeCrypto.EVP_DigestInit(ctx, algorithm.replace("-", "").toLowerCase());
- } catch (Exception ex) {
- throw new RuntimeException(ex.getMessage() + " (" + algorithm + ")");
- }
- }
-
- public int doFinal(byte[] out, int outOff) {
- int i = NativeCrypto.EVP_DigestFinal(ctx, out, outOff);
- reset();
- return i;
- }
-
- public String getAlgorithmName() {
- return algorithm;
- }
-
- public int getDigestSize() {
- return NativeCrypto.EVP_DigestSize(ctx);
- }
-
- public int getByteLength() {
- return NativeCrypto.EVP_DigestBlockSize(ctx);
- }
-
- public void reset() {
- NativeCrypto.EVP_DigestInit(ctx, algorithm.replace("-", "").toLowerCase());
- }
-
- public void update(byte in) {
- singleByte[0] = in;
- NativeCrypto.EVP_DigestUpdate(ctx, singleByte, 0, 1);
- }
-
- public void update(byte[] in, int inOff, int len) {
- NativeCrypto.EVP_DigestUpdate(ctx, in, inOff, len);
- }
-
- @Override
- protected void finalize() throws Throwable {
- super.finalize();
- NativeCrypto.EVP_free(ctx);
- }
-
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLMessageDigestJDK.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLMessageDigestJDK.java
deleted file mode 100644
index 4ba3a74..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLMessageDigestJDK.java
+++ /dev/null
@@ -1,117 +0,0 @@
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-
-/**
- * Implements the JDK MessageDigest interface using OpenSSL's EVP API.
- */
-public class OpenSSLMessageDigestJDK extends MessageDigest {
-
- /**
- * Holds a pointer to the native message digest context.
- */
- private int ctx;
-
- /**
- * Holds a dummy buffer for writing single bytes to the digest.
- */
- private byte[] singleByte = new byte[1];
-
- /**
- * Creates a new OpenSSLMessageDigestJDK instance for the given algorithm
- * name.
- *
- * @param algorithm The name of the algorithm, e.g. "SHA1".
- *
- * @return The new OpenSSLMessageDigestJDK instance.
- *
- * @throws RuntimeException In case of problems.
- */
- public static OpenSSLMessageDigestJDK getInstance(String algorithm) throws NoSuchAlgorithmException{
- return new OpenSSLMessageDigestJDK(algorithm);
- }
-
- /**
- * Creates a new OpenSSLMessageDigest instance for the given algorithm
- * name.
- *
- * @param algorithm The name of the algorithm, e.g. "SHA1".
- */
- private OpenSSLMessageDigestJDK(String algorithm) throws NoSuchAlgorithmException {
- super(algorithm);
-
- // We don't support MD2 anymore. This needs to also check for aliases
- // and OIDs.
- if ("MD2".equalsIgnoreCase(algorithm) || "1.2.840.113549.2.2"
- .equalsIgnoreCase(algorithm)) {
- throw new NoSuchAlgorithmException(algorithm);
- }
-
- ctx = NativeCrypto.EVP_new();
- try {
- NativeCrypto.EVP_DigestInit(ctx, getAlgorithm().replace("-", "").toLowerCase());
- } catch (Exception ex) {
- throw new NoSuchAlgorithmException(ex.getMessage() + " (" + algorithm + ")");
- }
- }
-
- @Override
- protected byte[] engineDigest() {
- byte[] result = new byte[NativeCrypto.EVP_DigestSize(ctx)];
- NativeCrypto.EVP_DigestFinal(ctx, result, 0);
- engineReset();
- return result;
- }
-
- @Override
- protected void engineReset() {
- NativeCrypto.EVP_DigestInit(ctx, getAlgorithm().replace("-", "").toLowerCase());
- }
-
- @Override
- protected int engineGetDigestLength() {
- return NativeCrypto.EVP_DigestSize(ctx);
- }
-
- @Override
- protected void engineUpdate(byte input) {
- singleByte[0] = input;
- engineUpdate(singleByte, 0, 1);
- }
-
- @Override
- protected void engineUpdate(byte[] input, int offset, int len) {
- NativeCrypto.EVP_DigestUpdate(ctx, input, offset, len);
- }
-
- @Override
- protected void finalize() throws Throwable {
- super.finalize();
- NativeCrypto.EVP_free(ctx);
- }
-
- static public class MD5 extends OpenSSLMessageDigestJDK {
- public MD5() throws NoSuchAlgorithmException {
- super("MD5");
- }
- }
-
- static public class SHA1 extends OpenSSLMessageDigestJDK {
- public SHA1() throws NoSuchAlgorithmException {
- super("SHA-1");
- }
- }
-
- static public class SHA224 extends OpenSSLMessageDigestJDK {
- public SHA224() throws NoSuchAlgorithmException {
- super("SHA-224");
- }
- }
-
- static public class SHA256 extends OpenSSLMessageDigestJDK {
- public SHA256() throws NoSuchAlgorithmException {
- super("SHA-256");
- }
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLServerSocketFactoryImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLServerSocketFactoryImpl.java
deleted file mode 100644
index f342457..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLServerSocketFactoryImpl.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.ServerSocket;
-import java.security.KeyManagementException;
-
-public class OpenSSLServerSocketFactoryImpl extends javax.net.ssl.SSLServerSocketFactory {
-
- private SSLParameters sslParameters;
- private IOException instantiationException;
-
- public OpenSSLServerSocketFactoryImpl() {
- super();
- try {
- this.sslParameters = SSLParameters.getDefault();
- this.sslParameters.setUseClientMode(false);
- } catch (KeyManagementException e) {
- instantiationException =
- new IOException("Delayed instantiation exception:");
- instantiationException.initCause(e);
- }
- }
-
- public OpenSSLServerSocketFactoryImpl(SSLParameters sslParameters) {
- this.sslParameters = (SSLParameters) sslParameters.clone();
- this.sslParameters.setUseClientMode(false);
- }
-
- public String[] getDefaultCipherSuites() {
- return NativeCrypto.getDefaultCipherSuites();
- }
-
- public String[] getSupportedCipherSuites() {
- return NativeCrypto.getSupportedCipherSuites();
- }
-
- public ServerSocket createServerSocket() throws IOException {
- return new OpenSSLServerSocketImpl((SSLParameters) sslParameters.clone());
- }
-
- public ServerSocket createServerSocket(int port) throws IOException {
- return new OpenSSLServerSocketImpl(port, (SSLParameters) sslParameters.clone());
- }
-
- public ServerSocket createServerSocket(int port, int backlog)
- throws IOException {
- return new OpenSSLServerSocketImpl(port, backlog, (SSLParameters) sslParameters.clone());
- }
-
- public ServerSocket createServerSocket(int port, int backlog,
- InetAddress iAddress) throws IOException {
- return new OpenSSLServerSocketImpl(port, backlog, iAddress, (SSLParameters) sslParameters.clone());
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLServerSocketImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLServerSocketImpl.java
deleted file mode 100644
index 8d5a43e..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLServerSocketImpl.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.Socket;
-
-/**
- * OpenSSL-based implementation of server sockets.
- *
- * This class only supports SSLv3 and TLSv1. This should be documented elsewhere
- * later, for example in the package.html or a separate reference document.
- */
-public class OpenSSLServerSocketImpl extends javax.net.ssl.SSLServerSocket {
- private final SSLParameters sslParameters;
- private String[] enabledProtocols = NativeCrypto.getSupportedProtocols();
- private String[] enabledCipherSuites = NativeCrypto.getDefaultCipherSuites();
-
- protected OpenSSLServerSocketImpl(SSLParameters sslParameters)
- throws IOException {
- super();
- this.sslParameters = sslParameters;
- }
-
- protected OpenSSLServerSocketImpl(int port, SSLParameters sslParameters)
- throws IOException {
- super(port);
- this.sslParameters = sslParameters;
- }
-
- protected OpenSSLServerSocketImpl(int port, int backlog, SSLParameters sslParameters)
- throws IOException {
- super(port, backlog);
- this.sslParameters = sslParameters;
- }
-
- protected OpenSSLServerSocketImpl(int port, int backlog, InetAddress iAddress, SSLParameters sslParameters)
- throws IOException {
- super(port, backlog, iAddress);
- this.sslParameters = sslParameters;
- }
-
- @Override
- public boolean getEnableSessionCreation() {
- return sslParameters.getEnableSessionCreation();
- }
-
- @Override
- public void setEnableSessionCreation(boolean flag) {
- sslParameters.setEnableSessionCreation(flag);
- }
-
- /**
- * The names of the protocols' versions that may be used on this SSL
- * connection.
- * @return an array of protocols names
- */
- @Override
- public String[] getSupportedProtocols() {
- return NativeCrypto.getSupportedProtocols();
- }
-
- /**
- * The names of the protocols' versions that in use on this SSL connection.
- *
- * @return an array of protocols names
- */
- @Override
- public String[] getEnabledProtocols() {
- return enabledProtocols.clone();
- }
-
- /**
- * This method enables the protocols' versions listed by
- * getSupportedProtocols().
- *
- * @param protocols names of all the protocols to enable.
- *
- * @throws IllegalArgumentException when one or more of the names in the
- * array are not supported, or when the array is null.
- */
- @Override
- public void setEnabledProtocols(String[] protocols) {
- enabledProtocols = NativeCrypto.checkEnabledProtocols(protocols);
- }
-
- @Override
- public String[] getSupportedCipherSuites() {
- return NativeCrypto.getSupportedCipherSuites();
- }
-
- @Override
- public String[] getEnabledCipherSuites() {
- return enabledCipherSuites.clone();
- }
-
- /**
- * This method enables the cipher suites listed by
- * getSupportedCipherSuites().
- *
- * @param suites the names of all the cipher suites to enable
- * @throws IllegalArgumentException when one or more of the ciphers in array
- * suites are not supported, or when the array is null.
- */
- @Override
- public void setEnabledCipherSuites(String[] suites) {
- enabledCipherSuites = NativeCrypto.checkEnabledCipherSuites(suites);
- }
-
- @Override
- public boolean getWantClientAuth() {
- return sslParameters.getWantClientAuth();
- }
-
- @Override
- public void setWantClientAuth(boolean want) {
- sslParameters.setWantClientAuth(want);
- }
-
- @Override
- public boolean getNeedClientAuth() {
- return sslParameters.getNeedClientAuth();
- }
-
- @Override
- public void setNeedClientAuth(boolean need) {
- sslParameters.setNeedClientAuth(need);
- }
-
- @Override
- public void setUseClientMode(boolean mode) {
- sslParameters.setUseClientMode(mode);
- }
-
- @Override
- public boolean getUseClientMode() {
- return sslParameters.getUseClientMode();
- }
-
- @Override
- public Socket accept() throws IOException {
- OpenSSLSocketImpl socket = new OpenSSLSocketImpl(sslParameters,
- enabledProtocols.clone(),
- enabledCipherSuites.clone());
- implAccept(socket);
- return socket;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSessionImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSessionImpl.java
deleted file mode 100644
index f42bcae..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSessionImpl.java
+++ /dev/null
@@ -1,483 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.IOException;
-import java.security.AccessControlContext;
-import java.security.AccessController;
-import java.security.Principal;
-import java.security.cert.Certificate;
-import java.security.cert.X509Certificate;
-import java.util.Iterator;
-import java.util.UnknownFormatConversionException;
-import java.util.Vector;
-
-import javax.net.ssl.SSLPeerUnverifiedException;
-import javax.net.ssl.SSLPermission;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSessionBindingEvent;
-import javax.net.ssl.SSLSessionBindingListener;
-import javax.net.ssl.SSLSessionContext;
-import javax.security.cert.CertificateEncodingException;
-
-import org.apache.harmony.luni.util.TwoKeyHashMap;
-import org.apache.harmony.security.provider.cert.X509CertImpl;
-
-/**
- * Implementation of the class OpenSSLSessionImpl
- * based on OpenSSL. The JNI native interface for some methods
- * of this this class are defined in the file:
- * org_apache_harmony_xnet_provider_jsse_NativeCrypto.cpp
- */
-public class OpenSSLSessionImpl implements SSLSession {
-
- long lastAccessedTime = 0;
- X509Certificate[] localCertificates;
- X509Certificate[] peerCertificates;
-
- private boolean isValid = true;
- private TwoKeyHashMap values = new TwoKeyHashMap();
- private javax.security.cert.X509Certificate[] peerCertificateChain;
- protected int sslSessionNativePointer;
- private String peerHost;
- private int peerPort;
- private AbstractSessionContext sessionContext;
- private byte[] id;
-
- /**
- * Class constructor creates an SSL session context given the appropriate
- * SSL parameters.
- *
- * @param session the Identifier for SSL session
- * @param sslParameters the SSL parameters like ciphers' suites etc.
- */
- protected OpenSSLSessionImpl(int sslSessionNativePointer, X509Certificate[] localCertificates,
- String peerHost, int peerPort, AbstractSessionContext sessionContext) {
- this.sslSessionNativePointer = sslSessionNativePointer;
- this.localCertificates = localCertificates;
- this.peerHost = peerHost;
- this.peerPort = peerPort;
- this.sessionContext = sessionContext;
- }
-
- /**
- * Constructs a session from a byte[] containing DER data. This
- * allows loading the saved session.
- * @throws IOException
- */
- OpenSSLSessionImpl(byte[] derData,
- String peerHost, int peerPort,
- javax.security.cert.X509Certificate[] peerCertificateChain,
- AbstractSessionContext sessionContext)
- throws IOException {
- this(initializeNativeImpl(derData, derData.length),
- null,
- peerHost,
- peerPort,
- sessionContext);
- this.peerCertificateChain = peerCertificateChain;
- // TODO move this check into native code so we can throw an error with more information
- if (this.sslSessionNativePointer == 0) {
- throw new IOException("Invalid session data");
- }
- }
-
- private static native int initializeNativeImpl(byte[] data, int size);
-
- /**
- * Gets the identifier of the actual SSL session
- * @return array of sessions' identifiers.
- */
- public byte[] getId() {
- if (id == null) {
- resetId();
- }
- return id;
- }
-
- public static native byte[] getId(int sslSessionNativePointer);
-
- void resetId() {
- id = getId(sslSessionNativePointer);
- }
-
- /**
- * Get the session object in DER format. This allows saving the session
- * data or sharing it with other processes.
- */
- byte[] getEncoded() {
- return getEncoded(sslSessionNativePointer);
- }
-
- private native static byte[] getEncoded(int sslSessionNativePointer);
-
- /**
- * Gets the creation time of the SSL session.
- * @return the session's creation time in milliseconds since the epoch
- */
- public long getCreationTime() {
- return getCreationTime(sslSessionNativePointer);
- }
-
- private static native long getCreationTime(int sslSessionNativePointer);
-
- /**
- * Gives the last time this concrete SSL session was accessed. Accessing
- * here is to mean that a new connection with the same SSL context data was
- * established.
- *
- * @return the session's last access time in milliseconds since the epoch
- */
- public long getLastAccessedTime() {
- return (lastAccessedTime == 0) ? getCreationTime() : lastAccessedTime;
- }
-
- /**
- * Gives the largest buffer size for the application's data bound to this
- * concrete SSL session.
- * @return the largest buffer size
- */
- public int getApplicationBufferSize() {
- return SSLRecordProtocol.MAX_DATA_LENGTH;
- }
-
- /**
- * Gives the largest SSL/TLS packet size one can expect for this concrete
- * SSL session.
- * @return the largest packet size
- */
- public int getPacketBufferSize() {
- return SSLRecordProtocol.MAX_SSL_PACKET_SIZE;
- }
-
- /**
- * Gives the principal (subject) of this concrete SSL session used in the
- * handshaking phase of the connection.
- * @return a X509 certificate or null if no principal was defined
- */
- public Principal getLocalPrincipal() {
- if (localCertificates != null && localCertificates.length > 0) {
- return localCertificates[0].getSubjectX500Principal();
- } else {
- return null;
- }
- }
-
- /**
- * Gives the certificate(s) of the principal (subject) of this concrete SSL
- * session used in the handshaking phase of the connection. The OpenSSL
- * native method supports only RSA certificates.
- * @return an array of certificates (the local one first and then eventually
- * that of the certification authority) or null if no certificate
- * were used during the handshaking phase.
- */
- public Certificate[] getLocalCertificates() {
- return localCertificates;
- }
-
- /**
- * Returns the X509 certificates of the peer in the PEM format.
- */
- private static native byte[][] getPeerCertificatesImpl(int sslCtxNativePointer,
- int sslSessionNativePointer);
-
- /**
- * Gives the certificate(s) of the peer in this SSL session
- * used in the handshaking phase of the connection.
- * Please notice hat this method is superseded by
- * <code>getPeerCertificates()</code>.
- * @return an array of X509 certificates (the peer's one first and then
- * eventually that of the certification authority) or null if no
- * certificate were used during the SSL connection.
- * @throws <code>SSLPeerUnverifiedCertificateException</code> if either a
- * not X509 certificate was used (i.e. Kerberos certificates) or the
- * peer could not be verified.
- */
- public javax.security.cert.X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException {
- if (peerCertificateChain == null) {
- try {
- byte[][] bytes = getPeerCertificatesImpl(sessionContext.sslCtxNativePointer, sslSessionNativePointer);
- if (bytes == null) throw new SSLPeerUnverifiedException("No certificate available");
-
- peerCertificateChain = new javax.security.cert.X509Certificate[bytes.length];
-
- for(int i = 0; i < bytes.length; i++) {
- peerCertificateChain[i] = javax.security.cert.X509Certificate.getInstance(bytes[i]);
- }
-
- return peerCertificateChain;
- } catch (javax.security.cert.CertificateException e) {
- throw new SSLPeerUnverifiedException(e.getMessage());
- }
- } else {
- return peerCertificateChain;
- }
- }
-
- /**
- * Gives the identitity of the peer in this SSL session
- * determined via certificate(s).
- * @return an array of X509 certificates (the peer's one first and then
- * eventually that of the certification authority) or null if no
- * certificate were used during the SSL connection.
- * @throws <code>SSLPeerUnverifiedException</code> if either a not X509
- * certificate was used (i.e. Kerberos certificates) or the peer
- * could not be verified.
- */
- public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException {
- if (peerCertificates == null) {
- if (peerCertificateChain == null) getPeerCertificateChain();
- try {
- if (peerCertificateChain.length == 0) return new X509Certificate[]{};
-
- peerCertificates = new X509CertImpl[peerCertificateChain.length];
- for(int i = 0; i < peerCertificates.length; i++) {
- peerCertificates[i] = new X509CertImpl(peerCertificateChain[i].getEncoded());
- }
- return peerCertificates;
- } catch (SSLPeerUnverifiedException e) {
- return new X509Certificate[]{};
- } catch (IOException e) {
- return new X509Certificate[]{};
- } catch (CertificateEncodingException e) {
- return new X509Certificate[]{};
- }
- } else {
- return peerCertificates;
- }
- }
-
- /**
- * The identity of the principal that was used by the peer during the SSL
- * handshake phase is returned by this method.
- * @return a X500Principal of the last certificate for X509-based
- * cipher suites. If no principal was sent, then null is returned.
- * @throws <code>SSLPeerUnverifiedException</code> if either a not X509
- * certificate was used (i.e. Kerberos certificates) or the
- * peer does not exist.
- *
- */
- public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
- getPeerCertificates();
- if (peerCertificates == null) {
- throw new SSLPeerUnverifiedException("No peer certificate");
- }
- return peerCertificates[0].getSubjectX500Principal();
- }
-
- /**
- * The peer's host name used in this SSL session is returned. It is the host
- * name of the client for the server; and that of the server for the client.
- * It is not a reliable way to get a fully qualified host name: it is mainly
- * used internally to implement links for a temporary cache of SSL sessions.
- *
- * @return the host name of the peer, or null if no information is
- * available.
- *
- */
- public String getPeerHost() {
- return peerHost;
- }
-
- /**
- * Gives the peer's port number for the actual SSL session. It is the port
- * number of the client for the server; and that of the server for the
- * client. It is not a reliable way to get a peer's port number: it is
- * mainly used internally to implement links for a temporary cache of SSL
- * sessions.
- * @return the peer's port number, or -1 if no one is available.
- *
- */
- public int getPeerPort() {
- return peerPort;
- }
-
- /**
- * Gives back a string identifier of the crypto tools used in the actual SSL
- * session. For example AES_256_WITH_MD5.
- *
- * @return an identifier for all the cryptographic algorithms used in the
- * actual SSL session.
- */
- public String getCipherSuite() {
- return getCipherSuite(sslSessionNativePointer);
- }
-
- private static native String getCipherSuite(int sslSessionNativePointer);
-
- /**
- * Gives back the standard version name of the SSL protocol used in all
- * connections pertaining to this SSL session.
- *
- * @return the standard version name of the SSL protocol used in all
- * connections pertaining to this SSL session.
- *
- */
- public String getProtocol() {
- return getProtocol(sslSessionNativePointer);
- }
-
- private static native String getProtocol(int sslSessionNativePointer);
-
- /**
- * Gives back the context to which the actual SSL session is bound. A SSL
- * context consists of (1) a possible delegate, (2) a provider and (3) a
- * protocol. If the security manager is activated and one tries to access
- * the SSL context an exception may be thrown if a
- * <code>SSLPermission("getSSLSessionContext")</code>
- * permission is not set.
- * @return the SSL context used for this session, or null if it is
- * unavailable.
- */
- public SSLSessionContext getSessionContext() {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(new SSLPermission("getSSLSessionContext"));
- }
- return sessionContext;
- }
-
- /**
- * Gives back a boolean flag signaling whether a SSL session is valid and
- * available
- * for resuming or joining or not.
- * @return true if this session may be resumed.
- */
- public boolean isValid() {
- SSLSessionContext context = sessionContext;
- if (isValid
- && context != null
- && context.getSessionTimeout() != 0
- && lastAccessedTime + context.getSessionTimeout() > System.currentTimeMillis()) {
- isValid = false;
- }
- return isValid;
- }
-
- /**
- * It invalidates a SSL session forbidding any resumption.
- */
- public void invalidate() {
- isValid = false;
- sessionContext = null;
- }
-
- /**
- * Gives back the object which is bound to the the input parameter name.
- * This name is a sort of link to the data of the SSL session's application
- * layer, if any exists. The search for this link is monitored, as a matter
- * of security, by the full machinery of the <code>AccessController</code>
- * class.
- *
- * @param name the name of the binding to find.
- * @return the value bound to that name, or null if the binding does not
- * exist.
- * @throws <code>IllegalArgumentException</code> if the argument is null.
- */
- public Object getValue(String name) {
- if (name == null) {
- throw new IllegalArgumentException("Parameter is null");
- }
- return values.get(name, AccessController.getContext());
- }
-
- /**
- * Gives back an array with the names (sort of links) of all the data
- * objects of the application layer bound into the SSL session. The search
- * for this link is monitored, as a matter of security, by the full
- * machinery of the <code>AccessController</code> class.
- *
- * @return a non-null (possibly empty) array of names of the data objects
- * bound to this SSL session.
- */
- public String[] getValueNames() {
- Vector v = new Vector();
- AccessControlContext current = AccessController.getContext();
- AccessControlContext cont;
- for (Iterator it = values.entrySet().iterator(); it.hasNext();) {
- TwoKeyHashMap.Entry entry = (TwoKeyHashMap.Entry) it.next();
- cont = (AccessControlContext) entry.getKey2();
- if ((current == null && cont == null)
- || (current != null && current.equals(cont))) {
- v.add(entry.getKey1());
- }
- }
- return (String[]) v.toArray(new String[0]);
- }
-
- /**
- * A link (name) with the specified value object of the SSL session's
- * application layer data is created or replaced. If the new (or existing)
- * value object implements the <code>SSLSessionBindingListener</code>
- * interface, that object will be notified in due course. These links-to
- * -data bounds are monitored, as a matter of security, by the full
- * machinery of the <code>AccessController</code> class.
- *
- * @param name the name of the link (no null are
- * accepted!)
- * @param value data object that shall be bound to
- * name.
- * @throws <code>IllegalArgumentException</code> if one or both
- * argument(s) is null.
- */
- public void putValue(String name, Object value) {
- if (name == null || value == null) {
- throw new IllegalArgumentException("Parameter is null");
- }
- Object old = values.put(name, AccessController.getContext(), value);
- if (value instanceof SSLSessionBindingListener) {
- ((SSLSessionBindingListener) value)
- .valueBound(new SSLSessionBindingEvent(this, name));
- }
- if (old instanceof SSLSessionBindingListener) {
- ((SSLSessionBindingListener) old)
- .valueUnbound(new SSLSessionBindingEvent(this, name));
- }
- }
-
- /**
- * Removes a link (name) with the specified value object of the SSL
- * session's application layer data.
- *
- * <p>If the value object implements the <code>SSLSessionBindingListener</code>
- * interface, the object will receive a <code>valueUnbound</code> notification.
- *
- * <p>These links-to -data bounds are
- * monitored, as a matter of security, by the full machinery of the
- * <code>AccessController</code> class.
- *
- * @param name the name of the link (no null are
- * accepted!)
- * @throws <code>IllegalArgumentException</code> if the argument is null.
- */
- public void removeValue(String name) {
- if (name == null) {
- throw new IllegalArgumentException("Parameter is null");
- }
- Object old = values.remove(name, AccessController.getContext());
- if (old instanceof SSLSessionBindingListener) {
- SSLSessionBindingListener listener = (SSLSessionBindingListener) old;
- listener.valueUnbound(new SSLSessionBindingEvent(this, name));
- }
- }
-
- protected void finalize() {
- freeImpl(sslSessionNativePointer);
- }
-
- public static native void freeImpl(int session);
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSignature.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSignature.java
deleted file mode 100644
index 3db6301..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSignature.java
+++ /dev/null
@@ -1,215 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.security.InvalidKeyException;
-import java.security.InvalidParameterException;
-import java.security.NoSuchAlgorithmException;
-import java.security.PrivateKey;
-import java.security.PublicKey;
-import java.security.Signature;
-import java.security.SignatureException;
-import java.security.interfaces.DSAParams;
-import java.security.interfaces.DSAPublicKey;
-import java.security.interfaces.RSAPublicKey;
-
-/**
- * Implements the JDK MessageDigest interface using OpenSSL's EVP API.
- */
-public class OpenSSLSignature extends Signature {
-
- /**
- * Holds a pointer to the native message digest context.
- */
- private int ctx;
-
- /**
- * Holds a pointer to the native DSA key.
- */
- private int dsa;
-
- /**
- * Holds a pointer to the native RSA key.
- */
- private int rsa;
-
- /**
- * Holds the OpenSSL name of the algorithm (lower case, no dashes).
- */
- private String evpAlgorithm;
-
- /**
- * Holds a dummy buffer for writing single bytes to the digest.
- */
- private byte[] singleByte = new byte[1];
-
- /**
- * Creates a new OpenSSLSignature instance for the given algorithm name.
- *
- * @param algorithm The name of the algorithm, e.g. "SHA1".
- *
- * @return The new OpenSSLSignature instance.
- *
- * @throws RuntimeException In case of problems.
- */
- public static OpenSSLSignature getInstance(String algorithm) throws NoSuchAlgorithmException {
- //log("OpenSSLSignature", "getInstance() invoked with " + algorithm);
- return new OpenSSLSignature(algorithm);
- }
-
- /**
- * Creates a new OpenSSLSignature instance for the given algorithm name.
- *
- * @param algorithm The name of the algorithm, e.g. "SHA1".
- */
- private OpenSSLSignature(String algorithm) throws NoSuchAlgorithmException {
- super(algorithm);
-
- int i = algorithm.indexOf("with");
- if (i == -1) {
- throw new NoSuchAlgorithmException(algorithm);
- }
-
- // We don't support MD2 anymore. This needs to also check for aliases
- // and OIDs.
- if ("MD2withRSA".equalsIgnoreCase(algorithm) ||
- "MD2withRSAEncryption".equalsIgnoreCase(algorithm) ||
- "1.2.840.113549.1.1.2".equalsIgnoreCase(algorithm) ||
- "MD2/RSA".equalsIgnoreCase(algorithm)) {
- throw new NoSuchAlgorithmException("MD2withRSA");
- }
-
- // For the special combination of DSA and SHA1, we need to pass the
- // algorithm name as a pair consisting of crypto algorithm and hash
- // algorithm. For all other (RSA) cases, passing the hash algorithm
- // alone is not only sufficient, but actually necessary. OpenSSL
- // doesn't accept something like RSA-SHA1.
- if ("1.3.14.3.2.26with1.2.840.10040.4.1".equals(algorithm)
- || "SHA1withDSA".equals(algorithm)
- || "SHAwithDSA".equals(algorithm)) {
- evpAlgorithm = "DSA-SHA";
- } else {
- evpAlgorithm = algorithm.substring(0, i).replace("-", "").toUpperCase();
- }
-
- ctx = NativeCrypto.EVP_new();
- }
-
- @Override
- protected void engineUpdate(byte input) {
- singleByte[0] = input;
- engineUpdate(singleByte, 0, 1);
- }
-
- @Override
- protected void engineUpdate(byte[] input, int offset, int len) {
- if (state == SIGN) {
- throw new UnsupportedOperationException();
- } else {
- NativeCrypto.EVP_VerifyUpdate(ctx, input, offset, len);
- }
- }
-
- @Override
- protected Object engineGetParameter(String param) throws InvalidParameterException {
- return null;
- }
-
- @Override
- protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- protected void engineInitVerify(PublicKey publicKey) throws InvalidKeyException {
- //log("OpenSSLSignature", "engineInitVerify() invoked with " + publicKey.getClass().getCanonicalName());
-
- if (publicKey instanceof DSAPublicKey) {
- try {
- DSAPublicKey dsaPublicKey = (DSAPublicKey)publicKey;
- DSAParams dsaParams = dsaPublicKey.getParams();
- dsa = NativeCrypto.EVP_PKEY_new_DSA(dsaParams.getP().toByteArray(),
- dsaParams.getQ().toByteArray(), dsaParams.getG().toByteArray(),
- dsaPublicKey.getY().toByteArray(), null);
-
- } catch (Exception ex) {
- throw new InvalidKeyException(ex.toString());
- }
- } else if (publicKey instanceof RSAPublicKey) {
- try {
- RSAPublicKey rsaPublicKey = (RSAPublicKey)publicKey;
- rsa = NativeCrypto.EVP_PKEY_new_RSA(rsaPublicKey.getModulus().toByteArray(),
- rsaPublicKey.getPublicExponent().toByteArray(), null, null, null);
-
- } catch (Exception ex) {
- throw new InvalidKeyException(ex.toString());
- }
- } else {
- throw new InvalidKeyException("Need DSA or RSA public key");
- }
-
- try {
- NativeCrypto.EVP_VerifyInit(ctx, evpAlgorithm);
- } catch (Exception ex) {
- throw new RuntimeException(ex);
- }
- }
-
- @Override
- protected void engineSetParameter(String param, Object value) throws InvalidParameterException {
- }
-
- @Override
- protected byte[] engineSign() throws SignatureException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- protected boolean engineVerify(byte[] sigBytes) throws SignatureException {
- int handle = (rsa != 0) ? rsa : dsa;
-
- if (handle == 0) {
- // This can't actually happen, but you never know...
- throw new SignatureException("Need DSA or RSA public key");
- }
-
- try {
- int result = NativeCrypto.EVP_VerifyFinal(ctx, sigBytes, 0, sigBytes.length, handle);
- return result == 1;
- } catch (Exception ex) {
- throw new SignatureException(ex);
- }
-
- }
-
- @Override
- protected void finalize() throws Throwable {
- super.finalize();
-
- if (dsa != 0) {
- NativeCrypto.EVP_PKEY_free(dsa);
- }
-
- if (rsa != 0) {
- NativeCrypto.EVP_PKEY_free(rsa);
- }
-
- if (ctx != 0) {
- NativeCrypto.EVP_free(ctx);
- }
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketFactoryImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketFactoryImpl.java
deleted file mode 100644
index 7b6d7c8..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketFactoryImpl.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.net.UnknownHostException;
-import java.security.KeyManagementException;
-
-import org.apache.harmony.xnet.provider.jsse.SSLParameters;
-
-public class OpenSSLSocketFactoryImpl extends javax.net.ssl.SSLSocketFactory {
-
- private SSLParameters sslParameters;
- private IOException instantiationException;
-
- public OpenSSLSocketFactoryImpl() {
- super();
- try {
- sslParameters = SSLParameters.getDefault();
- } catch (KeyManagementException e) {
- instantiationException =
- new IOException("Delayed instantiation exception:");
- instantiationException.initCause(e);
- }
- }
-
- public OpenSSLSocketFactoryImpl(SSLParameters sslParameters) {
- super();
- this.sslParameters = sslParameters;
- }
-
- public String[] getDefaultCipherSuites() {
- return NativeCrypto.getDefaultCipherSuites();
- }
-
- public String[] getSupportedCipherSuites() {
- return NativeCrypto.getSupportedCipherSuites();
- }
-
- public Socket createSocket() throws IOException {
- if (instantiationException != null) {
- throw instantiationException;
- }
- return new OpenSSLSocketImpl((SSLParameters) sslParameters.clone());
- }
-
- public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
- return new OpenSSLSocketImpl(host, port, (SSLParameters) sslParameters.clone());
- }
-
- public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
- throws IOException, UnknownHostException {
- return new OpenSSLSocketImpl(host, port, localHost, localPort, (SSLParameters) sslParameters.clone());
- }
-
- public Socket createSocket(InetAddress host, int port) throws IOException {
- return new OpenSSLSocketImpl(host, port, (SSLParameters) sslParameters.clone());
- }
-
- public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)
- throws IOException {
- return new OpenSSLSocketImpl(address, port, localAddress, localPort, (SSLParameters) sslParameters.clone());
- }
-
- public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
- return new OpenSSLSocketImplWrapper(s, host, port, autoClose, (SSLParameters) sslParameters.clone());
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImpl.java
deleted file mode 100644
index edef590..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImpl.java
+++ /dev/null
@@ -1,995 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.Socket;
-import java.net.SocketException;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-import java.security.interfaces.RSAPublicKey;
-import java.util.ArrayList;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import javax.net.ssl.HandshakeCompletedEvent;
-import javax.net.ssl.HandshakeCompletedListener;
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLHandshakeException;
-import javax.net.ssl.SSLPeerUnverifiedException;
-import javax.net.ssl.SSLSession;
-
-import org.apache.harmony.security.provider.cert.X509CertImpl;
-
-/**
- * Implementation of the class OpenSSLSocketImpl
- * based on OpenSSL. The JNI native interface for some methods
- * of this this class are defined in the file:
- * org_apache_harmony_xnet_provider_jsse_NativeCrypto.cpp
- *
- * This class only supports SSLv3 and TLSv1. This should be documented elsewhere
- * later, for example in the package.html or a separate reference document.
- */
-public class OpenSSLSocketImpl
- extends javax.net.ssl.SSLSocket
- implements NativeCrypto.CertificateChainVerifier, NativeCrypto.HandshakeCompletedCallback {
- private int sslNativePointer;
- private InputStream is;
- private OutputStream os;
- private final Object handshakeLock = new Object();
- private final Object readLock = new Object();
- private final Object writeLock = new Object();
- private SSLParameters sslParameters;
- private String[] enabledProtocols;
- private String[] enabledCipherSuites;
- private OpenSSLSessionImpl sslSession;
- private Socket socket;
- private boolean autoClose;
- private boolean handshakeStarted = false;
-
- /**
- * Not set to true until the update from native that tells us the
- * full handshake is complete, since SSL_do_handshake can return
- * before the handshake is completely done due to
- * handshake_cutthrough support.
- */
- private boolean handshakeCompleted = false;
-
- private ArrayList<HandshakeCompletedListener> listeners;
- private int timeout = 0;
- // BEGIN android-added
- private int handshakeTimeout = -1; // -1 = same as timeout; 0 = infinite
- // END android-added
- private InetSocketAddress address;
-
- private static final AtomicInteger instanceCount = new AtomicInteger(0);
-
- public static int getInstanceCount() {
- return instanceCount.get();
- }
-
- private static void updateInstanceCount(int amount) {
- instanceCount.addAndGet(amount);
- }
-
- /**
- * Class constructor with 1 parameter
- *
- * @param sslParameters Parameters for the SSL
- * context
- * @throws IOException if network fails
- */
- protected OpenSSLSocketImpl(SSLParameters sslParameters) throws IOException {
- super();
- init(sslParameters);
- }
-
- /**
- * Create an OpenSSLSocketImpl from an OpenSSLServerSocketImpl
- *
- * @param sslParameters Parameters for the SSL
- * context
- * @throws IOException if network fails
- */
- protected OpenSSLSocketImpl(SSLParameters sslParameters,
- String[] enabledProtocols,
- String[] enabledCipherSuites) throws IOException {
- super();
- init(sslParameters, enabledProtocols, enabledCipherSuites);
- }
-
- /**
- * Class constructor with 3 parameters
- *
- * @throws IOException if network fails
- * @throws java.net.UnknownHostException host not defined
- */
- protected OpenSSLSocketImpl(String host, int port,
- SSLParameters sslParameters)
- throws IOException {
- super(host, port);
- init(sslParameters);
- }
-
- /**
- * Class constructor with 3 parameters: 1st is InetAddress
- *
- * @throws IOException if network fails
- * @throws java.net.UnknownHostException host not defined
- */
- protected OpenSSLSocketImpl(InetAddress address, int port,
- SSLParameters sslParameters)
- throws IOException {
- super(address, port);
- init(sslParameters);
- }
-
-
- /**
- * Class constructor with 5 parameters: 1st is host
- *
- * @throws IOException if network fails
- * @throws java.net.UnknownHostException host not defined
- */
- protected OpenSSLSocketImpl(String host, int port, InetAddress clientAddress,
- int clientPort, SSLParameters sslParameters)
- throws IOException {
- super(host, port, clientAddress, clientPort);
- init(sslParameters);
- }
-
- /**
- * Class constructor with 5 parameters: 1st is InetAddress
- *
- * @throws IOException if network fails
- * @throws java.net.UnknownHostException host not defined
- */
- protected OpenSSLSocketImpl(InetAddress address, int port,
- InetAddress clientAddress, int clientPort, SSLParameters sslParameters)
- throws IOException {
- super(address, port, clientAddress, clientPort);
- init(sslParameters);
- }
-
- /**
- * Constructor with 5 parameters: 1st is socket. Enhances an existing socket
- * with SSL functionality.
- *
- * @throws IOException if network fails
- */
- protected OpenSSLSocketImpl(Socket socket, String host, int port,
- boolean autoClose, SSLParameters sslParameters) throws IOException {
- super();
- this.socket = socket;
- this.timeout = socket.getSoTimeout();
- this.address = new InetSocketAddress(host, port);
- this.autoClose = autoClose;
- init(sslParameters);
- }
-
- /**
- * Initialize the SSL socket and set the certificates for the
- * future handshaking.
- */
- private void init(SSLParameters sslParameters) throws IOException {
- init(sslParameters,
- NativeCrypto.getSupportedProtocols(),
- NativeCrypto.getDefaultCipherSuites());
- }
-
- /**
- * Initialize the SSL socket and set the certificates for the
- * future handshaking.
- */
- private void init(SSLParameters sslParameters,
- String[] enabledProtocols,
- String[] enabledCipherSuites) throws IOException {
- this.sslParameters = sslParameters;
- this.enabledProtocols = enabledProtocols;
- this.enabledCipherSuites = enabledCipherSuites;
- updateInstanceCount(1);
- }
-
- /**
- * Gets the suitable session reference from the session cache container.
- *
- * @return OpenSSLSessionImpl
- */
- private OpenSSLSessionImpl getCachedClientSession(ClientSessionContext sessionContext) {
- if (super.getInetAddress() == null ||
- super.getInetAddress().getHostAddress() == null ||
- super.getInetAddress().getHostName() == null) {
- return null;
- }
- return (OpenSSLSessionImpl) sessionContext.getSession(
- super.getInetAddress().getHostName(),
- super.getPort());
- }
-
- /**
- * Ensures that logger is lazily loaded. The outer class seems to load
- * before logging is ready.
- */
- static class LoggerHolder {
- static final Logger logger = Logger.getLogger(OpenSSLSocketImpl.class.getName());
- }
-
- /**
- * Starts a TLS/SSL handshake on this connection using some native methods
- * from the OpenSSL library. It can negotiate new encryption keys, change
- * cipher suites, or initiate a new session. The certificate chain is
- * verified if the correspondent property in java.Security is set. All
- * listeners are notified at the end of the TLS/SSL handshake.
- *
- * @throws <code>IOException</code> if network fails
- */
- public void startHandshake() throws IOException {
- startHandshake(true);
- }
-
- /**
- * Perform the handshake
- * @param full If true, disable handshake cutthrough for a fully synchronous handshake
- */
- public synchronized void startHandshake(boolean full) throws IOException {
- synchronized (handshakeLock) {
- if (!handshakeStarted) {
- handshakeStarted = true;
- } else {
- return;
- }
- }
-
- this.sslNativePointer = NativeCrypto.SSL_new(sslParameters);
- // TODO move more code out of NativeCrypto.SSL_new
- NativeCrypto.setEnabledProtocols(sslNativePointer, enabledProtocols);
- NativeCrypto.setEnabledCipherSuites(sslNativePointer, enabledCipherSuites);
-
- boolean enableSessionCreation = sslParameters.getEnableSessionCreation();
- if (!enableSessionCreation) {
- NativeCrypto.SSL_set_session_creation_enabled(sslNativePointer,
- enableSessionCreation);
- }
-
- boolean client = sslParameters.getUseClientMode();
-
- AbstractSessionContext sessionContext;
- OpenSSLSessionImpl session;
- if (client) {
- // look for client session to reuse
- ClientSessionContext clientSessionContext = sslParameters.getClientSessionContext();
- sessionContext = clientSessionContext;
- session = getCachedClientSession(clientSessionContext);
- if (session != null) {
- NativeCrypto.SSL_set_session(sslNativePointer, session.sslSessionNativePointer);
- }
- } else {
- sessionContext = sslParameters.getServerSessionContext();
- session = null;
- }
-
- // setup peer certificate verification
- if (client) {
- // TODO support for anonymous cipher would require us to conditionally use SSL_VERIFY_NONE
- } else {
- // needing client auth takes priority...
- if (sslParameters.getNeedClientAuth()) {
- NativeCrypto.SSL_set_verify(sslNativePointer,
- NativeCrypto.SSL_VERIFY_PEER|
- NativeCrypto.SSL_VERIFY_FAIL_IF_NO_PEER_CERT|
- NativeCrypto.SSL_VERIFY_CLIENT_ONCE);
- // ... over just wanting it...
- } else if (sslParameters.getWantClientAuth()) {
- NativeCrypto.SSL_set_verify(sslNativePointer,
- NativeCrypto.SSL_VERIFY_PEER|
- NativeCrypto.SSL_VERIFY_CLIENT_ONCE);
- }
- // ... and it defaults properly so we don't need call SSL_set_verify in the common case.
- }
-
- if (client && full) {
- // we want to do a full synchronous handshake, so turn off cutthrough
- NativeCrypto.SSL_clear_mode(sslNativePointer, NativeCrypto.SSL_MODE_HANDSHAKE_CUTTHROUGH);
- }
-
- // BEGIN android-added
- // Temporarily use a different timeout for the handshake process
- int savedTimeout = timeout;
- if (handshakeTimeout >= 0) {
- setSoTimeout(handshakeTimeout);
- }
- // END android-added
-
-
- Socket socket = this.socket != null ? this.socket : this;
- int sslSessionNativePointer;
- try {
- sslSessionNativePointer = NativeCrypto.SSL_do_handshake(sslNativePointer, socket, this, this, timeout, client);
- } catch (CertificateException e) {
- throw new SSLPeerUnverifiedException(e.getMessage());
- }
- byte[] sessionId = OpenSSLSessionImpl.getId(sslSessionNativePointer);
- sslSession = (OpenSSLSessionImpl) sessionContext.getSession(sessionId);
- if (sslSession != null) {
- session.lastAccessedTime = System.currentTimeMillis();
- LoggerHolder.logger.fine("Reused cached session for "
- + getInetAddress() + ".");
- OpenSSLSessionImpl.freeImpl(sslSessionNativePointer);
- } else {
- if (!enableSessionCreation) {
- // Should have been prevented by NativeCrypto.SSL_set_session_creation_enabled
- throw new IllegalStateException("SSL Session may not be created");
- }
- byte[][] localCertificatesBytes = NativeCrypto.SSL_get_certificate(sslNativePointer);
- X509Certificate[] localCertificates;
- if (localCertificatesBytes == null) {
- localCertificates = null;
- } else {
- localCertificates = new X509Certificate[localCertificatesBytes.length];
- for (int i = 0; i < localCertificatesBytes.length; i++) {
- try {
- // TODO do not go through PEM decode, DER encode, DER decode
- localCertificates[i]
- = new X509CertImpl(
- javax.security.cert.X509Certificate.getInstance(
- localCertificatesBytes[i]).getEncoded());
- } catch (javax.security.cert.CertificateException e) {
- throw new IOException("Problem decoding local certificate", e);
- }
- }
- }
-
- if (address == null) {
- sslSession = new OpenSSLSessionImpl(sslSessionNativePointer, localCertificates,
- super.getInetAddress().getHostName(),
- super.getPort(), sessionContext);
- } else {
- sslSession = new OpenSSLSessionImpl(sslSessionNativePointer, localCertificates,
- address.getHostName(), address.getPort(),
- sessionContext);
- }
- // putSession will be done later in handshakeCompleted() callback
- if (handshakeCompleted) {
- sessionContext.putSession(sslSession);
- }
- LoggerHolder.logger.fine("Created new session for "
- + getInetAddress().getHostName() + ".");
- }
-
- // BEGIN android-added
- // Restore the original timeout now that the handshake is complete
- if (handshakeTimeout >= 0) {
- setSoTimeout(savedTimeout);
- }
- // END android-added
-
- // notifyHandshakeCompletedListeners will be done later in handshakeCompleted() callback
- if (handshakeCompleted) {
- notifyHandshakeCompletedListeners();
- }
-
- }
-
- /**
- * Implementation of NativeCrypto.HandshakeCompletedCallback
- * invoked via JNI from info_callback
- */
- public void handshakeCompleted() {
- handshakeCompleted = true;
-
- // If sslSession is null, the handshake was completed during
- // the call to NativeCrypto.SSL_do_handshake and not during a
- // later read operation. That means we do not need to fixup
- // the SSLSession and session cache or notify
- // HandshakeCompletedListeners, it will be done in
- // startHandshake.
- if (sslSession == null) {
- return;
- }
-
- // reset session id from the native pointer and update the
- // appropriate cache.
- sslSession.resetId();
- AbstractSessionContext sessionContext =
- (sslParameters.getUseClientMode())
- ? sslParameters.getClientSessionContext()
- : sslParameters.getServerSessionContext();
- sessionContext.putSession(sslSession);
-
- // let listeners know we are finally done
- notifyHandshakeCompletedListeners();
- }
-
- private void notifyHandshakeCompletedListeners() {
- if (listeners != null && !listeners.isEmpty()) {
- // notify the listeners
- HandshakeCompletedEvent event =
- new HandshakeCompletedEvent(this, sslSession);
- for (HandshakeCompletedListener listener : listeners) {
- try {
- listener.handshakeCompleted(event);
- } catch (RuntimeException e) {
- // TODO log?
- }
- }
- }
- }
-
- /**
- * Implementation of NativeCrypto.CertificateChainVerifier.
- *
- * @param bytes An array of certficates in PEM encode bytes
- * @param authMethod auth algorithm name
- *
- * @throws CertificateException if the certificate is untrusted
- */
- @SuppressWarnings("unused")
- public void verifyCertificateChain(byte[][] bytes, String authMethod) throws CertificateException {
- try {
- X509Certificate[] peerCertificateChain = new X509Certificate[bytes.length];
- for (int i = 0; i < bytes.length; i++) {
- peerCertificateChain[i] =
- new X509CertImpl(javax.security.cert.X509Certificate.getInstance(bytes[i]).getEncoded());
- }
-
- boolean client = sslParameters.getUseClientMode();
- if (client) {
- if (peerCertificateChain == null
- || peerCertificateChain.length == 0) {
- throw new SSLException("Server sends no certificate");
- }
- sslParameters.getTrustManager().checkServerTrusted(peerCertificateChain, authMethod);
- } else {
- sslParameters.getTrustManager().checkClientTrusted(peerCertificateChain, authMethod);
- }
-
- } catch (CertificateException e) {
- throw e;
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Returns an input stream for this SSL socket using native calls to the
- * OpenSSL library.
- *
- * @return: an input stream for reading bytes from this socket.
- * @throws: <code>IOException</code> if an I/O error occurs when creating
- * the input stream, the socket is closed, the socket is not
- * connected, or the socket input has been shutdown.
- */
- public InputStream getInputStream() throws IOException {
- synchronized(this) {
- if (is == null) {
- is = new SSLInputStream();
- }
-
- return is;
- }
- }
-
- /**
- * Returns an output stream for this SSL socket using native calls to the
- * OpenSSL library.
- *
- * @return an output stream for writing bytes to this socket.
- * @throws <code>IOException</code> if an I/O error occurs when creating
- * the output stream, or no connection to the socket exists.
- */
- public OutputStream getOutputStream() throws IOException {
- synchronized(this) {
- if (os == null) {
- os = new SSLOutputStream();
- }
-
- return os;
- }
- }
-
- /**
- * This method is not supported for this SSLSocket implementation
- * because reading from an SSLSocket may involve writing to the
- * network.
- */
- public void shutdownInput() throws IOException {
- throw new UnsupportedOperationException();
- }
-
- /**
- * This method is not supported for this SSLSocket implementation
- * because writing to an SSLSocket may involve reading from the
- * network.
- */
- public void shutdownOutput() throws IOException {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Reads with the native SSL_read function from the encrypted data stream
- * @return -1 if error or the end of the stream is reached.
- */
- private native int nativeread(int sslNativePointer, int timeout) throws IOException;
- private native int nativeread(int sslNativePointer, byte[] b, int off, int len, int timeout) throws IOException;
-
- /**
- * This inner class provides input data stream functionality
- * for the OpenSSL native implementation. It is used to
- * read data received via SSL protocol.
- */
- private class SSLInputStream extends InputStream {
- SSLInputStream() throws IOException {
- /**
- /* Note: When startHandshake() throws an exception, no
- * SSLInputStream object will be created.
- */
- OpenSSLSocketImpl.this.startHandshake(false);
- }
-
- /**
- * Reads one byte. If there is no data in the underlying buffer,
- * this operation can block until the data will be
- * available.
- * @return read value.
- * @throws <code>IOException</code>
- */
- public int read() throws IOException {
- synchronized(readLock) {
- return OpenSSLSocketImpl.this.nativeread(sslNativePointer, timeout);
- }
- }
-
- /**
- * Method acts as described in spec for superclass.
- * @see java.io.InputStream#read(byte[],int,int)
- */
- public int read(byte[] b, int off, int len) throws IOException {
- synchronized(readLock) {
- return OpenSSLSocketImpl.this.nativeread(sslNativePointer, b, off, len, timeout);
- }
- }
- }
-
- /**
- * Writes with the native SSL_write function to the encrypted data stream.
- */
- private native void nativewrite(int sslNativePointer, int b) throws IOException;
- private native void nativewrite(int sslNativePointer, byte[] b, int off, int len) throws IOException;
-
- /**
- * This inner class provides output data stream functionality
- * for the OpenSSL native implementation. It is used to
- * write data according to the encryption parameters given in SSL context.
- */
- private class SSLOutputStream extends OutputStream {
- SSLOutputStream() throws IOException {
- /**
- /* Note: When startHandshake() throws an exception, no
- * SSLOutputStream object will be created.
- */
- OpenSSLSocketImpl.this.startHandshake(false);
- }
-
- /**
- * Method acts as described in spec for superclass.
- * @see java.io.OutputStream#write(int)
- */
- public void write(int b) throws IOException {
- synchronized(writeLock) {
- OpenSSLSocketImpl.this.nativewrite(sslNativePointer, b);
- }
- }
-
- /**
- * Method acts as described in spec for superclass.
- * @see java.io.OutputStream#write(byte[],int,int)
- */
- public void write(byte[] b, int start, int len) throws IOException {
- synchronized(writeLock) {
- OpenSSLSocketImpl.this.nativewrite(sslNativePointer, b, start, len);
- }
- }
- }
-
-
- /**
- * The SSL session used by this connection is returned. The SSL session
- * determines which cipher suite should be used by all connections within
- * that session and which identities have the session's client and server.
- * This method starts the SSL handshake.
- * @return the SSLSession.
- * @throws <code>IOException</code> if the handshake fails
- */
- public SSLSession getSession() {
- try {
- startHandshake(true);
- } catch (IOException e) {
- // return an invalid session with
- // invalid cipher suite of "SSL_NULL_WITH_NULL_NULL"
- return SSLSessionImpl.NULL_SESSION;
- }
- return sslSession;
- }
-
- /**
- * Registers a listener to be notified that a SSL handshake
- * was successfully completed on this connection.
- * @throws <code>IllegalArgumentException</code> if listener is null.
- */
- public void addHandshakeCompletedListener(
- HandshakeCompletedListener listener) {
- if (listener == null) {
- throw new IllegalArgumentException("Provided listener is null");
- }
- if (listeners == null) {
- listeners = new ArrayList();
- }
- listeners.add(listener);
- }
-
- /**
- * The method removes a registered listener.
- * @throws IllegalArgumentException if listener is null or not registered
- */
- public void removeHandshakeCompletedListener(
- HandshakeCompletedListener listener) {
- if (listener == null) {
- throw new IllegalArgumentException("Provided listener is null");
- }
- if (listeners == null) {
- throw new IllegalArgumentException(
- "Provided listener is not registered");
- }
- if (!listeners.remove(listener)) {
- throw new IllegalArgumentException(
- "Provided listener is not registered");
- }
- }
-
- /**
- * Returns true if new SSL sessions may be established by this socket.
- *
- * @return true if the session may be created; false if a session already
- * exists and must be resumed.
- */
- public boolean getEnableSessionCreation() {
- return sslParameters.getEnableSessionCreation();
- }
-
- /**
- * Set a flag for the socket to inhibit or to allow the creation of a new
- * SSL sessions. If the flag is set to false, and there are no actual
- * sessions to resume, then there will be no successful handshaking.
- *
- * @param flag true if session may be created; false
- * if a session already exists and must be resumed.
- */
- public void setEnableSessionCreation(boolean flag) {
- sslParameters.setEnableSessionCreation(flag);
- }
-
- /**
- * The names of the cipher suites which could be used by the SSL connection
- * are returned.
- * @return an array of cipher suite names
- */
- public String[] getSupportedCipherSuites() {
- return NativeCrypto.getSupportedCipherSuites();
- }
-
- /**
- * The names of the cipher suites that are in use in the actual the SSL
- * connection are returned.
- *
- * @return an array of cipher suite names
- */
- public String[] getEnabledCipherSuites() {
- return enabledCipherSuites.clone();
- }
-
- /**
- * This method enables the cipher suites listed by
- * getSupportedCipherSuites().
- *
- * @param suites names of all the cipher suites to
- * put on use
- * @throws IllegalArgumentException when one or more of the
- * ciphers in array suites are not supported, or when the array
- * is null.
- */
- public void setEnabledCipherSuites(String[] suites) {
- enabledCipherSuites = NativeCrypto.checkEnabledCipherSuites(suites);
- }
-
- /**
- * The names of the protocols' versions that may be used on this SSL
- * connection.
- * @return an array of protocols names
- */
- public String[] getSupportedProtocols() {
- return NativeCrypto.getSupportedProtocols();
- }
-
- /**
- * The names of the protocols' versions that are in use on this SSL
- * connection.
- *
- * @return an array of protocols names
- */
- @Override
- public String[] getEnabledProtocols() {
- return enabledProtocols.clone();
- }
-
- /**
- * This method enables the protocols' versions listed by
- * getSupportedProtocols().
- *
- * @param protocols The names of all the protocols to put on use
- *
- * @throws IllegalArgumentException when one or more of the names in the
- * array are not supported, or when the array is null.
- */
- @Override
- public synchronized void setEnabledProtocols(String[] protocols) {
- enabledProtocols = NativeCrypto.checkEnabledProtocols(protocols);
- }
-
- /**
- * This method gives true back if the SSL socket is set to client mode.
- *
- * @return true if the socket should do the handshaking as client.
- */
- public boolean getUseClientMode() {
- return sslParameters.getUseClientMode();
- }
-
- /**
- * This method set the actual SSL socket to client mode.
- *
- * @param mode true if the socket starts in client
- * mode
- * @throws IllegalArgumentException if mode changes during
- * handshake.
- */
- public synchronized void setUseClientMode(boolean mode) {
- if (handshakeStarted) {
- throw new IllegalArgumentException(
- "Could not change the mode after the initial handshake has begun.");
- }
- sslParameters.setUseClientMode(mode);
- }
-
- /**
- * Returns true if the SSL socket requests client's authentication. Relevant
- * only for server sockets!
- *
- * @return true if client authentication is desired, false if not.
- */
- public boolean getWantClientAuth() {
- return sslParameters.getWantClientAuth();
- }
-
- /**
- * Returns true if the SSL socket needs client's authentication. Relevant
- * only for server sockets!
- *
- * @return true if client authentication is desired, false if not.
- */
- public boolean getNeedClientAuth() {
- return sslParameters.getNeedClientAuth();
- }
-
- /**
- * Sets the SSL socket to use client's authentication. Relevant only for
- * server sockets!
- *
- * @param need true if client authentication is
- * desired, false if not.
- */
- public void setNeedClientAuth(boolean need) {
- sslParameters.setNeedClientAuth(need);
- }
-
- /**
- * Sets the SSL socket to use client's authentication. Relevant only for
- * server sockets! Notice that in contrast to setNeedClientAuth(..) this
- * method will continue the negotiation if the client decide not to send
- * authentication credentials.
- *
- * @param want true if client authentication is
- * desired, false if not.
- */
- public void setWantClientAuth(boolean want) {
- sslParameters.setWantClientAuth(want);
- }
-
- /**
- * This method is not supported for SSLSocket implementation.
- */
- public void sendUrgentData(int data) throws IOException {
- throw new SocketException(
- "Method sendUrgentData() is not supported.");
- }
-
- /**
- * This method is not supported for SSLSocket implementation.
- */
- public void setOOBInline(boolean on) throws SocketException {
- throw new SocketException(
- "Methods sendUrgentData, setOOBInline are not supported.");
- }
-
- /**
- * Set the read timeout on this socket. The SO_TIMEOUT option, is specified
- * in milliseconds. The read operation will block indefinitely for a zero
- * value.
- *
- * @param timeout the read timeout value
- * @throws SocketException if an error occurs setting the option
- */
- public synchronized void setSoTimeout(int timeout) throws SocketException {
- super.setSoTimeout(timeout);
- this.timeout = timeout;
- }
-
- // BEGIN android-added
- /**
- * Set the handshake timeout on this socket. This timeout is specified in
- * milliseconds and will be used only during the handshake process.
- *
- * @param timeout the handshake timeout value
- */
- public synchronized void setHandshakeTimeout(int timeout) throws SocketException {
- this.handshakeTimeout = timeout;
- }
- // END android-added
-
- private native void nativeinterrupt(int sslNativePointer) throws IOException;
- private native void nativeclose(int sslNativePointer) throws IOException;
-
- /**
- * Closes the SSL socket. Once closed, a socket is not available for further
- * use anymore under any circumstance. A new socket must be created.
- *
- * @throws <code>IOException</code> if an I/O error happens during the
- * socket's closure.
- */
- public void close() throws IOException {
- // TODO: Close SSL sockets using a background thread so they close
- // gracefully.
-
- synchronized (handshakeLock) {
- if (!handshakeStarted) {
- // prevent further attemps to start handshake
- handshakeStarted = true;
-
- synchronized (this) {
- free();
-
- if (socket != null) {
- if (autoClose && !socket.isClosed()) socket.close();
- } else {
- if (!super.isClosed()) super.close();
- }
- }
-
- return;
- }
- }
-
- nativeinterrupt(sslNativePointer);
-
- synchronized (this) {
- synchronized (writeLock) {
- synchronized (readLock) {
-
- IOException pendingException = null;
-
- // Shut down the SSL connection, per se.
- try {
- if (handshakeStarted) {
- nativeclose(sslNativePointer);
- }
- } catch (IOException ex) {
- /*
- * Note the exception at this point, but try to continue
- * to clean the rest of this all up before rethrowing.
- */
- pendingException = ex;
- }
-
- /*
- * Even if the above call failed, it is still safe to free
- * the native structs, and we need to do so lest we leak
- * memory.
- */
- free();
-
- if (socket != null) {
- if (autoClose && !socket.isClosed())
- socket.close();
- } else {
- if (!super.isClosed())
- super.close();
- }
-
- if (pendingException != null) {
- throw pendingException;
- }
- }
- }
- }
- }
-
- private void free() {
- if (sslNativePointer == 0) {
- return;
- }
- NativeCrypto.SSL_free(sslNativePointer);
- sslNativePointer = 0;
- }
-
- protected void finalize() throws IOException {
- /*
- * Just worry about our own state. Notably we do not try and
- * close anything. The SocketImpl, either our own
- * PlainSocketImpl, or the Socket we are wrapping, will do
- * that. This might mean we do not properly SSL_shutdown, but
- * if you want to do that, properly close the socket yourself.
- *
- * The reason why we don't try to SSL_shutdown, is that there
- * can be a race between finalizers where the PlainSocketImpl
- * finalizer runs first and closes the socket. However, in the
- * meanwhile, the underlying file descriptor could be reused
- * for another purpose. If we call SSL_shutdown, the
- * underlying socket BIOs still have the old file descriptor
- * and will write the close notify to some unsuspecting
- * reader.
- */
- updateInstanceCount(-1);
- free();
- }
-
- /**
- * Verifies an RSA signature. Conceptually, this method doesn't really
- * belong here, but due to its native code being closely tied to OpenSSL
- * (just like the rest of this class), we put it here for the time being.
- * This also solves potential problems with native library initialization.
- *
- * @param message The message to verify
- * @param signature The signature to verify
- * @param algorithm The hash/sign algorithm to use, i.e. "RSA-SHA1"
- * @param key The RSA public key to use
- * @return true if the verification succeeds, false otherwise
- */
- public static boolean verifySignature(byte[] message, byte[] signature, String algorithm, RSAPublicKey key) {
- byte[] modulus = key.getModulus().toByteArray();
- byte[] exponent = key.getPublicExponent().toByteArray();
-
- return nativeverifysignature(message, signature, algorithm, modulus, exponent) == 1;
- }
-
- private static native int nativeverifysignature(byte[] message, byte[] signature,
- String algorithm, byte[] modulus, byte[] exponent);
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImplWrapper.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImplWrapper.java
deleted file mode 100644
index 959f2a0..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImplWrapper.java
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.net.SocketAddress;
-import java.net.SocketException;
-
-/**
- * This class wraps the SSL functionality over an existing conneted socket.
- */
-public class OpenSSLSocketImplWrapper extends OpenSSLSocketImpl {
-
- private Socket socket;
-
- protected OpenSSLSocketImplWrapper(Socket socket, String host, int port,
- boolean autoClose, SSLParameters sslParameters) throws IOException {
- super(socket, host, port, autoClose, sslParameters);
- if (!socket.isConnected()) {
- throw new SocketException("Socket is not connected.");
- }
- this.socket = socket;
- }
-
- @Override
- public void connect(SocketAddress sockaddr, int timeout)
- throws IOException {
- throw new IOException("Underlying socket is already connected.");
- }
-
- @Override
- public void connect(SocketAddress sockaddr) throws IOException {
- throw new IOException("Underlying socket is already connected.");
- }
-
- @Override
- public void bind(SocketAddress sockaddr) throws IOException {
- throw new IOException("Underlying socket is already connected.");
- }
-
- @Override
- public SocketAddress getRemoteSocketAddress() {
- return socket.getRemoteSocketAddress();
- }
-
- @Override
- public SocketAddress getLocalSocketAddress() {
- return socket.getLocalSocketAddress();
- }
-
- @Override
- public InetAddress getLocalAddress() {
- return socket.getLocalAddress();
- }
-
- @Override
- public InetAddress getInetAddress() {
- return socket.getInetAddress();
- }
-
- @Override
- public String toString() {
- return "SSL socket over " + socket.toString();
- }
-
- @Override
- public void setSoLinger(boolean on, int linger) throws SocketException {
- socket.setSoLinger(on, linger);
- }
-
- @Override
- public void setTcpNoDelay(boolean on) throws SocketException {
- socket.setTcpNoDelay(on);
- }
-
- @Override
- public void setReuseAddress(boolean on) throws SocketException {
- socket.setReuseAddress(on);
- }
-
- @Override
- public void setKeepAlive(boolean on) throws SocketException {
- socket.setKeepAlive(on);
- }
-
- @Override
- public void setTrafficClass(int tos) throws SocketException {
- socket.setTrafficClass(tos);
- }
-
- @Override
- public void setSoTimeout(int to) throws SocketException {
- socket.setSoTimeout(to);
- super.setSoTimeout(to);
- }
-
- @Override
- public void setSendBufferSize(int size) throws SocketException {
- socket.setSendBufferSize(size);
- }
-
- @Override
- public void setReceiveBufferSize(int size) throws SocketException {
- socket.setReceiveBufferSize(size);
- }
-
- @Override
- public boolean getTcpNoDelay() throws SocketException {
- return socket.getTcpNoDelay();
- }
-
- @Override
- public boolean getReuseAddress() throws SocketException {
- return socket.getReuseAddress();
- }
-
- @Override
- public boolean getOOBInline() throws SocketException {
- return socket.getOOBInline();
- }
-
- @Override
- public boolean getKeepAlive() throws SocketException {
- return socket.getKeepAlive();
- }
-
- @Override
- public int getTrafficClass() throws SocketException {
- return socket.getTrafficClass();
- }
-
- @Override
- public int getSoTimeout() throws SocketException {
- return socket.getSoTimeout();
- }
-
- @Override
- public int getSoLinger() throws SocketException {
- return socket.getSoLinger();
- }
-
- @Override
- public int getSendBufferSize() throws SocketException {
- return socket.getSendBufferSize();
- }
-
- @Override
- public int getReceiveBufferSize() throws SocketException {
- return socket.getReceiveBufferSize();
- }
-
- @Override
- public boolean isConnected() {
- return socket.isConnected();
- }
-
- @Override
- public boolean isClosed() {
- return socket.isClosed();
- }
-
- @Override
- public boolean isBound() {
- return socket.isBound();
- }
-
- @Override
- public boolean isOutputShutdown() {
- return socket.isOutputShutdown();
- }
-
- @Override
- public boolean isInputShutdown() {
- return socket.isInputShutdown();
- }
-
- @Override
- public int getPort() {
- return socket.getPort();
- }
-
- @Override
- public int getLocalPort() {
- return socket.getLocalPort();
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/PRF.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/PRF.java
deleted file mode 100644
index c2f91a3..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/PRF.java
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.AlertException;
-import org.apache.harmony.xnet.provider.jsse.Logger;
-
-import java.security.GeneralSecurityException;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.util.Arrays;
-import javax.net.ssl.SSLException;
-import javax.crypto.Mac;
-import javax.crypto.spec.SecretKeySpec;
-
-/**
- * This class provides functionality for computation
- * of PRF values for TLS (http://www.ietf.org/rfc/rfc2246.txt)
- * and SSL v3 (http://wp.netscape.com/eng/ssl3) protocols.
- */
-public class PRF {
- private static Logger.Stream logger = Logger.getStream("prf");
-
- private static Mac md5_mac;
- private static Mac sha_mac;
- protected static MessageDigest md5;
- protected static MessageDigest sha;
- private static int md5_mac_length;
- private static int sha_mac_length;
-
- static private void init() {
- try {
- md5_mac = Mac.getInstance("HmacMD5");
- sha_mac = Mac.getInstance("HmacSHA1");
- } catch (NoSuchAlgorithmException e) {
- throw new AlertException(AlertProtocol.INTERNAL_ERROR,
- new SSLException(
- "There is no provider of HmacSHA1 or HmacMD5 "
- + "algorithms installed in the system"));
- }
- md5_mac_length = md5_mac.getMacLength();
- sha_mac_length = sha_mac.getMacLength();
- try {
- md5 = MessageDigest.getInstance("MD5");
- sha = MessageDigest.getInstance("SHA-1");
- } catch (Exception e) {
- throw new AlertException(AlertProtocol.INTERNAL_ERROR,
- new SSLException(
- "Could not initialize the Digest Algorithms."));
- }
- }
-
- /**
- * Computes the value of SSLv3 pseudo random function.
- * @param out: the buffer to fill up with the value of the function.
- * @param secret: the buffer containing the secret value to generate prf.
- * @param seed: the seed to be used.
- */
- static synchronized void computePRF_SSLv3(byte[] out, byte[] secret, byte[] seed) {
- if (sha == null) {
- init();
- }
- int pos = 0;
- int iteration = 1;
- byte[] digest;
- while (pos < out.length) {
- byte[] pref = new byte[iteration];
- Arrays.fill(pref, (byte) (64 + iteration++));
- sha.update(pref);
- sha.update(secret);
- sha.update(seed);
- md5.update(secret);
- md5.update(sha.digest());
- digest = md5.digest(); // length == 16
- if (pos + 16 > out.length) {
- System.arraycopy(digest, 0, out, pos, out.length - pos);
- pos = out.length;
- } else {
- System.arraycopy(digest, 0, out, pos, 16);
- pos += 16;
- }
- }
- }
-
- /**
- * Computes the value of TLS pseudo random function.
- * @param out: the buffer to fill up with the value of the function.
- * @param secret: the buffer containing the secret value to generate prf.
- * @param str_bytes: the label bytes to be used.
- * @param seed: the seed to be used.
- */
- synchronized static void computePRF(byte[] out, byte[] secret,
- byte[] str_byts, byte[] seed) throws GeneralSecurityException {
- if (sha_mac == null) {
- init();
- }
- // Do concatenation of the label with the seed:
- // (metterings show that is is faster to concatenate the arrays
- // and to call HMAC.update on cancatenation, than twice call for
- // each of the part, i.e.:
- // time(HMAC.update(label+seed))
- // < time(HMAC.update(label)) + time(HMAC.update(seed))
- // but it takes more memmory (approximaty on 4%)
- /*
- byte[] tmp_seed = new byte[seed.length + str_byts.length];
- System.arraycopy(str_byts, 0, tmp_seed, 0, str_byts.length);
- System.arraycopy(seed, 0, tmp_seed, str_byts.length, seed.length);
- seed = tmp_seed;
- */
- SecretKeySpec keyMd5;
- SecretKeySpec keySha1;
- if ((secret == null) || (secret.length == 0)) {
- secret = new byte[8];
- keyMd5 = new SecretKeySpec(secret, "HmacMD5");
- keySha1 = new SecretKeySpec(secret, "HmacSHA1");
- } else {
- int length = secret.length >> 1; // division by 2
- int offset = secret.length & 1; // remainder
- keyMd5 = new SecretKeySpec(secret, 0, length + offset,
- "HmacMD5");
- keySha1 = new SecretKeySpec(secret, length, length
- + offset, "HmacSHA1");
- }
-
- //byte[] str_byts = label.getBytes();
-
- if (logger != null) {
- logger.println("secret["+secret.length+"]: ");
- logger.printAsHex(16, "", " ", secret);
- logger.println("label["+str_byts.length+"]: ");
- logger.printAsHex(16, "", " ", str_byts);
- logger.println("seed["+seed.length+"]: ");
- logger.printAsHex(16, "", " ", seed);
- logger.println("MD5 key:");
- logger.printAsHex(16, "", " ", keyMd5.getEncoded());
- logger.println("SHA1 key:");
- logger.printAsHex(16, "", " ", keySha1.getEncoded());
- }
-
- md5_mac.init(keyMd5);
- sha_mac.init(keySha1);
-
- int pos = 0;
- md5_mac.update(str_byts);
- byte[] hash = md5_mac.doFinal(seed); // A(1)
- while (pos < out.length) {
- md5_mac.update(hash);
- md5_mac.update(str_byts);
- md5_mac.update(seed);
- if (pos + md5_mac_length < out.length) {
- md5_mac.doFinal(out, pos);
- pos += md5_mac_length;
- } else {
- System.arraycopy(md5_mac.doFinal(), 0, out,
- pos, out.length - pos);
- break;
- }
- // make A(i)
- hash = md5_mac.doFinal(hash);
- }
- if (logger != null) {
- logger.println("P_MD5:");
- logger.printAsHex(md5_mac_length, "", " ", out);
- }
-
- pos = 0;
- sha_mac.update(str_byts);
- hash = sha_mac.doFinal(seed); // A(1)
- byte[] sha1hash;
- while (pos < out.length) {
- sha_mac.update(hash);
- sha_mac.update(str_byts);
- sha1hash = sha_mac.doFinal(seed);
- for (int i = 0; (i < sha_mac_length) & (pos < out.length); i++) {
- out[pos++] ^= sha1hash[i];
- }
- // make A(i)
- hash = sha_mac.doFinal(hash);
- }
-
- if (logger != null) {
- logger.println("PRF:");
- logger.printAsHex(sha_mac_length, "", " ", out);
- }
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ProtocolVersion.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ProtocolVersion.java
deleted file mode 100644
index def27f9..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ProtocolVersion.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.util.Hashtable;
-
-/**
- *
- * Represents Protocol Version
- */
-public class ProtocolVersion {
- /**
- * Protocols supported by this provider implementation
- */
- public static final String[] supportedProtocols = new String[] { "TLSv1",
- "SSLv3" };
-
- private static Hashtable<String, ProtocolVersion> protocolsByName = new Hashtable<String, ProtocolVersion>(4);
-
- /**
- *
- * Returns true if protocol version is supported
- *
- * @param version
- */
- public static boolean isSupported(byte[] version) {
- if (version[0] != 3 || (version[1] != 0 && version[1] != 1)) {
- return false;
- }
- return true;
- }
-
- /**
- * Returns ProtocolVersion
- *
- * @param version
- * @return
- */
- public static ProtocolVersion getByVersion(byte[] version) {
- if (version[0] == 3) {
- if (version[1] == 1) {
- return TLSv1;
- }
- if (version[1] == 0) {
- return SSLv3;
- }
- }
- return null;
- }
-
- /**
- * Returns true if provider supports protocol version
- *
- * @param name
- * @return
- */
- public static boolean isSupported(String name) {
- return protocolsByName.containsKey(name);
- }
-
- /**
- * Returns ProtocolVersion
- *
- * @param name
- * @return
- */
- public static ProtocolVersion getByName(String name) {
- return protocolsByName.get(name);
- }
-
- /**
- * Highest protocol version supported by provider implementation
- *
- * @param protocols
- * @return
- */
- public static ProtocolVersion getLatestVersion(String[] protocols) {
- if (protocols == null || protocols.length == 0) {
- return null;
- }
- ProtocolVersion latest = getByName(protocols[0]);
- ProtocolVersion current;
- for (int i = 1; i < protocols.length; i++) {
- current = getByName(protocols[i]);
- if (current == null) {
- continue;
- }
- if ((latest == null)
- || (latest.version[0] < current.version[0])
- || (latest.version[0] == current.version[0] && latest.version[1] < current.version[1])) {
- latest = current;
- }
- }
- return latest;
-
- }
-
- /**
- * SSL 3.0 protocol version
- */
- public static ProtocolVersion SSLv3 = new ProtocolVersion("SSLv3",
- new byte[] { 3, 0 });
-
- /**
- * TLS 1.0 protocol version
- */
- public static ProtocolVersion TLSv1 = new ProtocolVersion("TLSv1",
- new byte[] { 3, 1 });
-
- static {
- protocolsByName.put(SSLv3.name, SSLv3);
- protocolsByName.put(TLSv1.name, TLSv1);
- protocolsByName.put("SSL", SSLv3);
- protocolsByName.put("TLS", TLSv1);
- }
-
- /**
- * Protocol name
- */
- public final String name;
-
- /**
- * Protocol version as byte array
- */
- public final byte[] version;
-
- private ProtocolVersion(String name, byte[] version) {
- this.name = name;
- this.version = version;
- }
-
- /**
- * Compares this ProtocolVersion to the specified object.
- */
- @Override
- public boolean equals(Object o) {
- if (o instanceof ProtocolVersion
- && this.version[0] == ((ProtocolVersion) o).version[0]
- && this.version[1] == ((ProtocolVersion) o).version[1]) {
- return true;
- }
- return false;
- }
-} \ No newline at end of file
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLBufferedInput.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLBufferedInput.java
deleted file mode 100644
index 31bb681..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLBufferedInput.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.SSLInputStream;
-
-import java.io.IOException;
-import java.nio.ByteBuffer;
-
-/**
- * This is a wrapper input stream for ByteBuffer data source.
- * Among with the read functionality it provides info
- * about number of cunsumed bytes from the source ByteBuffer.
- * The source ByteBuffer object can be reseted.
- * So one instance of this wrapper can be reused for several
- * ByteBuffer data sources.
- */
-public class SSLBufferedInput extends SSLInputStream {
-
- private ByteBuffer in;
- private int bytik;
- private int consumed = 0;
-
- /**
- * Constructor
- */
- protected SSLBufferedInput() {}
-
- /**
- * Sets the buffer as a data source
- */
- protected void setSourceBuffer(ByteBuffer in) {
- consumed = 0;
- this.in = in;
- }
-
- @Override
- public int available() throws IOException {
- // in assumption that the buffer has been set
- return in.remaining();
- }
-
- /**
- * Returns the number of consumed bytes.
- */
- protected int consumed() {
- return consumed;
- }
-
- /**
- * Reads the following byte value. If there are no bytes in the source
- * buffer, method throws java.nio.BufferUnderflowException.
- */
- @Override
- public int read() throws IOException {
- // TODO: implement optimized read(int)
- // and read(byte[], int, int) methods
- bytik = in.get() & 0x00FF;
- consumed ++;
- return bytik;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLClientSessionCache.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLClientSessionCache.java
deleted file mode 100644
index 8a73fa5..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLClientSessionCache.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import javax.net.ssl.SSLSession;
-
-/**
- * A persistent {@link javax.net.ssl.SSLSession} cache used by
- * {@link javax.net.ssl.SSLSessionContext} to share client-side SSL sessions
- * across processes. For example, this cache enables applications to
- * persist and reuse sessions across restarts.
- *
- * <p>The {@code SSLSessionContext} implementation converts
- * {@code SSLSession}s into raw bytes and vice versa. The exact makeup of the
- * session data is dependent upon the caller's implementation and is opaque to
- * the {@code SSLClientSessionCache} implementation.
- */
-public interface SSLClientSessionCache {
-
- /**
- * Gets data from a pre-existing session for a given server host and port.
- *
- * @param host from {@link javax.net.ssl.SSLSession#getPeerHost()}
- * @param port from {@link javax.net.ssl.SSLSession#getPeerPort()}
- * @return the session data or null if none is cached
- * @throws NullPointerException if host is null
- */
- public byte[] getSessionData(String host, int port);
-
- /**
- * Stores session data for the given session.
- *
- * @param session to cache data for
- * @param sessionData to cache
- * @throws NullPointerException if session, result of
- * {@code session.getPeerHost()} or data is null
- */
- public void putSessionData(SSLSession session, byte[] sessionData);
-} \ No newline at end of file
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLContextImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLContextImpl.java
deleted file mode 100644
index 34942e1..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLContextImpl.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.SSLEngineImpl;
-import org.apache.harmony.xnet.provider.jsse.SSLParameters;
-// BEGIN android-removed
-// import org.apache.harmony.xnet.provider.jsse.SSLServerSocketFactoryImpl;
-// END android-removed
-
-import java.security.KeyManagementException;
-import java.security.SecureRandom;
-
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.SSLContextSpi;
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.SSLServerSocketFactory;
-import javax.net.ssl.SSLSessionContext;
-import javax.net.ssl.SSLSocketFactory;
-import javax.net.ssl.TrustManager;
-
-// BEGIN android-note
-// Modified heavily during SSLSessionContext refactoring. Added support for
-// persistent session caches.
-// END android-note
-
-/**
- * Implementation of SSLContext service provider interface.
- */
-public class SSLContextImpl extends SSLContextSpi {
-
- /** Client session cache. */
- private ClientSessionContext clientSessionContext;
-
- /** Server session cache. */
- private ServerSessionContext serverSessionContext;
-
- protected SSLParameters sslParameters;
-
- public SSLContextImpl() {
- super();
- }
-
- @Override
- public void engineInit(KeyManager[] kms, TrustManager[] tms,
- SecureRandom sr) throws KeyManagementException {
- engineInit(kms, tms, sr, null, null);
- }
-
- /**
- * Initializes this {@code SSLContext} instance. All of the arguments are
- * optional, and the security providers will be searched for the required
- * implementations of the needed algorithms.
- *
- * @param kms the key sources or {@code null}
- * @param tms the trust decision sources or {@code null}
- * @param sr the randomness source or {@code null}
- * @param clientCache persistent client session cache or {@code null}
- * @param serverCache persistent server session cache or {@code null}
- * @throws KeyManagementException if initializing this instance fails
- */
- public void engineInit(KeyManager[] kms, TrustManager[] tms,
- SecureRandom sr, SSLClientSessionCache clientCache,
- SSLServerSessionCache serverCache) throws KeyManagementException {
- sslParameters = new SSLParameters(kms, tms, sr,
- clientCache, serverCache);
- clientSessionContext = sslParameters.getClientSessionContext();
- serverSessionContext = sslParameters.getServerSessionContext();
- }
-
- public SSLSocketFactory engineGetSocketFactory() {
- if (sslParameters == null) {
- throw new IllegalStateException("SSLContext is not initiallized.");
- }
- return new OpenSSLSocketFactoryImpl(sslParameters);
- }
-
- @Override
- public SSLServerSocketFactory engineGetServerSocketFactory() {
- if (sslParameters == null) {
- throw new IllegalStateException("SSLContext is not initiallized.");
- }
- return new OpenSSLServerSocketFactoryImpl(sslParameters);
- }
-
- @Override
- public SSLEngine engineCreateSSLEngine(String host, int port) {
- if (sslParameters == null) {
- throw new IllegalStateException("SSLContext is not initiallized.");
- }
- return new SSLEngineImpl(host, port,
- (SSLParameters) sslParameters.clone());
- }
-
- @Override
- public SSLEngine engineCreateSSLEngine() {
- if (sslParameters == null) {
- throw new IllegalStateException("SSLContext is not initiallized.");
- }
- return new SSLEngineImpl((SSLParameters) sslParameters.clone());
- }
-
- @Override
- public ServerSessionContext engineGetServerSessionContext() {
- return serverSessionContext;
- }
-
- @Override
- public ClientSessionContext engineGetClientSessionContext() {
- return clientSessionContext;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLEngineAppData.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLEngineAppData.java
deleted file mode 100644
index 9a2cb5e..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLEngineAppData.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.AlertException;
-
-import java.nio.ByteBuffer;
-import javax.net.ssl.SSLException;
-
-/**
- * This class is used to retrieve the application data
- * arrived for the SSLEngine.
- */
-public class SSLEngineAppData implements org.apache.harmony.xnet.provider.jsse.Appendable {
-
- /**
- * Buffer containing received application data.
- */
- byte[] buffer;
-
- /**
- * Constructor
- */
- protected SSLEngineAppData() {}
-
- /**
- * Stores received data. The source data is not cloned,
- * just the array reference is remembered into the buffer field.
- */
- public void append(byte[] src) {
- if (buffer != null) {
- throw new AlertException(
- AlertProtocol.INTERNAL_ERROR,
- new SSLException("Attempt to override the data"));
- }
- buffer = src;
- }
-
- /**
- * Places the data from the buffer into the array of destination
- * ByteBuffer objects.
- */
- protected int placeTo(ByteBuffer[] dsts, int offset, int length) {
- if (buffer == null) {
- return 0;
- }
- int pos = 0;
- int len = buffer.length;
- int rem;
- // write data to the buffers
- for (int i=offset; i<offset+length; i++) {
- rem = dsts[i].remaining();
- // TODO: optimization work - use hasArray, array(), arraycopy
- if (len - pos < rem) {
- // can fully write remaining data into buffer
- dsts[i].put(buffer, pos, len - pos);
- pos = len;
- // data was written, exit
- break;
- }
- // write chunk of data
- dsts[i].put(buffer, pos, rem);
- pos += rem;
- }
- if (pos != len) {
- // The data did not feet into the buffers,
- // it should not happen, because the destination buffers
- // had been checked for the space before record unwrapping.
- // But if it so, we should allert about internal error.
- throw new AlertException(
- AlertProtocol.INTERNAL_ERROR,
- new SSLException(
- "The received application data could not be fully written"
- + "into the destination buffers"));
- }
- buffer = null;
- return len;
- }
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLEngineDataStream.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLEngineDataStream.java
deleted file mode 100644
index e209dd1..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLEngineDataStream.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.nio.ByteBuffer;
-
-/**
- * This class provides the DataStream functionality
- * implemented over the array of ByteBuffer instances.
- * Among with the data chunks read functionality
- * it provides the info about amount of consumed data.
- * The source ByteBuffer objects can be replaced by other.
- * So one instance of this wrapper can be reused for several
- * data sources.
- */
-public class SSLEngineDataStream implements DataStream {
-
- private ByteBuffer[] srcs;
- private int offset;
- private int limit;
-
- private int available;
- private int consumed;
-
- protected SSLEngineDataStream() {}
-
- protected void setSourceBuffers(ByteBuffer[] srcs, int offset, int length) {
- this.srcs = srcs;
- this.offset = offset;
- this.limit = offset+length;
- this.consumed = 0;
- this.available = 0;
- for (int i=offset; i<limit; i++) {
- if (srcs[i] == null) {
- throw new IllegalStateException(
- "Some of the input parameters are null");
- }
- available += srcs[i].remaining();
- }
- }
-
- public int available() {
- return available;
- }
-
- public boolean hasData() {
- return available > 0;
- }
-
- public byte[] getData(int length) {
- // TODO: optimization work:
- // use ByteBuffer.get(byte[],int,int)
- // and ByteBuffer.hasArray() methods
- int len = (length < available) ? length : available;
- available -= len;
- consumed += len;
- byte[] res = new byte[len];
- int pos = 0;
- loop:
- for (; offset<limit; offset++) {
- while (srcs[offset].hasRemaining()) {
- res[pos++] = srcs[offset].get();
- len --;
- if (len == 0) {
- break loop;
- }
- }
- }
- return res;
- }
-
- protected int consumed() {
- return consumed;
- }
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLEngineImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLEngineImpl.java
deleted file mode 100644
index c28a311..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLEngineImpl.java
+++ /dev/null
@@ -1,769 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.AlertException;
-import org.apache.harmony.xnet.provider.jsse.SSLSessionImpl;
-import org.apache.harmony.xnet.provider.jsse.SSLEngineDataStream;
-
-import java.io.IOException;
-import java.nio.BufferUnderflowException;
-import java.nio.ByteBuffer;
-import java.nio.ReadOnlyBufferException;
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.SSLHandshakeException;
-import javax.net.ssl.SSLEngineResult;
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLSession;
-
-/**
- * Implementation of SSLEngine.
- * @see javax.net.ssl.SSLEngine class documentation for more information.
- */
-public class SSLEngineImpl extends SSLEngine {
-
- // indicates if peer mode was set
- private boolean peer_mode_was_set = false;
- // indicates if handshake has been started
- private boolean handshake_started = false;
- // indicates if inbound operations finished
- private boolean isInboundDone = false;
- // indicates if outbound operations finished
- private boolean isOutboundDone = false;
- // indicates if close_notify alert had been sent to another peer
- private boolean close_notify_was_sent = false;
- // indicates if close_notify alert had been received from another peer
- private boolean close_notify_was_received = false;
- // indicates if engine was closed (it means that
- // all the works on it are done, except (probably) some finalizing work)
- private boolean engine_was_closed = false;
- // indicates if engine was shutted down (it means that
- // all cleaning work had been done and the engine is not operable)
- private boolean engine_was_shutteddown = false;
-
- // record protocol to be used
- protected SSLRecordProtocol recordProtocol;
- // input stream for record protocol
- private SSLBufferedInput recProtIS;
- // handshake protocol to be used
- private HandshakeProtocol handshakeProtocol;
- // alert protocol to be used
- private AlertProtocol alertProtocol;
- // place where application data will be stored
- private SSLEngineAppData appData;
- // outcoming application data stream
- private SSLEngineDataStream dataStream = new SSLEngineDataStream();
- // active session object
- private SSLSessionImpl session;
-
- // peer configuration parameters
- protected SSLParameters sslParameters;
-
- // in case of emergency situations when data could not be
- // placed in destination buffers it will be stored in this
- // fields
- private byte[] remaining_wrapped_data = null;
- private byte[] remaining_hsh_data = null;
-
- // logger
- private Logger.Stream logger = Logger.getStream("engine");
-
- /**
- * Ctor
- * @param sslParameters: SSLParameters
- */
- protected SSLEngineImpl(SSLParameters sslParameters) {
- super();
- this.sslParameters = sslParameters;
- }
-
- /**
- * Ctor
- * @param host: String
- * @param port: int
- * @param sslParameters: SSLParameters
- */
- protected SSLEngineImpl(String host, int port, SSLParameters sslParameters) {
- super(host, port);
- this.sslParameters = sslParameters;
- }
-
- /**
- * Starts the handshake.
- * @throws SSLException
- * @see javax.net.ssl.SSLEngine#beginHandshake() method documentation
- * for more information
- */
- @Override
- public void beginHandshake() throws SSLException {
- if (engine_was_closed) {
- throw new SSLException("Engine has already been closed.");
- }
- if (!peer_mode_was_set) {
- throw new IllegalStateException("Client/Server mode was not set");
- }
- if (!handshake_started) {
- handshake_started = true;
- if (getUseClientMode()) {
- handshakeProtocol = new ClientHandshakeImpl(this);
- } else {
- handshakeProtocol = new ServerHandshakeImpl(this);
- }
- appData = new SSLEngineAppData();
- alertProtocol = new AlertProtocol();
- recProtIS = new SSLBufferedInput();
- recordProtocol = new SSLRecordProtocol(handshakeProtocol,
- alertProtocol, recProtIS, appData);
- }
- handshakeProtocol.start();
- }
-
- /**
- * Closes inbound operations of this engine
- * @throws SSLException
- * @see javax.net.ssl.SSLEngine#closeInbound() method documentation
- * for more information
- */
- @Override
- public void closeInbound() throws SSLException {
- if (logger != null) {
- logger.println("closeInbound() "+isInboundDone);
- }
- if (isInboundDone) {
- return;
- }
- isInboundDone = true;
- engine_was_closed = true;
- if (handshake_started) {
- if (!close_notify_was_received) {
- if (session != null) {
- session.invalidate();
- }
- alertProtocol.alert(AlertProtocol.FATAL,
- AlertProtocol.INTERNAL_ERROR);
- throw new SSLException("Inbound is closed before close_notify "
- + "alert has been received.");
- }
- } else {
- // engine is closing before initial handshake has been made
- shutdown();
- }
- }
-
- /**
- * Closes outbound operations of this engine
- * @see javax.net.ssl.SSLEngine#closeOutbound() method documentation
- * for more information
- */
- @Override
- public void closeOutbound() {
- if (logger != null) {
- logger.println("closeOutbound() "+isOutboundDone);
- }
- if (isOutboundDone) {
- return;
- }
- isOutboundDone = true;
- if (handshake_started) {
- // initial handshake had been started
- alertProtocol.alert(AlertProtocol.WARNING,
- AlertProtocol.CLOSE_NOTIFY);
- close_notify_was_sent = true;
- } else {
- // engine is closing before initial handshake has been made
- shutdown();
- }
- engine_was_closed = true;
- }
-
- /**
- * Returns handshake's delegated tasks to be run
- * @return the delegated task to be executed.
- * @see javax.net.ssl.SSLEngine#getDelegatedTask() method documentation
- * for more information
- */
- @Override
- public Runnable getDelegatedTask() {
- return handshakeProtocol.getTask();
- }
-
- /**
- * Returns names of supported cipher suites.
- * @return array of strings containing the names of supported cipher suites
- * @see javax.net.ssl.SSLEngine#getSupportedCipherSuites() method
- * documentation for more information
- */
- @Override
- public String[] getSupportedCipherSuites() {
- return CipherSuite.getSupportedCipherSuiteNames();
- }
-
- // --------------- SSLParameters based methods ---------------------
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#getEnabledCipherSuites() method
- * documentation for more information
- */
- @Override
- public String[] getEnabledCipherSuites() {
- return sslParameters.getEnabledCipherSuites();
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#setEnabledCipherSuites(String[]) method
- * documentation for more information
- */
- @Override
- public void setEnabledCipherSuites(String[] suites) {
- sslParameters.setEnabledCipherSuites(suites);
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#getSupportedProtocols() method
- * documentation for more information
- */
- @Override
- public String[] getSupportedProtocols() {
- return ProtocolVersion.supportedProtocols.clone();
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#getEnabledProtocols() method
- * documentation for more information
- */
- @Override
- public String[] getEnabledProtocols() {
- return sslParameters.getEnabledProtocols();
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#setEnabledProtocols(String[]) method
- * documentation for more information
- */
- @Override
- public void setEnabledProtocols(String[] protocols) {
- sslParameters.setEnabledProtocols(protocols);
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#setUseClientMode(boolean) method
- * documentation for more information
- */
- @Override
- public void setUseClientMode(boolean mode) {
- if (handshake_started) {
- throw new IllegalArgumentException(
- "Could not change the mode after the initial handshake has begun.");
- }
- sslParameters.setUseClientMode(mode);
- peer_mode_was_set = true;
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#getUseClientMode() method
- * documentation for more information
- */
- @Override
- public boolean getUseClientMode() {
- return sslParameters.getUseClientMode();
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#setNeedClientAuth(boolean) method
- * documentation for more information
- */
- @Override
- public void setNeedClientAuth(boolean need) {
- sslParameters.setNeedClientAuth(need);
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#getNeedClientAuth() method
- * documentation for more information
- */
- @Override
- public boolean getNeedClientAuth() {
- return sslParameters.getNeedClientAuth();
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#setWantClientAuth(boolean) method
- * documentation for more information
- */
- @Override
- public void setWantClientAuth(boolean want) {
- sslParameters.setWantClientAuth(want);
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#getWantClientAuth() method
- * documentation for more information
- */
- @Override
- public boolean getWantClientAuth() {
- return sslParameters.getWantClientAuth();
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#setEnableSessionCreation(boolean) method
- * documentation for more information
- */
- @Override
- public void setEnableSessionCreation(boolean flag) {
- sslParameters.setEnableSessionCreation(flag);
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#getEnableSessionCreation() method
- * documentation for more information
- */
- @Override
- public boolean getEnableSessionCreation() {
- return sslParameters.getEnableSessionCreation();
- }
-
- // -----------------------------------------------------------------
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#getHandshakeStatus() method
- * documentation for more information
- */
- @Override
- public SSLEngineResult.HandshakeStatus getHandshakeStatus() {
- if (!handshake_started || engine_was_shutteddown) {
- // initial handshake has not been started yet
- return SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING;
- }
- if (alertProtocol.hasAlert()) {
- // need to send an alert
- return SSLEngineResult.HandshakeStatus.NEED_WRAP;
- }
- if (close_notify_was_sent && !close_notify_was_received) {
- // waiting for "close_notify" response
- return SSLEngineResult.HandshakeStatus.NEED_UNWRAP;
- }
- return handshakeProtocol.getStatus();
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#getSession() method
- * documentation for more information
- */
- @Override
- public SSLSession getSession() {
- if (session != null) {
- return session;
- }
- return SSLSessionImpl.NULL_SESSION;
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#isInboundDone() method
- * documentation for more information
- */
- @Override
- public boolean isInboundDone() {
- return isInboundDone || engine_was_closed;
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#isOutboundDone() method
- * documentation for more information
- */
- @Override
- public boolean isOutboundDone() {
- return isOutboundDone;
- }
-
- /**
- * Decodes one complete SSL/TLS record provided in the source buffer.
- * If decoded record contained application data, this data will
- * be placed in the destination buffers.
- * For more information about TLS record fragmentation see
- * TLS v 1 specification (http://www.ietf.org/rfc/rfc2246.txt) p 6.2.
- * @param src source buffer containing SSL/TLS record.
- * @param dsts destination buffers to place received application data.
- * @see javax.net.ssl.SSLEngine#unwrap(ByteBuffer,ByteBuffer[],int,int)
- * method documentation for more information
- */
- @Override
- public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dsts,
- int offset, int length) throws SSLException {
- if (engine_was_shutteddown) {
- return new SSLEngineResult(SSLEngineResult.Status.CLOSED,
- SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING, 0, 0);
- }
- if ((src == null) || (dsts == null)) {
- throw new IllegalStateException(
- "Some of the input parameters are null");
- }
-
- if (!handshake_started) {
- beginHandshake();
- }
-
- SSLEngineResult.HandshakeStatus handshakeStatus = getHandshakeStatus();
- // If is is initial handshake or connection closure stage,
- // check if this call was made in spite of handshake status
- if ((session == null || engine_was_closed) && (
- handshakeStatus.equals(
- SSLEngineResult.HandshakeStatus.NEED_WRAP) ||
- handshakeStatus.equals(
- SSLEngineResult.HandshakeStatus.NEED_TASK))) {
- return new SSLEngineResult(
- getEngineStatus(), handshakeStatus, 0, 0);
- }
-
- if (src.remaining() < recordProtocol.getMinRecordSize()) {
- return new SSLEngineResult(
- SSLEngineResult.Status.BUFFER_UNDERFLOW,
- getHandshakeStatus(), 0, 0);
- }
-
- try {
- src.mark();
- // check the destination buffers and count their capacity
- int capacity = 0;
- for (int i=offset; i<offset+length; i++) {
- if (dsts[i] == null) {
- throw new IllegalStateException(
- "Some of the input parameters are null");
- }
- if (dsts[i].isReadOnly()) {
- throw new ReadOnlyBufferException();
- }
- capacity += dsts[i].remaining();
- }
- if (capacity < recordProtocol.getDataSize(src.remaining())) {
- return new SSLEngineResult(
- SSLEngineResult.Status.BUFFER_OVERFLOW,
- getHandshakeStatus(), 0, 0);
- }
- recProtIS.setSourceBuffer(src);
- // unwrap the record contained in source buffer, pass it
- // to appropriate client protocol (alert, handshake, or app)
- // and retrieve the type of unwrapped data
- int type = recordProtocol.unwrap();
- // process the data and return the result
- switch (type) {
- case ContentType.HANDSHAKE:
- case ContentType.CHANGE_CIPHER_SPEC:
- if (handshakeProtocol.getStatus().equals(
- SSLEngineResult.HandshakeStatus.FINISHED)) {
- session = recordProtocol.getSession();
- }
- break;
- case ContentType.APPLICATION_DATA:
- break;
- case ContentType.ALERT:
- if (alertProtocol.isFatalAlert()) {
- alertProtocol.setProcessed();
- if (session != null) {
- session.invalidate();
- }
- String description = "Fatal alert received "
- + alertProtocol.getAlertDescription();
- shutdown();
- throw new SSLException(description);
- } else {
- if (logger != null) {
- logger.println("Warning allert has been received: "
- + alertProtocol.getAlertDescription());
- }
- switch(alertProtocol.getDescriptionCode()) {
- case AlertProtocol.CLOSE_NOTIFY:
- alertProtocol.setProcessed();
- close_notify_was_received = true;
- if (!close_notify_was_sent) {
- closeOutbound();
- closeInbound();
- } else {
- closeInbound();
- shutdown();
- }
- break;
- case AlertProtocol.NO_RENEGOTIATION:
- alertProtocol.setProcessed();
- if (session == null) {
- // message received during the initial
- // handshake
- throw new AlertException(
- AlertProtocol.HANDSHAKE_FAILURE,
- new SSLHandshakeException(
- "Received no_renegotiation "
- + "during the initial handshake"));
- } else {
- // just stop the handshake
- handshakeProtocol.stop();
- }
- break;
- default:
- alertProtocol.setProcessed();
- }
- }
- break;
- }
- return new SSLEngineResult(getEngineStatus(), getHandshakeStatus(),
- recProtIS.consumed(),
- // place the app. data (if any) into the dest. buffers
- // and get the number of produced bytes:
- appData.placeTo(dsts, offset, length));
- } catch (BufferUnderflowException e) {
- // there was not enought data ource buffer to make complete packet
- src.reset();
- return new SSLEngineResult(SSLEngineResult.Status.BUFFER_UNDERFLOW,
- getHandshakeStatus(), 0, 0);
- } catch (AlertException e) {
- // fatal alert occured
- alertProtocol.alert(AlertProtocol.FATAL, e.getDescriptionCode());
- engine_was_closed = true;
- src.reset();
- if (session != null) {
- session.invalidate();
- }
- // shutdown work will be made after the alert will be sent
- // to another peer (by wrap method)
- throw e.getReason();
- } catch (SSLException e) {
- throw e;
- } catch (IOException e) {
- alertProtocol.alert(AlertProtocol.FATAL,
- AlertProtocol.INTERNAL_ERROR);
- engine_was_closed = true;
- // shutdown work will be made after the alert will be sent
- // to another peer (by wrap method)
- throw new SSLException(e.getMessage());
- }
- }
-
- /**
- * Encodes the application data into SSL/TLS record. If handshake status
- * of the engine differs from NOT_HANDSHAKING the operation can work
- * without consuming of the source data.
- * For more information about TLS record fragmentation see
- * TLS v 1 specification (http://www.ietf.org/rfc/rfc2246.txt) p 6.2.
- * @param srcs the source buffers with application data to be encoded
- * into SSL/TLS record.
- * @param offset the offset in the destination buffers array pointing to
- * the first buffer with the source data.
- * @param len specifies the maximum number of buffers to be procesed.
- * @param dst the destination buffer where encoded data will be placed.
- * @see javax.net.ssl.SSLEngine#wrap(ByteBuffer[],int,int,ByteBuffer) method
- * documentation for more information
- */
- @Override
- public SSLEngineResult wrap(ByteBuffer[] srcs, int offset,
- int len, ByteBuffer dst) throws SSLException {
- if (engine_was_shutteddown) {
- return new SSLEngineResult(SSLEngineResult.Status.CLOSED,
- SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING, 0, 0);
- }
- if ((srcs == null) || (dst == null)) {
- throw new IllegalStateException(
- "Some of the input parameters are null");
- }
- if (dst.isReadOnly()) {
- throw new ReadOnlyBufferException();
- }
-
- if (!handshake_started) {
- beginHandshake();
- }
-
- SSLEngineResult.HandshakeStatus handshakeStatus = getHandshakeStatus();
- // If it is an initial handshake or connection closure stage,
- // check if this call was made in spite of handshake status
- if ((session == null || engine_was_closed) && (
- handshakeStatus.equals(
- SSLEngineResult.HandshakeStatus.NEED_UNWRAP) ||
- handshakeStatus.equals(
- SSLEngineResult.HandshakeStatus.NEED_TASK))) {
- return new SSLEngineResult(
- getEngineStatus(), handshakeStatus, 0, 0);
- }
-
- int capacity = dst.remaining();
- int produced = 0;
-
- if (alertProtocol.hasAlert()) {
- // we have an alert to be sent
- if (capacity < recordProtocol.getRecordSize(2)) {
- return new SSLEngineResult(
- SSLEngineResult.Status.BUFFER_OVERFLOW,
- handshakeStatus, 0, 0);
- }
- byte[] alert_data = alertProtocol.wrap();
- // place the alert record into destination
- dst.put(alert_data);
- if (alertProtocol.isFatalAlert()) {
- alertProtocol.setProcessed();
- if (session != null) {
- session.invalidate();
- }
- // fatal alert has been sent, so shut down the engine
- shutdown();
- return new SSLEngineResult(
- SSLEngineResult.Status.CLOSED,
- SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING,
- 0, alert_data.length);
- } else {
- alertProtocol.setProcessed();
- // check if the works on this engine have been done
- if (close_notify_was_sent && close_notify_was_received) {
- shutdown();
- return new SSLEngineResult(SSLEngineResult.Status.CLOSED,
- SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING,
- 0, alert_data.length);
- }
- return new SSLEngineResult(
- getEngineStatus(),
- getHandshakeStatus(),
- 0, alert_data.length);
- }
- }
-
- if (capacity < recordProtocol.getMinRecordSize()) {
- if (logger != null) {
- logger.println("Capacity of the destination("
- +capacity+") < MIN_PACKET_SIZE("
- +recordProtocol.getMinRecordSize()+")");
- }
- return new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW,
- handshakeStatus, 0, 0);
- }
-
- try {
- if (!handshakeStatus.equals(
- SSLEngineResult.HandshakeStatus.NEED_WRAP)) {
- // so we wraps application data
- dataStream.setSourceBuffers(srcs, offset, len);
- if ((capacity < SSLRecordProtocol.MAX_SSL_PACKET_SIZE) &&
- (capacity < recordProtocol.getRecordSize(
- dataStream.available()))) {
- if (logger != null) {
- logger.println("The destination buffer("
- +capacity+") can not take the resulting packet("
- + recordProtocol.getRecordSize(
- dataStream.available())+")");
- }
- return new SSLEngineResult(
- SSLEngineResult.Status.BUFFER_OVERFLOW,
- handshakeStatus, 0, 0);
- }
- if (remaining_wrapped_data == null) {
- remaining_wrapped_data =
- recordProtocol.wrap(ContentType.APPLICATION_DATA,
- dataStream);
- }
- if (capacity < remaining_wrapped_data.length) {
- // It should newer happen because we checked the destination
- // buffer size, but there is a possibility
- // (if dest buffer was filled outside)
- // so we just remember the data into remaining_wrapped_data
- // and will enclose it during the the next call
- return new SSLEngineResult(
- SSLEngineResult.Status.BUFFER_OVERFLOW,
- handshakeStatus, dataStream.consumed(), 0);
- } else {
- dst.put(remaining_wrapped_data);
- produced = remaining_wrapped_data.length;
- remaining_wrapped_data = null;
- return new SSLEngineResult(getEngineStatus(),
- handshakeStatus, dataStream.consumed(), produced);
- }
- } else {
- if (remaining_hsh_data == null) {
- remaining_hsh_data = handshakeProtocol.wrap();
- }
- if (capacity < remaining_hsh_data.length) {
- // It should newer happen because we checked the destination
- // buffer size, but there is a possibility
- // (if dest buffer was filled outside)
- // so we just remember the data into remaining_hsh_data
- // and will enclose it during the the next call
- return new SSLEngineResult(
- SSLEngineResult.Status.BUFFER_OVERFLOW,
- handshakeStatus, 0, 0);
- } else {
- dst.put(remaining_hsh_data);
- produced = remaining_hsh_data.length;
- remaining_hsh_data = null;
-
- handshakeStatus = handshakeProtocol.getStatus();
- if (handshakeStatus.equals(
- SSLEngineResult.HandshakeStatus.FINISHED)) {
- session = recordProtocol.getSession();
- }
- }
- return new SSLEngineResult(
- getEngineStatus(), getHandshakeStatus(), 0, produced);
- }
- } catch (AlertException e) {
- // fatal alert occured
- alertProtocol.alert(AlertProtocol.FATAL, e.getDescriptionCode());
- engine_was_closed = true;
- if (session != null) {
- session.invalidate();
- }
- // shutdown work will be made after the alert will be sent
- // to another peer (by wrap method)
- throw e.getReason();
- }
- }
-
- // Shutdownes the engine and makes all cleanup work.
- private void shutdown() {
- engine_was_closed = true;
- engine_was_shutteddown = true;
- isOutboundDone = true;
- isInboundDone = true;
- if (handshake_started) {
- alertProtocol.shutdown();
- alertProtocol = null;
- handshakeProtocol.shutdown();
- handshakeProtocol = null;
- recordProtocol.shutdown();
- recordProtocol = null;
- }
- }
-
-
- private SSLEngineResult.Status getEngineStatus() {
- return (engine_was_closed)
- ? SSLEngineResult.Status.CLOSED
- : SSLEngineResult.Status.OK;
- }
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLInputStream.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLInputStream.java
deleted file mode 100644
index b2501a7..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLInputStream.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * This class is a base for all input stream classes used
- * in protocol implementation. It extends an InputStream with
- * some additional read methods allowing to read TLS specific
- * data types such as uint8, uint32 etc (see TLS v 1 specification
- * at http://www.ietf.org/rfc/rfc2246.txt).
- */
-public abstract class SSLInputStream extends InputStream {
-
- @Override
- public abstract int available() throws IOException;
-
- /**
- * Reads the following byte value. Note that in the case of
- * reaching of the end of the data this methods throws the
- * exception, not return -1. The type of exception depends
- * on implementation. It was done for simplifying and speeding
- * up of processing of such cases.
- * @see org.apache.harmony.xnet.provider.jsse.SSLStreamedInput#read()
- * @see org.apache.harmony.xnet.provider.jsse.SSLBufferedInput#read()
- * @see org.apache.harmony.xnet.provider.jsse.HandshakeIODataStream#read()
- */
- @Override
- public abstract int read() throws IOException;
-
- @Override
- public long skip(long n) throws IOException {
- long skept = n;
- while (n > 0) {
- read();
- n--;
- }
- return skept;
- }
-
- /**
- * Reads and returns uint8 value.
- */
- public int readUint8() throws IOException {
- return read() & 0x00FF;
- }
-
- /**
- * Reads and returns uint16 value.
- */
- public int readUint16() throws IOException {
- return (read() << 8) | (read() & 0x00FF);
- }
-
- /**
- * Reads and returns uint24 value.
- */
- public int readUint24() throws IOException {
- return (read() << 16) | (read() << 8) | (read() & 0x00FF);
- }
-
- /**
- * Reads and returns uint32 value.
- */
- public long readUint32() throws IOException {
- return (read() << 24) | (read() << 16)
- | (read() << 8) | (read() & 0x00FF);
- }
-
- /**
- * Reads and returns uint64 value.
- */
- public long readUint64() throws IOException {
- // BEGIN android-changed
- long hi = readUint32();
- long lo = readUint32();
- return (hi << 32) | lo;
- // END android-changed
- }
-
- /**
- * Returns the vector of opaque values of specified length;
- * @param length - the length of the vector to be read.
- * @return the read data
- * @throws IOException if read operation could not be finished.
- */
- public byte[] read(int length) throws IOException {
- byte[] res = new byte[length];
- for (int i=0; i<length; i++) {
- res[i] = (byte) read();
- }
- return res;
- }
-
- @Override
- public int read(byte[] b, int off, int len) throws IOException {
- int read_b;
- int i = 0;
- do {
- if ((read_b = read()) == -1) {
- return (i == 0) ? -1 : i;
- }
- b[off+i] = (byte) read_b;
- i++;
- } while ((available() != 0) && (i<len));
- return i;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLParameters.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLParameters.java
deleted file mode 100644
index 9c6f0a0..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLParameters.java
+++ /dev/null
@@ -1,440 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyManagementException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.SecureRandom;
-import java.security.UnrecoverableKeyException;
-import java.security.cert.CertificateEncodingException;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLException;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
-import javax.net.ssl.X509KeyManager;
-import javax.net.ssl.X509TrustManager;
-
-import org.apache.harmony.security.provider.cert.X509CertImpl;
-
-/**
- * The instances of this class incapsulate all the info
- * about enabled cipher suites and protocols,
- * as well as the information about client/server mode of
- * ssl socket, whether it require/want client authentication or not,
- * and controls whether new SSL sessions may be established by this
- * socket or not.
- */
-// BEGIN android-changed
-public class SSLParameters implements Cloneable {
-// END android-changed
-
- // default source of authentication keys
- private static X509KeyManager defaultKeyManager;
- // default source of authentication trust decisions
- private static X509TrustManager defaultTrustManager;
- // default source of random numbers
- private static SecureRandom defaultSecureRandom;
- // default SSL parameters
- private static SSLParameters defaultParameters;
-
- // client session context contains the set of reusable
- // client-side SSL sessions
-// BEGIN android-changed
- private final ClientSessionContext clientSessionContext;
- // server session context contains the set of reusable
- // server-side SSL sessions
- private final ServerSessionContext serverSessionContext;
-// END android-changed
- // source of authentication keys
- private X509KeyManager keyManager;
- // source of authentication trust decisions
- private X509TrustManager trustManager;
- // source of random numbers
- private SecureRandom secureRandom;
-
- // cipher suites available for SSL connection
- // BEGIN android-changed
- private CipherSuite[] enabledCipherSuites;
- // END android-changed
- // string representations of available cipher suites
- private String[] enabledCipherSuiteNames = null;
-
- // protocols available for SSL connection
- private String[] enabledProtocols = ProtocolVersion.supportedProtocols;
-
- // if the peer with this parameters tuned to work in client mode
- private boolean client_mode = true;
- // if the peer with this parameters tuned to require client authentication
- private boolean need_client_auth = false;
- // if the peer with this parameters tuned to request client authentication
- private boolean want_client_auth = false;
- // if the peer with this parameters allowed to cteate new SSL session
- private boolean enable_session_creation = true;
-
-// BEGIN android-changed
- protected CipherSuite[] getEnabledCipherSuitesMember() {
- if (enabledCipherSuites == null) this.enabledCipherSuites = CipherSuite.defaultCipherSuites;
- return enabledCipherSuites;
- }
-// END android-changed
-
- /**
- * Initializes the parameters. Naturally this constructor is used
- * in SSLContextImpl.engineInit method which dirrectly passes its
- * parameters. In other words this constructor holds all
- * the functionality provided by SSLContext.init method.
- * See {@link javax.net.ssl.SSLContext#init(KeyManager[],TrustManager[],
- * SecureRandom)} for more information
- */
- protected SSLParameters(KeyManager[] kms, TrustManager[] tms,
-// BEGIN android-changed
- SecureRandom sr, SSLClientSessionCache clientCache,
- SSLServerSessionCache serverCache)
- throws KeyManagementException {
- this.serverSessionContext
- = new ServerSessionContext(NativeCrypto.SSL_CTX_new(), serverCache);
- this.clientSessionContext
- = new ClientSessionContext(NativeCrypto.SSL_CTX_new(), clientCache);
-// END android-changed
- try {
- // initialize key manager
- boolean initialize_default = false;
- // It's not described by the spec of SSLContext what should happen
- // if the arrays of length 0 are specified. This implementation
- // behave as for null arrays (i.e. use installed security providers)
- if ((kms == null) || (kms.length == 0)) {
- if (defaultKeyManager == null) {
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(
- KeyManagerFactory.getDefaultAlgorithm());
- kmf.init(null, null);
- kms = kmf.getKeyManagers();
- // tell that we are trying to initialize defaultKeyManager
- initialize_default = true;
- } else {
- keyManager = defaultKeyManager;
- }
- }
- if (keyManager == null) { // was not initialized by default
- for (int i = 0; i < kms.length; i++) {
- if (kms[i] instanceof X509KeyManager) {
- keyManager = (X509KeyManager)kms[i];
- break;
- }
- }
- if (keyManager == null) {
- throw new KeyManagementException("No X509KeyManager found");
- }
- if (initialize_default) {
- // found keyManager is default key manager
- defaultKeyManager = keyManager;
- }
- }
-
- // initialize trust manager
- initialize_default = false;
- if ((tms == null) || (tms.length == 0)) {
- if (defaultTrustManager == null) {
- TrustManagerFactory tmf = TrustManagerFactory
- .getInstance(TrustManagerFactory.getDefaultAlgorithm());
- tmf.init((KeyStore)null);
- tms = tmf.getTrustManagers();
- initialize_default = true;
- } else {
- trustManager = defaultTrustManager;
- }
- }
- if (trustManager == null) { // was not initialized by default
- for (int i = 0; i < tms.length; i++) {
- if (tms[i] instanceof X509TrustManager) {
- trustManager = (X509TrustManager)tms[i];
- break;
- }
- }
- if (trustManager == null) {
- throw new KeyManagementException("No X509TrustManager found");
- }
- if (initialize_default) {
- // found trustManager is default trust manager
- defaultTrustManager = trustManager;
-// BEGIN android-added
- if (trustManager instanceof TrustManagerImpl) {
- ((TrustManagerImpl) trustManager).indexTrustAnchors();
- }
-// END android-added
- }
- }
- } catch (NoSuchAlgorithmException e) {
- throw new KeyManagementException(e);
- } catch (KeyStoreException e) {
- throw new KeyManagementException(e);
- } catch (UnrecoverableKeyException e) {
- throw new KeyManagementException(e);
-// BEGIN android-added
- } catch (CertificateEncodingException e) {
- throw new KeyManagementException(e);
- } catch (InvalidAlgorithmParameterException e) {
- throw new KeyManagementException(e);
-// END android-added
- }
- // initialize secure random
- // BEGIN android-removed
- // if (sr == null) {
- // if (defaultSecureRandom == null) {
- // defaultSecureRandom = new SecureRandom();
- // }
- // secureRandom = defaultSecureRandom;
- // } else {
- // secureRandom = sr;
- // }
- // END android-removed
- // BEGIN android-added
- // We simply use the SecureRandom passed in by the caller. If it's
- // null, we don't replace it by a new instance. The native code below
- // then directly accesses /dev/urandom. Not the most elegant solution,
- // but faster than going through the SecureRandom object.
- secureRandom = sr;
- // END android-added
- }
-
- protected static SSLParameters getDefault() throws KeyManagementException {
- if (defaultParameters == null) {
-// BEGIN android-changed
- defaultParameters = new SSLParameters(null, null, null, null, null);
-// END android-changed
- }
- return (SSLParameters) defaultParameters.clone();
- }
-
- /**
- * @return server session context
- */
-// BEGIN android-changed
- protected ServerSessionContext getServerSessionContext() {
-// END android-changed
- return serverSessionContext;
- }
-
- /**
- * @return client session context
- */
-// BEGIN android-changed
- protected ClientSessionContext getClientSessionContext() {
-// END android-changed
- return clientSessionContext;
- }
-
- /**
- * @return key manager
- */
- protected X509KeyManager getKeyManager() {
- return keyManager;
- }
-
- /**
- * @return trust manager
- */
- protected X509TrustManager getTrustManager() {
- return trustManager;
- }
-
- /**
- * @return secure random
- */
- protected SecureRandom getSecureRandom() {
- // BEGIN android-removed
- // return secureRandom;
- // END android-removed
- // BEGIN android-added
- if (secureRandom != null) return secureRandom;
- if (defaultSecureRandom == null)
- {
- defaultSecureRandom = new SecureRandom();
- }
- secureRandom = defaultSecureRandom;
- // END android-added
- return secureRandom;
- }
-
- // BEGIN android-added
- /**
- * @return the secure random member reference, even it is null
- */
- protected SecureRandom getSecureRandomMember() {
- return secureRandom;
- }
- // END android-added
-
- /**
- * @return the names of enabled cipher suites
- */
- protected String[] getEnabledCipherSuites() {
- if (enabledCipherSuiteNames == null) {
- // BEGIN android-added
- CipherSuite[] enabledCipherSuites = getEnabledCipherSuitesMember();
- // END android-added
- enabledCipherSuiteNames = new String[enabledCipherSuites.length];
- for (int i = 0; i< enabledCipherSuites.length; i++) {
- enabledCipherSuiteNames[i] = enabledCipherSuites[i].getName();
- }
- }
- return enabledCipherSuiteNames.clone();
- }
-
- /**
- * Sets the set of available cipher suites for use in SSL connection.
- * @param suites: String[]
- * @return
- */
- protected void setEnabledCipherSuites(String[] suites) {
- if (suites == null) {
- throw new IllegalArgumentException("Provided parameter is null");
- }
- CipherSuite[] cipherSuites = new CipherSuite[suites.length];
- for (int i=0; i<suites.length; i++) {
- cipherSuites[i] = CipherSuite.getByName(suites[i]);
- if (cipherSuites[i] == null || !cipherSuites[i].supported) {
- throw new IllegalArgumentException(suites[i] +
- " is not supported.");
- }
- }
- enabledCipherSuites = cipherSuites;
- enabledCipherSuiteNames = suites;
- }
-
- /**
- * @return the set of enabled protocols
- */
- protected String[] getEnabledProtocols() {
- return enabledProtocols.clone();
- }
-
- /**
- * Sets the set of available protocols for use in SSL connection.
- * @param protocols String[]
- */
- protected void setEnabledProtocols(String[] protocols) {
- if (protocols == null) {
- throw new IllegalArgumentException("Provided parameter is null");
- }
- for (int i=0; i<protocols.length; i++) {
- if (!ProtocolVersion.isSupported(protocols[i])) {
- throw new IllegalArgumentException("Protocol " + protocols[i] +
- " is not supported.");
- }
- }
- enabledProtocols = protocols;
- }
-
- /**
- * Tunes the peer holding this parameters to work in client mode.
- * @param mode if the peer is configured to work in client mode
- */
- protected void setUseClientMode(boolean mode) {
- client_mode = mode;
- }
-
- /**
- * Returns the value indicating if the parameters configured to work
- * in client mode.
- */
- protected boolean getUseClientMode() {
- return client_mode;
- }
-
- /**
- * Tunes the peer holding this parameters to require client authentication
- */
- protected void setNeedClientAuth(boolean need) {
- need_client_auth = need;
- // reset the want_client_auth setting
- want_client_auth = false;
- }
-
- /**
- * Returns the value indicating if the peer with this parameters tuned
- * to require client authentication
- */
- protected boolean getNeedClientAuth() {
- return need_client_auth;
- }
-
- /**
- * Tunes the peer holding this parameters to request client authentication
- */
- protected void setWantClientAuth(boolean want) {
- want_client_auth = want;
- // reset the need_client_auth setting
- need_client_auth = false;
- }
-
- /**
- * Returns the value indicating if the peer with this parameters
- * tuned to request client authentication
- * @return
- */
- protected boolean getWantClientAuth() {
- return want_client_auth;
- }
-
- /**
- * Allows/disallows the peer holding this parameters to
- * create new SSL session
- */
- protected void setEnableSessionCreation(boolean flag) {
- enable_session_creation = flag;
- }
-
- /**
- * Returns the value indicating if the peer with this parameters
- * allowed to cteate new SSL session
- */
- protected boolean getEnableSessionCreation() {
- return enable_session_creation;
- }
-
- /**
- * Returns the clone of this object.
- * @return the clone.
- */
- @Override
- protected Object clone() {
-// BEGIN android-changed
- try {
- return super.clone();
- } catch (CloneNotSupportedException e) {
- throw new AssertionError(e);
- }
-// END android-changed
- }
-
- /**
- * Gets the default trust manager.
- *
- * TODO: Move this to a published API under dalvik.system.
- */
- public static X509TrustManager getDefaultTrustManager() {
- return defaultTrustManager;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLRecordProtocol.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLRecordProtocol.java
deleted file mode 100644
index 423a817..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLRecordProtocol.java
+++ /dev/null
@@ -1,482 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.AlertException;
-import org.apache.harmony.xnet.provider.jsse.SSLSessionImpl;
-import org.apache.harmony.xnet.provider.jsse.SSLInputStream;
-
-import java.io.IOException;
-import javax.net.ssl.SSLProtocolException;
-
-/**
- * This class performs functionality dedicated to SSL record layer.
- * It unpacks and routes income data to the appropriate
- * client protocol (handshake, alert, application data protocols)
- * and packages outcome data into SSL/TLS records.
- * Initially created object has null connection state and does not
- * perform any cryptography computations over the income/outcome data.
- * After handshake protocol agreed upon security parameters they are placed
- * into SSLSessionImpl object and available for record protocol as
- * pending session. The order of setting up of the pending session
- * as an active session differs for client and server modes.
- * So for client mode the parameters are provided by handshake protocol
- * during retrieving of change_cipher_spec message to be sent (by calling of
- * getChangeCipherSpecMesage method).
- * For server side mode record protocol retrieves the parameters from
- * handshake protocol after receiving of client's change_cipher_spec message.
- * After the pending session has been setted up as a curent session,
- * new connectin state object is created and used for encryption/decryption
- * of the messages.
- * Among with base functionality this class provides the information about
- * constrains on the data length, and information about correspondance
- * of plain and encrypted data lengths.
- * For more information on TLS v1 see http://www.ietf.org/rfc/rfc2246.txt,
- * on SSL v3 see http://wp.netscape.com/eng/ssl3,
- * on SSL v2 see http://wp.netscape.com/eng/security/SSL_2.html.
- */
-public class SSLRecordProtocol {
-
- /**
- * Maximum length of allowed plain data fragment
- * as specified by TLS specification.
- */
- protected static int MAX_DATA_LENGTH = 16384; // 2^14
- /**
- * Maximum length of allowed compressed data fragment
- * as specified by TLS specification.
- */
- protected static int MAX_COMPRESSED_DATA_LENGTH
- = MAX_DATA_LENGTH + 1024;
- /**
- * Maximum length of allowed ciphered data fragment
- * as specified by TLS specification.
- */
- protected static int MAX_CIPHERED_DATA_LENGTH
- = MAX_COMPRESSED_DATA_LENGTH + 1024;
- /**
- * Maximum length of ssl record. It is counted as:
- * type(1) + version(2) + length(2) + MAX_CIPHERED_DATA_LENGTH
- */
- protected static int MAX_SSL_PACKET_SIZE
- = MAX_CIPHERED_DATA_LENGTH + 5;
- // the SSL session used for connection
- private SSLSessionImpl session;
- // protocol version of the connection
- private byte[] version;
- // input stream of record protocol
- private SSLInputStream in;
- // handshake protocol object to which handshaking data will be transmitted
- private HandshakeProtocol handshakeProtocol;
- // alert protocol to indicate alerts occured/received
- private AlertProtocol alertProtocol;
- // application data object to which application data will be transmitted
- private org.apache.harmony.xnet.provider.jsse.Appendable appData;
- // connection state holding object
- private ConnectionState
- activeReadState, activeWriteState, pendingConnectionState;
-
- // logger
- private Logger.Stream logger = Logger.getStream("record");
-
- // flag indicating if session object has been changed after
- // handshake phase (to distinguish session pending state)
- private boolean sessionWasChanged = false;
-
- // change cipher spec message content
- private static final byte[] change_cipher_spec_byte = new byte[] {1};
-
- /**
- * Creates an instance of record protocol and tunes
- * up the client protocols to use ut.
- * @param handshakeProtocol: HandshakeProtocol
- * @param alertProtocol: AlertProtocol
- * @param in: SSLInputStream
- * @param appData: Appendable
- */
- protected SSLRecordProtocol(HandshakeProtocol handshakeProtocol,
- AlertProtocol alertProtocol,
- SSLInputStream in,
- Appendable appData) {
- this.handshakeProtocol = handshakeProtocol;
- this.handshakeProtocol.setRecordProtocol(this);
- this.alertProtocol = alertProtocol;
- this.alertProtocol.setRecordProtocol(this);
- this.in = in;
- this.appData = appData;
- }
-
- /**
- * Returns the session obtained during the handshake negotiation.
- * If the handshake process was not compleated, method returns null.
- * @return the session in effect.
- */
- protected SSLSessionImpl getSession() {
- return session;
- }
-
- /**
- * Returns the minimum possible length of the SSL record.
- * @return
- */
- protected int getMinRecordSize() {
- return (activeReadState == null)
- ? 6 // type + version + length + 1 byte of data
- : 5 + activeReadState.getMinFragmentSize();
- }
-
- /**
- * Returns the record length for the specified incoming data length.
- * If actual resulting record length is greater than
- * MAX_CIPHERED_DATA_LENGTH, MAX_CIPHERED_DATA_LENGTH is returned.
- */
- protected int getRecordSize(int data_size) {
- if (activeWriteState == null) {
- return 5+data_size; // type + version + length + data_size
- } else {
- int res = 5 + activeWriteState.getFragmentSize(data_size);
- return (res > MAX_CIPHERED_DATA_LENGTH)
- ? MAX_CIPHERED_DATA_LENGTH // so the source data should be
- // splitted into several packets
- : res;
- }
- }
-
- /**
- * Returns the upper bound of length of data containing in the record with
- * specified length.
- * If the provided record_size is greater or equal to
- * MAX_CIPHERED_DATA_LENGTH the returned value will be
- * MAX_DATA_LENGTH
- * counted as for data with
- * MAX_CIPHERED_DATA_LENGTH length.
- */
- protected int getDataSize(int record_size) {
- record_size -= 5; // - (type + version + length + data_size)
- if (record_size > MAX_CIPHERED_DATA_LENGTH) {
- // the data of such size consists of the several packets
- return MAX_DATA_LENGTH;
- }
- if (activeReadState == null) {
- return record_size;
- }
- return activeReadState.getContentSize(record_size);
- }
-
- /**
- * Depending on the Connection State (Session) encrypts and compress
- * the provided data, and packs it into TLSCiphertext structure.
- * @param content_type: int
- * @param fragment: byte[]
- * @return ssl packet created over the current connection state
- */
- protected byte[] wrap(byte content_type, DataStream dataStream) {
- byte[] fragment = dataStream.getData(MAX_DATA_LENGTH);
- return wrap(content_type, fragment, 0, fragment.length);
- }
-
- /**
- * Depending on the Connection State (Session) encrypts and compress
- * the provided data, and packs it into TLSCiphertext structure.
- * @param content_type: int
- * @param fragment: byte[]
- * @return ssl packet created over the current connection state
- */
- protected byte[] wrap(byte content_type,
- byte[] fragment, int offset, int len) {
- if (logger != null) {
- logger.println("SSLRecordProtocol.wrap: TLSPlaintext.fragment["
- +len+"]:");
- logger.print(fragment, offset, len);
- }
- if (len > MAX_DATA_LENGTH) {
- throw new AlertException(
- AlertProtocol.INTERNAL_ERROR,
- new SSLProtocolException(
- "The provided chunk of data is too big: " + len
- + " > MAX_DATA_LENGTH == "+MAX_DATA_LENGTH));
- }
- byte[] ciphered_fragment = fragment;
- if (activeWriteState != null) {
- ciphered_fragment =
- activeWriteState.encrypt(content_type, fragment, offset, len);
- if (ciphered_fragment.length > MAX_CIPHERED_DATA_LENGTH) {
- throw new AlertException(
- AlertProtocol.INTERNAL_ERROR,
- new SSLProtocolException(
- "The ciphered data increased more than on 1024 bytes"));
- }
- if (logger != null) {
- logger.println("SSLRecordProtocol.wrap: TLSCiphertext.fragment["
- +ciphered_fragment.length+"]:");
- logger.print(ciphered_fragment);
- }
- }
- return packetize(content_type, version, ciphered_fragment);
- }
-
- private byte[] packetize(byte type, byte[] version, byte[] fragment) {
- byte[] buff = new byte[5+fragment.length];
- buff[0] = type;
- if (version != null) {
- buff[1] = version[0];
- buff[2] = version[1];
- } else {
- buff[1] = 3;
- buff[2] = 1;
- }
- buff[3] = (byte) ((0x00FF00 & fragment.length) >> 8);
- buff[4] = (byte) (0x0000FF & fragment.length);
- System.arraycopy(fragment, 0, buff, 5, fragment.length);
- return buff;
- }
-
- /**
- * Set the ssl session to be used after sending the changeCipherSpec message
- * @param session: SSLSessionImpl
- */
- private void setSession(SSLSessionImpl session) {
- if (!sessionWasChanged) {
- // session was not changed for current handshake process
- if (logger != null) {
- logger.println("SSLRecordProtocol.setSession: Set pending session");
- logger.println(" cipher name: " + session.getCipherSuite());
- }
- this.session = session;
- // create new connection state
- pendingConnectionState = ((version == null) || (version[1] == 1))
- ? (ConnectionState) new ConnectionStateTLS(getSession())
- : (ConnectionState) new ConnectionStateSSLv3(getSession());
- sessionWasChanged = true;
- } else {
- // wait for rehandshaking's session
- sessionWasChanged = false;
- }
- }
-
- /**
- * Returns the change cipher spec message to be sent to another peer.
- * The pending connection state will be built on the base of provided
- * session object
- * The calling of this method triggers pending write connection state to
- * be active.
- * @return ssl record containing the "change cipher spec" message.
- */
- protected byte[] getChangeCipherSpecMesage(SSLSessionImpl session) {
- // make change_cipher_spec_message:
- byte[] change_cipher_spec_message;
- if (activeWriteState == null) {
- change_cipher_spec_message = new byte[] {
- ContentType.CHANGE_CIPHER_SPEC, version[0],
- version[1], 0, 1, 1
- };
- } else {
- change_cipher_spec_message =
- packetize(ContentType.CHANGE_CIPHER_SPEC, version,
- activeWriteState.encrypt(ContentType.CHANGE_CIPHER_SPEC,
- change_cipher_spec_byte, 0, 1));
- }
- setSession(session);
- activeWriteState = pendingConnectionState;
- if (logger != null) {
- logger.println("SSLRecordProtocol.getChangeCipherSpecMesage");
- logger.println("activeWriteState = pendingConnectionState");
- logger.print(change_cipher_spec_message);
- }
- return change_cipher_spec_message;
- }
-
- /**
- * Retrieves the fragment field of TLSCiphertext, and than
- * depending on the established Connection State
- * decrypts and decompresses it. The following structure is expected
- * on the input at the moment of the call:
- *
- * struct {
- * ContentType type;
- * ProtocolVersion version;
- * uint16 length;
- * select (CipherSpec.cipher_type) {
- * case stream: GenericStreamCipher;
- * case block: GenericBlockCipher;
- * } fragment;
- * } TLSCiphertext;
- *
- * (as specified by RFC 2246, TLS v1 Protocol specification)
- *
- * In addition this method can recognize SSLv2 hello message which
- * are often used to establish the SSL/TLS session.
- *
- * @throws IOException if some io errors have been occured
- * @throws EndOfSourceException if underlying input stream
- * has ran out of data.
- * @throws EndOfBufferException if there was not enought data
- * to build complete ssl packet.
- * @return the type of unwrapped message.
- */
- protected int unwrap() throws IOException {
- if (logger != null) {
- logger.println("SSLRecordProtocol.unwrap: BEGIN [");
- }
- int type = in.readUint8();
- if ((type < ContentType.CHANGE_CIPHER_SPEC)
- || (type > ContentType.APPLICATION_DATA)) {
- if (logger != null) {
- logger.println("Non v3.1 message type:" + type);
- }
- if (type >= 0x80) {
- // it is probably SSL v2 client_hello message
- // (see SSL v2 spec at:
- // http://wp.netscape.com/eng/security/SSL_2.html)
- int length = (type & 0x7f) << 8 | in.read();
- byte[] fragment = in.read(length);
- handshakeProtocol.unwrapSSLv2(fragment);
- if (logger != null) {
- logger.println(
- "SSLRecordProtocol:unwrap ] END, SSLv2 type");
- }
- return ContentType.HANDSHAKE;
- }
- throw new AlertException(AlertProtocol.UNEXPECTED_MESSAGE,
- new SSLProtocolException(
- "Unexpected message type has been received: "+type));
- }
- if (logger != null) {
- logger.println("Got the message of type: " + type);
- }
- if (version != null) {
- if ((in.read() != version[0])
- || (in.read() != version[1])) {
- throw new AlertException(AlertProtocol.UNEXPECTED_MESSAGE,
- new SSLProtocolException(
- "Unexpected message type has been received: " +
- type));
- }
- } else {
- in.skip(2); // just skip the version number
- }
- int length = in.readUint16();
- if (logger != null) {
- logger.println("TLSCiphertext.fragment["+length+"]: ...");
- }
- if (length > MAX_CIPHERED_DATA_LENGTH) {
- throw new AlertException(AlertProtocol.RECORD_OVERFLOW,
- new SSLProtocolException(
- "Received message is too big."));
- }
- byte[] fragment = in.read(length);
- if (logger != null) {
- logger.print(fragment);
- }
- if (activeReadState != null) {
- fragment = activeReadState.decrypt((byte) type, fragment);
- if (logger != null) {
- logger.println("TLSPlaintext.fragment:");
- logger.print(fragment);
- }
- }
- if (fragment.length > MAX_DATA_LENGTH) {
- throw new AlertException(AlertProtocol.DECOMPRESSION_FAILURE,
- new SSLProtocolException(
- "Decompressed plain data is too big."));
- }
- switch (type) {
- case ContentType.CHANGE_CIPHER_SPEC:
- // notify handshake protocol:
- handshakeProtocol.receiveChangeCipherSpec();
- setSession(handshakeProtocol.getSession());
- // change cipher spec message has been received, so:
- if (logger != null) {
- logger.println("activeReadState = pendingConnectionState");
- }
- activeReadState = pendingConnectionState;
- break;
- case ContentType.ALERT:
- alert(fragment[0], fragment[1]);
- break;
- case ContentType.HANDSHAKE:
- handshakeProtocol.unwrap(fragment);
- break;
- case ContentType.APPLICATION_DATA:
- if (logger != null) {
- logger.println(
- "TLSCiphertext.unwrap: APP DATA["+length+"]:");
- logger.println(new String(fragment));
- }
- appData.append(fragment);
- break;
- default:
- throw new AlertException(AlertProtocol.UNEXPECTED_MESSAGE,
- new SSLProtocolException(
- "Unexpected message type has been received: " +
- type));
- }
- if (logger != null) {
- logger.println("SSLRecordProtocol:unwrap ] END, type: " + type);
- }
- return type;
- }
-
- /**
- * Passes the alert information to the alert protocol.
- * @param level: byte
- * @param description: byte
- */
- protected void alert(byte level, byte description) {
- if (logger != null) {
- logger.println("SSLRecordProtocol.allert: "+level+" "+description);
- }
- alertProtocol.alert(level, description);
- }
-
- /**
- * Sets up the SSL version used in this connection.
- * This method is calling from the hanshake protocol after
- * it becomes known witch protocol version will be used.
- * @param ver: byte[]
- * @return
- */
- protected void setVersion(byte[] ver) {
- this.version = ver;
- }
-
- /**
- * Shutdownes the protocol. It will be impossiblke to use the instance
- * after the calling of this method.
- */
- protected void shutdown() {
- session = null;
- version = null;
- in = null;
- handshakeProtocol = null;
- alertProtocol = null;
- appData = null;
- if (pendingConnectionState != null) {
- pendingConnectionState.shutdown();
- }
- pendingConnectionState = null;
- if (activeReadState != null) {
- activeReadState.shutdown();
- }
- activeReadState = null;
- if (activeReadState != null) {
- activeReadState.shutdown();
- }
- activeWriteState = null;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLServerSessionCache.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLServerSessionCache.java
deleted file mode 100644
index 32a0e72..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLServerSessionCache.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import javax.net.ssl.SSLSession;
-
-/**
- * A persistent {@link javax.net.ssl.SSLSession} cache used by
- * {@link javax.net.ssl.SSLSessionContext} to share server-side SSL sessions
- * across processes. For example, this cache enables one server to resume
- * a session started by a different server based on a session ID provided
- * by the client.
- *
- * <p>The {@code SSLSessionContext} implementation converts
- * {@code SSLSession}s into raw bytes and vice versa. The exact makeup of the
- * session data is dependent upon the caller's implementation and is opaque to
- * the {@code SSLServerSessionCache} implementation.
- */
-public interface SSLServerSessionCache {
-
- /**
- * Gets the session data for given session ID.
- *
- * @param id from {@link javax.net.ssl.SSLSession#getId()}
- * @return the session data or null if none is cached
- * @throws NullPointerException if id is null
- */
- public byte[] getSessionData(byte[] id);
-
- /**
- * Stores session data for the given session.
- *
- * @param session to cache data for
- * @param sessionData to cache
- * @throws NullPointerException if session or data is null
- */
- public void putSessionData(SSLSession session, byte[] sessionData);
-} \ No newline at end of file
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLSessionImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLSessionImpl.java
deleted file mode 100644
index 922de2b..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLSessionImpl.java
+++ /dev/null
@@ -1,366 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.security.AccessControlContext;
-import java.security.AccessController;
-import java.security.Principal;
-import java.security.SecureRandom;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateEncodingException;
-import java.security.cert.X509Certificate;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Vector;
-
-import javax.net.ssl.SSLPeerUnverifiedException;
-import javax.net.ssl.SSLPermission;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSessionBindingEvent;
-import javax.net.ssl.SSLSessionBindingListener;
-import javax.net.ssl.SSLSessionContext;
-
-/**
- *
- * SSLSession implementation
- *
- * @see javax.net.ssl.SSLSession
- */
-public class SSLSessionImpl implements SSLSession, Cloneable {
-
- /**
- * Session object reporting an invalid cipher suite of "SSL_NULL_WITH_NULL_NULL"
- */
- public static final SSLSessionImpl NULL_SESSION = new SSLSessionImpl(null);
-
- /**
- * Container class for the 'value' map's keys.
- */
- private static final class ValueKey {
- final String name;
- final AccessControlContext acc;
-
- ValueKey(String name) {
- super();
- this.name = name;
- this.acc = AccessController.getContext();
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((acc == null) ? 0 : acc.hashCode());
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (!(obj instanceof ValueKey))
- return false;
- ValueKey other = (ValueKey) obj;
- if (acc == null) {
- if (other.acc != null)
- return false;
- } else if (!acc.equals(other.acc))
- return false;
- if (name == null) {
- if (other.name != null)
- return false;
- } else if (!name.equals(other.name))
- return false;
- return true;
- }
- }
-
- private long creationTime;
- private boolean isValid = true;
- private Map<ValueKey, Object> values = new HashMap<ValueKey, Object>();
-
- /**
- * ID of the session
- */
- byte[] id;
-
- /**
- * Last time the session was accessed
- */
- long lastAccessedTime;
-
- /**
- * Protocol used in the session
- */
- ProtocolVersion protocol;
-
- /**
- * CipherSuite used in the session
- */
- CipherSuite cipherSuite;
-
- /**
- * Context of the session
- */
-// BEGIN android-changed
- SSLSessionContext context;
-// END android-changed
-
- /**
- * certificates were sent to the peer
- */
- X509Certificate[] localCertificates;
-
- /**
- * Peer certificates
- */
- X509Certificate[] peerCertificates;
-
- /**
- * Peer host name
- */
- private String peerHost;
-
- /**
- * Peer port number
- */
- private int peerPort = -1;
-
- /**
- * Master secret
- */
- byte[] master_secret;
-
- /**
- * clientRandom
- */
- byte[] clientRandom;
-
- /**
- * serverRandom
- */
- byte[] serverRandom;
-
- /**
- * True if this entity is considered the server
- */
- final boolean isServer;
-
- /**
- * Creates SSLSession implementation
- *
- * @param cipher_suite
- * @param sr
- */
- public SSLSessionImpl(CipherSuite cipher_suite, SecureRandom sr) {
- creationTime = System.currentTimeMillis();
- lastAccessedTime = creationTime;
- if (cipher_suite == null) {
- this.cipherSuite = CipherSuite.TLS_NULL_WITH_NULL_NULL;
- id = new byte[0];
- isServer = false;
- isValid = false;
- } else {
- this.cipherSuite = cipher_suite;
- id = new byte[32];
- sr.nextBytes(id);
- long time = creationTime / 1000;
- id[28] = (byte) ((time & 0xFF000000) >>> 24);
- id[29] = (byte) ((time & 0x00FF0000) >>> 16);
- id[30] = (byte) ((time & 0x0000FF00) >>> 8);
- id[31] = (byte) ((time & 0x000000FF));
- isServer = true;
- }
-
- }
-
- /**
- * Creates SSLSession implementation
- *
- * @param sr
- */
- public SSLSessionImpl(SecureRandom sr) {
- this(null, sr);
- }
-
- public int getApplicationBufferSize() {
- return SSLRecordProtocol.MAX_DATA_LENGTH;
- }
-
- public String getCipherSuite() {
- return cipherSuite.getName();
- }
-
- public long getCreationTime() {
- return creationTime;
- }
-
- public byte[] getId() {
- return id;
- }
-
- public long getLastAccessedTime() {
- return lastAccessedTime;
- }
-
- public Certificate[] getLocalCertificates() {
- return localCertificates;
- }
-
- public Principal getLocalPrincipal() {
- if (localCertificates != null && localCertificates.length > 0) {
- return localCertificates[0].getSubjectX500Principal();
- }
- return null;
- }
-
- public int getPacketBufferSize() {
- return SSLRecordProtocol.MAX_SSL_PACKET_SIZE;
- }
-
- public javax.security.cert.X509Certificate[] getPeerCertificateChain()
- throws SSLPeerUnverifiedException {
- if (peerCertificates == null) {
- throw new SSLPeerUnverifiedException("No peer certificate");
- }
- javax.security.cert.X509Certificate[] certs = new javax.security.cert.X509Certificate[peerCertificates.length];
- for (int i = 0; i < certs.length; i++) {
- try {
- certs[i] = javax.security.cert.X509Certificate.getInstance(peerCertificates[i]
- .getEncoded());
- } catch (javax.security.cert.CertificateException e) {
- } catch (CertificateEncodingException e) {
- }
- }
- return certs;
- }
-
- public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException {
- if (peerCertificates == null) {
- throw new SSLPeerUnverifiedException("No peer certificate");
- }
- return peerCertificates;
- }
-
- public String getPeerHost() {
- return peerHost;
- }
-
- public int getPeerPort() {
- return peerPort;
- }
-
- public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
- if (peerCertificates == null) {
- throw new SSLPeerUnverifiedException("No peer certificate");
- }
- return peerCertificates[0].getSubjectX500Principal();
- }
-
- public String getProtocol() {
- return (protocol == null) ? "NONE" : protocol.name;
- }
-
- public SSLSessionContext getSessionContext() {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(new SSLPermission("getSSLSessionContext"));
- }
- return context;
- }
-
- public Object getValue(String name) {
- if (name == null) {
- throw new IllegalArgumentException("Parameter is null");
- }
- return values.get(new ValueKey(name));
- }
-
- public String[] getValueNames() {
- final Vector<String> v = new Vector<String>();
- final AccessControlContext currAcc = AccessController.getContext();
- for (ValueKey key : values.keySet()) {
- if ((currAcc == null && key.acc == null)
- || (currAcc != null && currAcc.equals(key.acc))) {
- v.add(key.name);
- }
- }
- return v.toArray(new String[v.size()]);
- }
-
- public void invalidate() {
- isValid = false;
- context = null;
- }
-
- public boolean isValid() {
- if (isValid && context != null && context.getSessionTimeout() != 0
- && lastAccessedTime + context.getSessionTimeout() > System.currentTimeMillis()) {
- isValid = false;
- }
- return isValid;
- }
-
- public void putValue(String name, Object value) {
- if (name == null || value == null) {
- throw new IllegalArgumentException("Parameter is null");
- }
- Object old = values.put(new ValueKey(name), value);
- if (value instanceof SSLSessionBindingListener) {
- ((SSLSessionBindingListener) value).valueBound(new SSLSessionBindingEvent(this, name));
- }
- if (old instanceof SSLSessionBindingListener) {
- ((SSLSessionBindingListener) old).valueUnbound(new SSLSessionBindingEvent(this, name));
- }
-
- }
-
- public void removeValue(String name) {
- if (name == null) {
- throw new IllegalArgumentException("Parameter is null");
- }
- Object old = values.remove(new ValueKey(name));
- if (old instanceof SSLSessionBindingListener) {
- SSLSessionBindingListener listener = (SSLSessionBindingListener) old;
- listener.valueUnbound(new SSLSessionBindingEvent(this, name));
- }
- }
-
- @Override
- public Object clone() {
- try {
- return super.clone();
- } catch (CloneNotSupportedException e) {
- throw new AssertionError(e);
- }
- }
-
- /**
- * Sets the address of the peer
- *
- * @param peerHost
- * @param peerPort
- */
- void setPeer(String peerHost, int peerPort) {
- this.peerHost = peerHost;
- this.peerPort = peerPort;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLStreamedInput.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLStreamedInput.java
deleted file mode 100644
index c040653..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLStreamedInput.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * This class acts like a filtered input stream: it takes
- * the bytes from another InputStream.
- */
-public class SSLStreamedInput extends SSLInputStream {
-
- private InputStream in;
-
- public SSLStreamedInput(InputStream in) {
- this.in = in;
- }
-
- @Override
- public int available() throws IOException {
- return in.available();
- }
-
- /**
- * Read an opaque value from the stream.
- * @return the value read from the underlying stream.
- * @throws IOException if the data could not be read from
- * the underlying stream
- * @throws org.apache.harmony.xnet.provider.jsse.EndOfSourceException if the end of the underlying
- * stream has been reached.
- */
- @Override
- public int read() throws IOException {
- int res = in.read();
- if (res < 0) {
- throw new EndOfSourceException();
- }
- return res;
- }
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLv3Constants.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLv3Constants.java
deleted file mode 100644
index 07aaca8..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLv3Constants.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-/**
- *
- * Contains SSL 3.0 constants
- * @see <a href="http://wp.netscape.com/eng/ssl3">SSL 3.0 Spec.</a>
- */
-public class SSLv3Constants {
-
- /**
- * Client is a sender. Used in hash calculating for finished message.
- * @see <a href="http://wp.netscape.com/eng/ssl3">SSL 3.0 Spec., 5.6.9
- * Finished</a>
- */
- static final byte[] client = new byte[] { 0x43, 0x4C, 0x4E, 0x54 };
-
- /**
- * Server is a sender. Used in hash calculating for finished message.
- * @see <a href="http://wp.netscape.com/eng/ssl3">SSL 3.0 Spec., 5.6.9
- * Finished</a>
- */
- static final byte[] server = new byte[] { 0x53, 0x52, 0x56, 0x52 };
-
- /**
- * pad_1 for MD5
- * @see <a href="http://wp.netscape.com/eng/ssl3">SSL 3.0 Spec., 5.2.3.1
- * Null or standard stream cipher</a>
- */
- static final byte[] MD5pad1 = new byte[] { 0x36, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36 };
-
- /**
- * pad_1 for SHA
- * @see <a href="http://wp.netscape.com/eng/ssl3">SSL 3.0 Spec., 5.2.3.1
- * Null or standard stream cipher</a>
- */
- static final byte[] SHApad1 = new byte[] { 0x36, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0x36 };
-
- /**
- * pad_2 for MD5
- * @see <a href="http://wp.netscape.com/eng/ssl3">SSL 3.0 Spec., 5.2.3.1
- * Null or standard stream cipher</a>
- */
- static final byte[] MD5pad2 = new byte[] { 0x5C, 0x5C, 0x5C, 0x5C,
- 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
- 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
- 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
- 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C };
-
- /**
- * pad_2 for SHA
- * @see <a href="http://wp.netscape.com/eng/ssl3">SSL 3.0 Spec., 5.2.3.1
- * Null or standard stream cipher</a>
- */
- static final byte[] SHApad2 = new byte[] { 0x5C, 0x5C, 0x5C, 0x5C,
- 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
- 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
- 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
- 0x5C, 0x5C, 0x5C };
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHandshakeImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHandshakeImpl.java
deleted file mode 100644
index b76c42f..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHandshakeImpl.java
+++ /dev/null
@@ -1,724 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.SSLv3Constants;
-import org.apache.harmony.xnet.provider.jsse.SSLSessionImpl;
-import org.apache.harmony.xnet.provider.jsse.ProtocolVersion;
-
-import java.io.IOException;
-import java.math.BigInteger;
-import java.security.AccessController;
-import java.security.KeyFactory;
-import java.security.KeyPair;
-import java.security.KeyPairGenerator;
-import java.security.NoSuchAlgorithmException;
-import java.security.PrivateKey;
-import java.security.PrivilegedExceptionAction;
-import java.security.PublicKey;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-import java.security.interfaces.RSAPublicKey;
-
-import java.util.Arrays;
-
-import javax.crypto.Cipher;
-import javax.crypto.KeyAgreement;
-import javax.crypto.interfaces.DHPublicKey;
-import javax.crypto.spec.DHParameterSpec;
-import javax.crypto.spec.DHPublicKeySpec;
-import javax.net.ssl.X509ExtendedKeyManager;
-import javax.net.ssl.X509KeyManager;
-import javax.net.ssl.X509TrustManager;
-
-/**
- * Server side handshake protocol implementation.
- * Handshake protocol operates on top of the Record Protocol.
- * It responsible for negotiating a session.
- *
- * The implementation processes inbound client handshake messages,
- * creates and sends respond messages. Outbound messages are supplied
- * to Record Protocol. Detected errors are reported to the Alert protocol.
- *
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7.4.
- * Handshake protocol.</a>
- *
- */
-public class ServerHandshakeImpl extends HandshakeProtocol {
-
- // private key used in key exchange
- private PrivateKey privKey;
-
- /**
- * Creates Server Handshake Implementation
- *
- * @param owner
- */
- public ServerHandshakeImpl(Object owner) {
- super(owner);
- status = NEED_UNWRAP;
- }
-
- /**
- * Start session negotiation
- */
- @Override
- public void start() {
- if (session == null) { // initial handshake
- status = NEED_UNWRAP;
- return; // wait client hello
- }
- if (clientHello != null && this.status != FINISHED) {
- // current negotiation has not completed
- return; // ignore
- }
-
- // renegotiation
- sendHelloRequest();
- status = NEED_UNWRAP;
- }
-
- /**
- * Proceses inbound handshake messages
- * @param bytes
- */
- @Override
- public void unwrap(byte[] bytes) {
-
- io_stream.append(bytes);
- while (io_stream.available() > 0) {
- int handshakeType;
- int length;
- io_stream.mark();
- try {
- handshakeType = io_stream.read();
- length = io_stream.readUint24();
- if (io_stream.available() < length) {
- io_stream.reset();
- return;
- }
-
- switch (handshakeType) {
- case 1: // CLIENT_HELLO
- if (clientHello != null && this.status != FINISHED) {
- // Client hello has been received during handshake
- unexpectedMessage();
- return;
- }
- // if protocol planed to send Hello Request message
- // - cancel this demand.
- needSendHelloRequest = false;
- clientHello = new ClientHello(io_stream, length);
- if (nonBlocking) {
- delegatedTasks.add(new DelegatedTask(new PrivilegedExceptionAction<Void>() {
- public Void run() throws Exception {
- processClientHello();
- return null;
- }
- }, this, AccessController.getContext()));
- return;
- }
- processClientHello();
- break;
-
- case 11: // CLIENT CERTIFICATE
- if (isResuming || certificateRequest == null
- || serverHelloDone == null || clientCert != null) {
- unexpectedMessage();
- return;
- }
- clientCert = new CertificateMessage(io_stream, length);
- if (clientCert.certs.length == 0) {
- if (parameters.getNeedClientAuth()) {
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE,
- "HANDSHAKE FAILURE: no client certificate received");
- }
- } else {
- String authType = clientCert.certs[0].getPublicKey()
- .getAlgorithm();
- try {
- parameters.getTrustManager().checkClientTrusted(
- clientCert.certs, authType);
- } catch (CertificateException e) {
- fatalAlert(AlertProtocol.BAD_CERTIFICATE,
- "Untrusted Client Certificate ", e);
- }
- session.peerCertificates = clientCert.certs;
- }
- break;
-
- case 15: // CERTIFICATE_VERIFY
- if (isResuming
- || clientKeyExchange == null
- || clientCert == null
- || clientKeyExchange.isEmpty() //client certificate
- // contains fixed DH
- // parameters
- || certificateVerify != null
- || changeCipherSpecReceived) {
- unexpectedMessage();
- return;
- }
- certificateVerify = new CertificateVerify(io_stream, length);
-
- DigitalSignature ds = new DigitalSignature(session.cipherSuite.keyExchange);
- ds.init(serverCert.certs[0]);
- byte[] md5_hash = null;
- byte[] sha_hash = null;
-
- if (session.cipherSuite.keyExchange == CipherSuite.KeyExchange_RSA_EXPORT
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_RSA
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DHE_RSA
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DHE_RSA_EXPORT) {
- md5_hash = io_stream.getDigestMD5withoutLast();
- sha_hash = io_stream.getDigestSHAwithoutLast();
- } else if (session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DHE_DSS
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DHE_DSS_EXPORT) {
- sha_hash = io_stream.getDigestSHAwithoutLast();
- } else if (session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DH_anon
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DH_anon_EXPORT) {
- }
- ds.setMD5(md5_hash);
- ds.setSHA(sha_hash);
- if (!ds.verifySignature(certificateVerify.signedHash)) {
- fatalAlert(AlertProtocol.DECRYPT_ERROR,
- "DECRYPT ERROR: CERTIFICATE_VERIFY incorrect signature");
- }
- break;
- case 16: // CLIENT_KEY_EXCHANGE
- if (isResuming
- || serverHelloDone == null
- || clientKeyExchange != null
- || (clientCert == null && parameters
- .getNeedClientAuth())) {
- unexpectedMessage();
- return;
- }
- if (session.cipherSuite.keyExchange == CipherSuite.KeyExchange_RSA
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_RSA_EXPORT) {
- clientKeyExchange = new ClientKeyExchange(io_stream,
- length, serverHello.server_version[1] == 1,
- true);
- Cipher c = null;
- try {
- c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
- c.init(Cipher.DECRYPT_MODE, privKey);
- preMasterSecret = c
- .doFinal(clientKeyExchange.exchange_keys);
- // check preMasterSecret:
- if (preMasterSecret.length != 48
- || preMasterSecret[0] != clientHello.client_version[0]
- || preMasterSecret[1] != clientHello.client_version[1]) {
- // incorrect preMasterSecret
- // prevent an attack (see TLS 1.0 spec., 7.4.7.1.)
- preMasterSecret = new byte[48];
- parameters.getSecureRandom().nextBytes(
- preMasterSecret);
- }
- } catch (Exception e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR,
- "INTERNAL ERROR", e);
- }
- } else { // diffie hellman key exchange
- clientKeyExchange = new ClientKeyExchange(io_stream,
- length, serverHello.server_version[1] == 1,
- false);
- if (clientKeyExchange.isEmpty()) {
- // TODO check that client cert. DH params
- // matched server cert. DH params
-
- // client cert. contains fixed DH parameters
- preMasterSecret = ((DHPublicKey) clientCert.certs[0]
- .getPublicKey()).getY().toByteArray();
- } else {
- PublicKey clientPublic;
- KeyAgreement agreement;
- try {
- KeyFactory kf = null;
- try {
- kf = KeyFactory.getInstance("DH");
- } catch (NoSuchAlgorithmException ee) {
- kf = KeyFactory
- .getInstance("DiffieHellman");
- }
- try {
- agreement = KeyAgreement.getInstance("DH");
- } catch (NoSuchAlgorithmException ee) {
- agreement = KeyAgreement
- .getInstance("DiffieHellman");
- }
- clientPublic = kf
- .generatePublic(new DHPublicKeySpec(
- new BigInteger(
- 1,
- clientKeyExchange.exchange_keys),
- serverKeyExchange.par1,
- serverKeyExchange.par2));
- agreement.init(privKey);
- agreement.doPhase(clientPublic, true);
- preMasterSecret = agreement.generateSecret();
- } catch (Exception e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR,
- "INTERNAL ERROR", e);
- return;
- }
- }
- }
-
- computerMasterSecret();
- break;
-
- case 20: // FINISHED
- if (!isResuming && !changeCipherSpecReceived) {
- unexpectedMessage();
- return;
- }
-
- clientFinished = new Finished(io_stream, length);
- verifyFinished(clientFinished.getData());
- // BEGIN android-added
- session.context = parameters.getServerSessionContext();
- // END android-added
- parameters.getServerSessionContext().putSession(session);
- if (!isResuming) {
- sendChangeCipherSpec();
- } else {
- session.lastAccessedTime = System.currentTimeMillis();
- status = FINISHED;
- }
- break;
- default:
- unexpectedMessage();
- return;
- }
- } catch (IOException e) {
- // io stream dosn't contain complete handshake message
- io_stream.reset();
- return;
- }
- }
- }
- /**
- * Processes SSLv2 Hello message
- * @ see TLS 1.0 spec., E.1. Version 2 client hello
- * @param bytes
- */
- @Override
- public void unwrapSSLv2(byte[] bytes) {
- io_stream.append(bytes);
- io_stream.mark();
- try {
- clientHello = new ClientHello(io_stream);
- } catch (IOException e) {
- io_stream.reset();
- return;
- }
- if (nonBlocking) {
- delegatedTasks.add(new DelegatedTask(
- new PrivilegedExceptionAction<Void>() {
- public Void run() throws Exception {
- processClientHello();
- return null;
- }
- }, this, AccessController.getContext()));
- return;
- }
- processClientHello();
- }
-
- /**
- *
- * Processes Client Hello message.
- * Server responds to client hello message with server hello
- * and (if necessary) server certificate, server key exchange,
- * certificate request, and server hello done messages.
- */
- void processClientHello() {
- CipherSuite cipher_suite;
-
- // check that clientHello contains CompressionMethod.null
- checkCompression: {
- for (int i = 0; i < clientHello.compression_methods.length; i++) {
- if (clientHello.compression_methods[i] == 0) {
- break checkCompression;
- }
- }
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE,
- "HANDSHAKE FAILURE. Incorrect client hello message");
- }
-
- if (!ProtocolVersion.isSupported(clientHello.client_version)) {
- fatalAlert(AlertProtocol.PROTOCOL_VERSION,
- "PROTOCOL VERSION. Unsupported client version "
- + clientHello.client_version[0]
- + clientHello.client_version[1]);
- }
-
- isResuming = false;
- FIND: if (clientHello.session_id.length != 0) {
- // client wishes to reuse session
-
- SSLSessionImpl sessionToResume;
- boolean reuseCurrent = false;
-
- // reuse current session
- if (session != null
- && Arrays.equals(session.id, clientHello.session_id)) {
- if (session.isValid()) {
- isResuming = true;
- break FIND;
- }
- reuseCurrent = true;
- }
-
- // find session in cash
- sessionToResume = findSessionToResume(clientHello.session_id);
- if (sessionToResume == null || !sessionToResume.isValid()) {
- if (!parameters.getEnableSessionCreation()) {
- if (reuseCurrent) {
- // we can continue current session
- sendWarningAlert(AlertProtocol.NO_RENEGOTIATION);
- status = NOT_HANDSHAKING;
- clearMessages();
- return;
- }
- // throw AlertException
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "SSL Session may not be created");
- }
- session = null;
- } else {
- session = (SSLSessionImpl)sessionToResume.clone();
- isResuming = true;
- }
- }
-
- if (isResuming) {
- cipher_suite = session.cipherSuite;
- // clientHello.cipher_suites must include at least cipher_suite from the session
- checkCipherSuite: {
- for (int i = 0; i < clientHello.cipher_suites.length; i++) {
- if (cipher_suite.equals(clientHello.cipher_suites[i])) {
- break checkCipherSuite;
- }
- }
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE,
- "HANDSHAKE FAILURE. Incorrect client hello message");
- }
- } else {
- cipher_suite = selectSuite(clientHello.cipher_suites);
- if (cipher_suite == null) {
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "HANDSHAKE FAILURE. NO COMMON SUITE");
- }
- if (!parameters.getEnableSessionCreation()) {
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE,
- "SSL Session may not be created");
- }
- session = new SSLSessionImpl(cipher_suite, parameters.getSecureRandom());
- session.setPeer(engineOwner.getPeerHost(), engineOwner.getPeerPort());
- }
-
- recordProtocol.setVersion(clientHello.client_version);
- session.protocol = ProtocolVersion.getByVersion(clientHello.client_version);
- session.clientRandom = clientHello.random;
-
- // create server hello message
- serverHello = new ServerHello(parameters.getSecureRandom(),
- clientHello.client_version,
- session.getId(), cipher_suite, (byte) 0); //CompressionMethod.null
- session.serverRandom = serverHello.random;
- send(serverHello);
- if (isResuming) {
- sendChangeCipherSpec();
- return;
- }
-
- // create and send server certificate message if needed
- if (!cipher_suite.isAnonymous()) { // need to send server certificate
- X509Certificate[] certs = null;
- String certType = null;
- if (cipher_suite.keyExchange == CipherSuite.KeyExchange_RSA
- || cipher_suite.keyExchange == CipherSuite.KeyExchange_RSA_EXPORT
- || cipher_suite.keyExchange == CipherSuite.KeyExchange_DHE_RSA
- || cipher_suite.keyExchange == CipherSuite.KeyExchange_DHE_RSA_EXPORT) {
- certType = "RSA";
- } else if (cipher_suite.keyExchange == CipherSuite.KeyExchange_DHE_DSS
- || cipher_suite.keyExchange == CipherSuite.KeyExchange_DHE_DSS_EXPORT) {
- certType = "DSA";
- } else if (cipher_suite.keyExchange == CipherSuite.KeyExchange_DH_DSS) {
- certType = "DH_DSA";
- } else if (cipher_suite.keyExchange == CipherSuite.KeyExchange_DH_RSA) {
- certType = "DH_RSA";
- }
- // obtain certificates from key manager
- String alias = null;
- X509KeyManager km = parameters.getKeyManager();
- if (km instanceof X509ExtendedKeyManager) {
- X509ExtendedKeyManager ekm = (X509ExtendedKeyManager)km;
- // BEGIN android-removed
- // if (this.socketOwner != null) {
- // alias = ekm.chooseServerAlias(certType, null,
- // this.socketOwner);
- // } else {
- // END android-removed
- alias = ekm.chooseEngineServerAlias(certType, null,
- this.engineOwner);
- // BEGIN android-removed
- // }
- // END android-removed
- if (alias != null) {
- certs = ekm.getCertificateChain(alias);
- }
- } else {
- // BEGIN android-removed
- // alias = km.chooseServerAlias(certType, null, this.socketOwner);
- // if (alias != null) {
- // END android-removed
- certs = km.getCertificateChain(alias);
- // BEGIN android-removed
- // }
- // END android-removed
- }
-
- if (certs == null) {
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "NO SERVER CERTIFICATE FOUND");
- return;
- }
- session.localCertificates = certs;
- serverCert = new CertificateMessage(certs);
- privKey = parameters.getKeyManager().getPrivateKey(alias);
- send(serverCert);
- }
-
- // create and send server key exchange message if needed
- RSAPublicKey rsakey = null;
- DHPublicKeySpec dhkeySpec = null;
- byte[] hash = null;
- BigInteger p = null;
- BigInteger g = null;
-
- KeyPairGenerator kpg = null;
-
- try {
- if (cipher_suite.keyExchange == CipherSuite.KeyExchange_RSA_EXPORT) {
- PublicKey pk = serverCert.certs[0].getPublicKey();
- if (getRSAKeyLength(pk) > 512) {
- // key is longer than 512 bits
- kpg = KeyPairGenerator.getInstance("RSA");
- kpg.initialize(512);
- }
- } else if (cipher_suite.keyExchange == CipherSuite.KeyExchange_DHE_DSS
- || cipher_suite.keyExchange == CipherSuite.KeyExchange_DHE_DSS_EXPORT
- || cipher_suite.keyExchange == CipherSuite.KeyExchange_DHE_RSA
- || cipher_suite.keyExchange == CipherSuite.KeyExchange_DHE_RSA_EXPORT
- || cipher_suite.keyExchange == CipherSuite.KeyExchange_DH_anon
- || cipher_suite.keyExchange == CipherSuite.KeyExchange_DH_anon_EXPORT) {
- try {
- kpg = KeyPairGenerator.getInstance("DH");
- } catch (NoSuchAlgorithmException ee) {
- kpg = KeyPairGenerator.getInstance("DiffieHellman");
- }
- p = new BigInteger(1, DHParameters.getPrime());
- g = new BigInteger("2");
- DHParameterSpec spec = new DHParameterSpec(p, g);
- kpg.initialize(spec);
- }
- } catch (Exception e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);
- }
-
- if (kpg != null) {
- // need to send server key exchange message
- DigitalSignature ds = new DigitalSignature(cipher_suite.keyExchange);
- KeyPair kp = null;
- try {
- kp = kpg.genKeyPair();
- if (cipher_suite.keyExchange == CipherSuite.KeyExchange_RSA_EXPORT) {
- rsakey = (RSAPublicKey) kp.getPublic();
- } else {
- DHPublicKey dhkey = (DHPublicKey) kp.getPublic();
- KeyFactory kf = null;
- try {
- kf = KeyFactory.getInstance("DH");
- } catch (NoSuchAlgorithmException e) {
- kf = KeyFactory.getInstance("DiffieHellman");
- }
- dhkeySpec = kf.getKeySpec(dhkey,
- DHPublicKeySpec.class);
- }
- if (!cipher_suite.isAnonymous()) { // calculate signed_params
-
- // init by private key which correspond to
- // server certificate
- ds.init(privKey);
-
- // use emphemeral key for key exchange
- privKey = kp.getPrivate();
- ds.update(clientHello.getRandom());
- ds.update(serverHello.getRandom());
-
- byte[] tmp;
- byte[] tmpLength = new byte[2];
-//FIXME 1_byte==0x00
- if (cipher_suite.keyExchange == CipherSuite.KeyExchange_RSA_EXPORT) {
- tmp = ServerKeyExchange.toUnsignedByteArray(rsakey.getModulus());
- tmpLength[0] = (byte) ((tmp.length & 0xFF00) >>> 8);
- tmpLength[1] = (byte) (tmp.length & 0xFF);
- ds.update(tmpLength);
- ds.update(tmp);
- tmp = ServerKeyExchange.toUnsignedByteArray(rsakey.getPublicExponent());
- tmpLength[0] = (byte) ((tmp.length & 0xFF00) >>> 8);
- tmpLength[1] = (byte) (tmp.length & 0xFF);
- ds.update(tmpLength);
- ds.update(tmp);
- } else {
- tmp = ServerKeyExchange.toUnsignedByteArray(dhkeySpec.getP());
- tmpLength[0] = (byte) ((tmp.length & 0xFF00) >>> 8);
- tmpLength[1] = (byte) (tmp.length & 0xFF);
- ds.update(tmpLength);
- ds.update(tmp);
- tmp = ServerKeyExchange.toUnsignedByteArray(dhkeySpec.getG());
- tmpLength[0] = (byte) ((tmp.length & 0xFF00) >>> 8);
- tmpLength[1] = (byte) (tmp.length & 0xFF);
- ds.update(tmpLength);
- ds.update(tmp);
- tmp = ServerKeyExchange.toUnsignedByteArray(dhkeySpec.getY());
- tmpLength[0] = (byte) ((tmp.length & 0xFF00) >>> 8);
- tmpLength[1] = (byte) (tmp.length & 0xFF);
- ds.update(tmpLength);
- ds.update(tmp);
- }
- hash = ds.sign();
- } else {
- privKey = kp.getPrivate(); // use emphemeral key for key exchange
- }
- } catch (Exception e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);
- }
-
- if (cipher_suite.keyExchange == CipherSuite.KeyExchange_RSA_EXPORT) {
- serverKeyExchange = new ServerKeyExchange(rsakey.getModulus(),
- rsakey.getPublicExponent(), null, hash);
- } else {
- serverKeyExchange = new ServerKeyExchange(p,
- g, dhkeySpec.getY(), hash);
- }
- send(serverKeyExchange);
- }
-
- // CERTIFICATE_REQUEST
- certRequest: if (parameters.getWantClientAuth()
- || parameters.getNeedClientAuth()) {
- X509Certificate[] accepted;
- try {
- X509TrustManager tm = parameters.getTrustManager();
- accepted = tm.getAcceptedIssuers();
- } catch (ClassCastException e) {
- // don't send certificateRequest
- break certRequest;
- }
- byte[] requestedClientCertTypes = {1, 2}; // rsa sign, dsa sign
- certificateRequest = new CertificateRequest(
- requestedClientCertTypes, accepted);
- send(certificateRequest);
- }
-
- // SERVER_HELLO_DONE
- serverHelloDone = new ServerHelloDone();
- send(serverHelloDone);
- status = NEED_UNWRAP;
- }
-
- /**
- * Creates and sends finished message
- */
- @Override
- protected void makeFinished() {
- byte[] verify_data;
- boolean isTLS = (serverHello.server_version[1] == 1); // TLS 1.0 protocol
- if (isTLS) {
- verify_data = new byte[12];
- computerVerifyDataTLS("server finished", verify_data);
- } else { // SSL 3.0 protocol (http://wp.netscape.com/eng/ssl3)
- verify_data = new byte[36];
- computerVerifyDataSSLv3(SSLv3Constants.server, verify_data);
- }
- serverFinished = new Finished(verify_data);
- send(serverFinished);
- if (isResuming) {
- if (isTLS) {
- computerReferenceVerifyDataTLS("client finished");
- } else {
- computerReferenceVerifyDataSSLv3(SSLv3Constants.client);
- }
- status = NEED_UNWRAP;
- } else {
- session.lastAccessedTime = System.currentTimeMillis();
- status = FINISHED;
- }
- }
-
- // find sesssion in the session hash
- private SSLSessionImpl findSessionToResume(byte[] session_id) {
- return (SSLSessionImpl)parameters.getServerSessionContext().getSession(session_id);
- }
-
- // find appropriate cipher_suite in the client suites
- private CipherSuite selectSuite(CipherSuite[] client_suites) {
- for (int i = 0; i < client_suites.length; i++) {
- if (!client_suites[i].supported) {
- continue;
- }
- // BEGIN android-changed
- for (int j = 0; j < parameters.getEnabledCipherSuitesMember().length; j++) {
- if (client_suites[i].equals(parameters.getEnabledCipherSuitesMember()[j])) {
- return client_suites[i];
- }
- }
- // END android-changed
- }
- return null;
- }
-
- /**
- * Processes inbound ChangeCipherSpec message
- */
- @Override
- public void receiveChangeCipherSpec() {
- if (isResuming) {
- if (serverFinished == null) {
- unexpectedMessage();
- } else {
- changeCipherSpecReceived = true;
- }
- } else {
- if ((parameters.getNeedClientAuth() && clientCert == null)
- || clientKeyExchange == null
- || (clientCert != null && !clientKeyExchange.isEmpty() && certificateVerify == null)) {
- unexpectedMessage();
- } else {
- changeCipherSpecReceived = true;
- }
- if (serverHello.server_version[1] == 1) {
- computerReferenceVerifyDataTLS("client finished");
- } else {
- computerReferenceVerifyDataSSLv3(SSLv3Constants.client);
- }
- }
- }
-
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHello.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHello.java
deleted file mode 100644
index 1cd9624..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHello.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.Message;
-
-import java.io.IOException;
-import java.security.SecureRandom;
-
-/**
- *
- * Represents server hello message.
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7.4.1.3.
- * Server hello.</a>
- */
-public class ServerHello extends Message {
-
- /**
- * Server version
- */
- byte[] server_version = new byte[2];
-
- /**
- * Random bytes
- */
- byte[] random = new byte[32];
-
- /**
- * Session id
- */
- byte[] session_id;
-
- /**
- * Selected cipher suite
- */
- CipherSuite cipher_suite;
-
- /**
- * Selected compression method
- */
- byte compression_method;
-
- /**
- * Creates outbound message
- * @param sr
- * @param server_version
- * @param session_id
- * @param cipher_suite
- * @param compression_method
- */
- public ServerHello(SecureRandom sr, byte[] server_version,
- byte[] session_id, CipherSuite cipher_suite, byte compression_method) {
- long gmt_unix_time = new java.util.Date().getTime() / 1000;
- sr.nextBytes(random);
- random[0] = (byte) ((gmt_unix_time & 0xFF000000) >>> 24);
- random[1] = (byte) ((gmt_unix_time & 0xFF0000) >>> 16);
- random[2] = (byte) ((gmt_unix_time & 0xFF00) >>> 8);
- random[3] = (byte) (gmt_unix_time & 0xFF);
- this.session_id = session_id;
- this.cipher_suite = cipher_suite;
- this.compression_method = compression_method;
- this.server_version = server_version;
- length = 38 + session_id.length;
- }
-
- /**
- * Creates inbound message
- * @param in
- * @param length
- * @throws IOException
- */
- public ServerHello(HandshakeIODataStream in, int length) throws IOException {
-
- server_version[0] = (byte) in.read();
- server_version[1] = (byte) in.read();
- in.read(random, 0, 32);
- int size = in.readUint8();
- session_id = new byte[size];
- in.read(session_id, 0, size);
- byte b0 = (byte) in.read();
- byte b1 = (byte) in.read();
- cipher_suite = CipherSuite.getByCode(b0, b1);
- compression_method = (byte) in.read();
- this.length = 38 + session_id.length;
- if (this.length != length) {
- fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR: incorrect ServerHello");
- }
-
- }
-
- /**
- * Sends message
- * @param out
- */
- @Override
- public void send(HandshakeIODataStream out) {
- out.write(server_version);
- out.write(random);
- out.writeUint8(session_id.length);
- out.write(session_id);
- out.write(cipher_suite.toBytes());
- out.write(compression_method);
- length = 38 + session_id.length;
- }
-
- /**
- * Returns server random
- * @return
- */
- public byte[] getRandom() {
- return random;
- }
-
- /**
- * Returns message type
- * @return
- */
- @Override
- public int getType() {
- return Handshake.SERVER_HELLO;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHelloDone.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHelloDone.java
deleted file mode 100644
index 73b6a81..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHelloDone.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.Message;
-
-import java.io.IOException;
-
-/**
- *
- * Represents server hello done message
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7.4.5.
- * Server hello done</a>
- *
- */
-public class ServerHelloDone extends Message {
-
- /**
- * Creates outbound message
- *
- */
- public ServerHelloDone() {
- }
-
- /**
- * Creates inbound message
- * @param in
- * @param length
- * @throws IOException
- */
- public ServerHelloDone(HandshakeIODataStream in, int length)
- throws IOException {
- if (length != 0) {
- fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR: incorrect ServerHelloDone");
- }
- }
-
- /**
- * Sends message
- * @param out
- */
- @Override
- public void send(HandshakeIODataStream out) {
- }
-
- /**
- * Returns message length
- * @return
- */
- @Override
- public int length() {
- return 0;
- }
-
- /**
- * Returns message type
- * @return
- */
- @Override
- public int getType() {
- return Handshake.SERVER_HELLO_DONE;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerKeyExchange.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerKeyExchange.java
deleted file mode 100644
index af056a3..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerKeyExchange.java
+++ /dev/null
@@ -1,193 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.Message;
-
-import java.io.IOException;
-import java.math.BigInteger;
-import java.security.KeyFactory;
-import java.security.interfaces.RSAPublicKey;
-import java.security.spec.RSAPublicKeySpec;
-
-/**
- *
- * Represents server key exchange message.
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7.4.3.
- * Server key exchange message.</a>
- *
- */
-public class ServerKeyExchange extends Message {
-
- // ServerRSAParams ServerDHParams
- final BigInteger par1; // rsa_modulus dh_p
- final byte[] bytes1;
-
- final BigInteger par2; // rsa_exponent dh_g
- final byte[] bytes2;
-
- final BigInteger par3; // dh_Ys
- final byte[] bytes3;
-
- /**
- * Signature
- */
- final byte[] hash;
-
- private RSAPublicKey key;
-
- /**
- * Creates outbound message
- * @param par1 rsa_modulus or dh_p
- * @param par2 rsa_exponent or dh_g
- * @param par3 dh_Ys for ServerDHParams; should be null for ServerRSAParams
- * @param hash should be null for anonymous SignatureAlgorithm
- */
- public ServerKeyExchange(BigInteger par1, BigInteger par2, BigInteger par3,
- byte[] hash) {
- this.par1 = par1;
- this.par2 = par2;
- this.par3 = par3;
- this.hash = hash;
-
- bytes1 = toUnsignedByteArray(this.par1);
-
- bytes2 = toUnsignedByteArray(this.par2);
-
- length = 4 + bytes1.length + bytes2.length;
- if (hash != null) {
- length += 2 + hash.length;
- }
- if (par3 == null) {
- bytes3 = null;
- return;
- }
- bytes3 = toUnsignedByteArray(this.par3);
- length += 2 + bytes3.length;
- }
-
- /**
- * Remove first byte if 0. Needed because BigInteger.toByteArray() sometimes
- * returns a zero prefix.
- */
- public static byte[] toUnsignedByteArray(BigInteger bi) {
- if (bi == null) {
- return null;
- }
- byte[] bb = bi.toByteArray();
- // bb is not null, and has at least 1 byte - ZERO is represented as [0]
- if (bb[0] == 0) {
- byte[] noZero = new byte[bb.length - 1];
- System.arraycopy(bb, 1, noZero, 0, noZero.length);
- return noZero;
- } else {
- return bb;
- }
- }
-
- /**
- * Creates inbound message
- * @param in
- * @param length
- * @param keyExchange
- * @throws IOException
- */
- public ServerKeyExchange(HandshakeIODataStream in, int length,
- int keyExchange) throws IOException {
-
- int size = in.readUint16();
- bytes1 = in.read(size);
- par1 = new BigInteger(1, bytes1);
- this.length = 2 + bytes1.length;
- size = in.readUint16();
- bytes2 = in.read(size);
- par2 = new BigInteger(1, bytes2);
- this.length += 2 + bytes2.length;
- if (keyExchange != CipherSuite.KeyExchange_RSA_EXPORT) {
- size = in.readUint16();
- bytes3 = in.read(size);
- par3 = new BigInteger(1, bytes3);
- this.length += 2 + bytes3.length;
- } else {
- par3 = null;
- bytes3 = null;
- }
- if (keyExchange != CipherSuite.KeyExchange_DH_anon_EXPORT
- && keyExchange != CipherSuite.KeyExchange_DH_anon) {
- size = in.readUint16();
- hash = in.read(size);
- this.length += 2 + hash.length;
- } else {
- hash = null;
- }
- if (this.length != length) {
- fatalAlert(AlertProtocol.DECODE_ERROR,
- "DECODE ERROR: incorrect ServerKeyExchange");
- }
- }
-
- /**
- * Sends message
- * @param out
- */
- @Override
- public void send(HandshakeIODataStream out) {
- out.writeUint16(bytes1.length);
- out.write(bytes1);
- out.writeUint16(bytes2.length);
- out.write(bytes2);
- if (bytes3 != null) {
- out.writeUint16(bytes3.length);
- out.write(bytes3);
- }
- if (hash != null) {
- out.writeUint16(hash.length);
- out.write(hash);
- }
- }
-
- /**
- * Returns RSAPublicKey generated using ServerRSAParams
- * (rsa_modulus and rsa_exponent).
- *
- * @return
- */
- public RSAPublicKey getRSAPublicKey() {
- if (key != null) {
- return key;
- }
- try {
- KeyFactory kf = KeyFactory.getInstance("RSA");
- key = (RSAPublicKey) kf.generatePublic(new RSAPublicKeySpec(par1,
- par2));
- } catch (Exception e) {
- return null;
- }
- return key;
- }
-
- /**
- * Returns message type
- * @return
- */
- @Override
- public int getType() {
- return Handshake.SERVER_KEY_EXCHANGE;
- }
-
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerSessionContext.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerSessionContext.java
deleted file mode 100644
index 160188d..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerSessionContext.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Iterator;
-import java.util.ArrayList;
-import java.util.Arrays;
-
-import javax.net.ssl.SSLSession;
-
-/**
- * Caches server sessions. Indexes by session ID. Users typically look up
- * sessions using the ID provided by an SSL client.
- */
-public class ServerSessionContext extends AbstractSessionContext {
-
- /*
- * TODO: Expire timed-out sessions more pro-actively.
- */
-
- private final Map<ByteArray, SSLSession> sessions
- = new LinkedHashMap<ByteArray, SSLSession>() {
- @Override
- protected boolean removeEldestEntry(
- Map.Entry<ByteArray, SSLSession> eldest) {
- return maximumSize > 0 && size() > maximumSize;
- }
- };
-
- private final SSLServerSessionCache persistentCache;
-
- public ServerSessionContext(int sslCtxNativePointer,
- SSLServerSessionCache persistentCache) {
- super(sslCtxNativePointer, 100, 0);
- this.persistentCache = persistentCache;
-
- // TODO make sure SSL_CTX does not automaticaly clear sessions we want it to cache
- // SSL_CTX_set_session_cache_mode(sslCtxNativePointer, SSL_SESS_CACHE_NO_AUTO_CLEAR);
-
- // TODO remove SSL_CTX session cache limit so we can manage it
- // SSL_CTX_sess_set_cache_size(sslCtxNativePointer, 0);
-
- // TODO override trimToSize to use SSL_CTX_sessions to remove from native cache
- }
-
- Iterator<SSLSession> sessionIterator() {
- synchronized (sessions) {
- SSLSession[] array = sessions.values().toArray(
- new SSLSession[sessions.size()]);
- return Arrays.asList(array).iterator();
- }
- }
-
- void trimToSize() {
- synchronized (sessions) {
- int size = sessions.size();
- if (size > maximumSize) {
- int removals = size - maximumSize;
- Iterator<SSLSession> i = sessions.values().iterator();
- do {
- i.next();
- i.remove();
- } while (--removals > 0);
- }
- }
- }
-
- public void setSessionTimeout(int seconds)
- throws IllegalArgumentException {
- if (seconds < 0) {
- throw new IllegalArgumentException("seconds < 0");
- }
- timeout = seconds;
- }
-
- public SSLSession getSession(byte[] sessionId) {
- ByteArray key = new ByteArray(sessionId);
- synchronized (sessions) {
- SSLSession session = sessions.get(key);
- if (session != null) {
- return session;
- }
- }
-
- // Check persistent cache.
- if (persistentCache != null) {
- byte[] data = persistentCache.getSessionData(sessionId);
- if (data != null) {
- SSLSession session = toSession(data, null, -1);
- if (session != null) {
- synchronized (sessions) {
- sessions.put(key, session);
- }
- return session;
- }
- }
- }
-
- return null;
- }
-
- @Override
- void putSession(SSLSession session) {
- byte[] id = session.getId();
- if (id.length == 0) {
- return;
- }
- ByteArray key = new ByteArray(id);
- synchronized (sessions) {
- sessions.put(key, session);
- }
-
- // TODO: In background thread.
- if (persistentCache != null) {
- byte[] data = toBytes(session);
- if (data != null) {
- persistentCache.putSessionData(session, data);
- }
- }
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/TrustManagerFactoryImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/TrustManagerFactoryImpl.java
deleted file mode 100644
index c473864..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/TrustManagerFactoryImpl.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.security.AccessController;
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.cert.CertificateException;
-
-import javax.net.ssl.ManagerFactoryParameters;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactorySpi;
-
-/**
- *
- * TrustManagerFactory service provider interface implementation.
- *
- * @see javax.net.ssl.TrustManagerFactorySpi
- */
-public class TrustManagerFactoryImpl extends TrustManagerFactorySpi {
-
- private KeyStore keyStore;
-
- /**
- * @see javax.net.ssl.TrustManagerFactorySpi#engineInit(KeyStore)
- */
- @Override
- public void engineInit(KeyStore ks) throws KeyStoreException {
- if (ks != null) {
- keyStore = ks;
- } else {
- // BEGIN android-added
- if (System.getProperty("javax.net.ssl.trustStore") == null) {
- String file = System.getProperty("java.home")
- + java.io.File.separator + "etc" + java.io.File.separator
- + "security" + java.io.File.separator
- + "cacerts.bks";
-
- System.setProperty("javax.net.ssl.trustStore", file);
- }
- // END android-added
- keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
- String keyStoreName = AccessController
- .doPrivileged(new java.security.PrivilegedAction<String>() {
- public String run() {
- return System
- .getProperty("javax.net.ssl.trustStore");
- }
- });
- String keyStorePwd = null;
- if (keyStoreName == null || keyStoreName.equalsIgnoreCase("NONE")
- || keyStoreName.length() == 0) {
- try {
- keyStore.load(null, null);
- } catch (IOException e) {
- throw new KeyStoreException(e);
- } catch (CertificateException e) {
- throw new KeyStoreException(e);
- } catch (NoSuchAlgorithmException e) {
- throw new KeyStoreException(e);
- }
- } else {
- keyStorePwd = AccessController
- .doPrivileged(new java.security.PrivilegedAction<String>() {
- public String run() {
- return System
- .getProperty("javax.net.ssl.trustStorePassword");
- }
- });
- char[] pwd;
- if (keyStorePwd == null) {
- pwd = new char[0];
- } else {
- pwd = keyStorePwd.toCharArray();
- }
- try {
- keyStore.load(new FileInputStream(new File(keyStoreName)), pwd);
- } catch (FileNotFoundException e) {
- throw new KeyStoreException(e);
- } catch (IOException e) {
- throw new KeyStoreException(e);
- } catch (CertificateException e) {
- throw new KeyStoreException(e);
- } catch (NoSuchAlgorithmException e) {
- throw new KeyStoreException(e);
- }
- }
- }
-
- }
-
- /**
- * @see javax.net.ssl#engineInit(ManagerFactoryParameters)
- */
- @Override
- public void engineInit(ManagerFactoryParameters spec)
- throws InvalidAlgorithmParameterException {
- throw new InvalidAlgorithmParameterException(
- "ManagerFactoryParameters not supported");
- }
-
- /**
- * @see javax.net.ssl#engineGetTrustManagers()
- */
- @Override
- public TrustManager[] engineGetTrustManagers() {
- if (keyStore == null) {
- throw new IllegalStateException(
- "TrustManagerFactory is not initialized");
- }
- return new TrustManager[] { new TrustManagerImpl(keyStore) };
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/TrustManagerImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/TrustManagerImpl.java
deleted file mode 100644
index 543dfb2..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/TrustManagerImpl.java
+++ /dev/null
@@ -1,234 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.bouncycastle.jce.provider.IndexedPKIXParameters;
-
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.cert.CertPathValidator;
-import java.security.cert.CertPathValidatorException;
-import java.security.cert.CertificateException;
-import java.security.cert.CertificateFactory;
-import java.security.cert.PKIXParameters;
-import java.security.cert.TrustAnchor;
-import java.security.cert.X509Certificate;
-import java.util.Arrays;
-import java.util.Enumeration;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import javax.net.ssl.X509TrustManager;
-
-// BEGIN android-added
-import java.lang.reflect.Method;
-import java.security.cert.CertPath;
-import java.security.cert.CertificateEncodingException;
-// END android-added
-
-/**
- *
- * TrustManager implementation. The implementation is based on CertPathValidator
- * PKIX and CertificateFactory X509 implementations. This implementations should
- * be provided by some certification provider.
- *
- * @see javax.net.ssl.X509TrustManager
- */
-public class TrustManagerImpl implements X509TrustManager {
-
- private CertPathValidator validator;
-
- private PKIXParameters params;
-
- private Exception err = null;
-
- private CertificateFactory factory;
-
- /**
- * Creates trust manager implementation
- *
- * @param ks
- */
- public TrustManagerImpl(KeyStore ks) {
- try {
- validator = CertPathValidator.getInstance("PKIX");
- factory = CertificateFactory.getInstance("X509");
- byte[] nameConstrains = null;
- Set<TrustAnchor> trusted = new HashSet<TrustAnchor>();
- for (Enumeration<String> en = ks.aliases(); en.hasMoreElements();) {
- final String alias = en.nextElement();
- final X509Certificate cert = (X509Certificate) ks.getCertificate(alias);
- if (cert != null) {
- trusted.add(new TrustAnchor(cert, nameConstrains));
- }
- }
- params = new PKIXParameters(trusted);
- params.setRevocationEnabled(false);
- } catch (Exception e) {
- err = e;
- }
- }
-
-// BEGIN android-added
- /**
- * Indexes trust anchors so they can be found in O(1) instead of O(N) time.
- */
- public void indexTrustAnchors() throws CertificateEncodingException,
- InvalidAlgorithmParameterException, KeyStoreException {
- params = new IndexedPKIXParameters(params.getTrustAnchors());
- params.setRevocationEnabled(false);
- }
-// END android-added
-
- /**
- * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],
- * String)
- */
- public void checkClientTrusted(X509Certificate[] chain, String authType)
- throws CertificateException {
- if (chain == null || chain.length == 0 || authType == null
- || authType.length() == 0) {
- throw new IllegalArgumentException("null or zero-length parameter");
- }
- if (err != null) {
- throw new CertificateException(err);
- }
- // BEGIN android-added
- // Cater for degenerate special case where we can't
- // establish an actual certificate chain the usual way,
- // but have the peer certificate in our trust store.
- if (isDirectlyTrustedCert(chain)) {
- return;
- }
- // END android-added
- try {
- // BEGIN android-changed
- CertPath certPath = factory.generateCertPath(Arrays.asList(chain));
- if (!Arrays.equals(chain[0].getEncoded(),
- ((X509Certificate)certPath.getCertificates().get(0))
- .getEncoded())) {
- // sanity check failed (shouldn't ever happen, but we are using pretty remote code)
- throw new CertificateException("Certificate chain error");
- }
- validator.validate(certPath, params);
- // END android-changed
- } catch (InvalidAlgorithmParameterException e) {
- throw new CertificateException(e);
- } catch (CertPathValidatorException e) {
- throw new CertificateException(e);
- }
- }
-
- /**
- * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],
- * String)
- */
- public void checkServerTrusted(X509Certificate[] chain, String authType)
- throws CertificateException {
- if (chain == null || chain.length == 0 || authType == null
- || authType.length() == 0) {
- throw new IllegalArgumentException(
- "null or zero-length parameter");
- }
- if (err != null) {
- throw new CertificateException(err);
- }
-// BEGIN android-changed
- CertificateException ce = null;
- try {
- CertPath certPath = factory.generateCertPath(
- Arrays.asList(chain));
- if (!Arrays.equals(chain[0].getEncoded(),
- certPath.getCertificates().get(0).getEncoded())) {
- // Sanity check failed (shouldn't ever happen, but we are
- // using pretty remote code)
- throw new CertificateException("Certificate chain error");
- }
- validator.validate(certPath, params);
- } catch (InvalidAlgorithmParameterException e) {
- ce = new CertificateException(e);
- } catch (CertPathValidatorException e) {
- ce = new CertificateException(e);
- }
- if (ce != null) {
- // Caters to degenerate special case where we can't
- // establish an actual certificate chain the usual way
- // but have the peer certificate in our trust store.
- if (!isDirectlyTrustedCert(chain)) {
- throw ce;
- }
- }
- }
-
- /**
- * Checks whether the given chain is just a certificate
- * that we have in our trust store.
- *
- * @param chain The certificate chain.
- *
- * @return True if the certificate is in our trust store, false otherwise.
- */
- private boolean isDirectlyTrustedCert(X509Certificate[] chain) {
- byte[] questionable;
-
- if (chain.length == 1) {
- if (params instanceof IndexedPKIXParameters) {
- IndexedPKIXParameters index = (IndexedPKIXParameters) params;
- return index.isDirectlyTrusted(chain[0]);
- } else {
- try {
- questionable = chain[0].getEncoded();
- Set<TrustAnchor> anchors = params.getTrustAnchors();
-
- for (TrustAnchor trustAnchor : anchors) {
- byte[] trusted = trustAnchor.getTrustedCert()
- .getEncoded();
- if (Arrays.equals(questionable, trusted)) {
- return true;
- }
- }
- } catch (CertificateEncodingException e) {
- // Ignore.
- }
- }
-
- }
-
- return false;
- }
-// END android-changed
-
- /**
- * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
- */
- public X509Certificate[] getAcceptedIssuers() {
- if (params == null) {
- return new X509Certificate[0];
- }
- Set<TrustAnchor> anchors = params.getTrustAnchors();
- X509Certificate[] certs = new X509Certificate[anchors.size()];
- int i = 0;
- for (Iterator<TrustAnchor> it = anchors.iterator(); it.hasNext();) {
- certs[i++] = it.next().getTrustedCert();
- }
- return certs;
- }
-
-}
diff --git a/x-net/src/main/native/org_apache_harmony_xnet_provider_jsse_NativeCrypto.cpp b/x-net/src/main/native/org_apache_harmony_xnet_provider_jsse_NativeCrypto.cpp
deleted file mode 100644
index 86eaadf..0000000
--- a/x-net/src/main/native/org_apache_harmony_xnet_provider_jsse_NativeCrypto.cpp
+++ /dev/null
@@ -1,2655 +0,0 @@
-/*
- * Copyright (C) 2007-2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**
- * Native glue for Java class org.apache.harmony.xnet.provider.jsse.NativeCrypto
- */
-
-#define LOG_TAG "NativeCrypto"
-
-#include <fcntl.h>
-#include <sys/socket.h>
-#include <unistd.h>
-
-#include <jni.h>
-
-#include <JNIHelp.h>
-#include <LocalArray.h>
-
-#include <openssl/dsa.h>
-#include <openssl/err.h>
-#include <openssl/evp.h>
-#include <openssl/rand.h>
-#include <openssl/rsa.h>
-#include <openssl/ssl.h>
-
-#undef WITH_JNI_TRACE
-#ifdef WITH_JNI_TRACE
-#define JNI_TRACE(...) \
- ((void)LOG(LOG_INFO, LOG_TAG "-jni", __VA_ARGS__)); \
- ((void)printf("I/" LOG_TAG "-jni:")); \
- ((void)printf(__VA_ARGS__)); \
- ((void)printf("\n"))
-#else
-#define JNI_TRACE(...) ((void)0)
-#endif
-/**
- * Frees the SSL error state.
- *
- * OpenSSL keeps an "error stack" per thread, and given that this code
- * can be called from arbitrary threads that we don't keep track of,
- * we err on the side of freeing the error state promptly (instead of,
- * say, at thread death).
- */
-static void freeSslErrorState(void) {
- ERR_clear_error();
- ERR_remove_state(0);
-}
-
-/*
- * Checks this thread's OpenSSL error queue and throws a RuntimeException if
- * necessary.
- *
- * @return 1 if an exception was thrown, 0 if not.
- */
-static int throwExceptionIfNecessary(JNIEnv* env) {
- int error = ERR_get_error();
- int result = 0;
-
- if (error != 0) {
- char message[50];
- ERR_error_string_n(error, message, sizeof(message));
- LOGD("OpenSSL error %d: %s", error, message);
- jniThrowRuntimeException(env, message);
- result = 1;
- }
-
- freeSslErrorState();
- return result;
-}
-
-
-/**
- * Throws an SocketTimeoutException with the given string as a message.
- */
-static void throwSocketTimeoutException(JNIEnv* env, const char* message) {
- if (jniThrowException(env, "java/net/SocketTimeoutException", message)) {
- LOGE("Unable to throw");
- }
-}
-
-/**
- * Throws a javax.net.ssl.SSLException with the given string as a message.
- */
-static void throwSSLExceptionStr(JNIEnv* env, const char* message) {
- if (jniThrowException(env, "javax/net/ssl/SSLException", message)) {
- LOGE("Unable to throw");
- }
-}
-
-/**
- * Throws an SSLException with a message constructed from the current
- * SSL errors. This will also log the errors.
- *
- * @param env the JNI environment
- * @param sslReturnCode return code from failing SSL function
- * @param sslErrorCode error code returned from SSL_get_error()
- * @param message null-ok; general error message
- */
-static void throwSSLExceptionWithSslErrors(JNIEnv* env, int sslReturnCode,
- int sslErrorCode, const char* message) {
- const char* messageStr = NULL;
- char* str;
- int ret;
-
- // First consult the SSL error code for the general message.
- switch (sslErrorCode) {
- case SSL_ERROR_NONE:
- messageStr = "Ok";
- break;
- case SSL_ERROR_SSL:
- messageStr = "Failure in SSL library, usually a protocol error";
- break;
- case SSL_ERROR_WANT_READ:
- messageStr = "SSL_ERROR_WANT_READ occured. You should never see this.";
- break;
- case SSL_ERROR_WANT_WRITE:
- messageStr = "SSL_ERROR_WANT_WRITE occured. You should never see this.";
- break;
- case SSL_ERROR_WANT_X509_LOOKUP:
- messageStr = "SSL_ERROR_WANT_X509_LOOKUP occured. You should never see this.";
- break;
- case SSL_ERROR_SYSCALL:
- messageStr = "I/O error during system call";
- break;
- case SSL_ERROR_ZERO_RETURN:
- messageStr = "SSL_ERROR_ZERO_RETURN occured. You should never see this.";
- break;
- case SSL_ERROR_WANT_CONNECT:
- messageStr = "SSL_ERROR_WANT_CONNECT occured. You should never see this.";
- break;
- case SSL_ERROR_WANT_ACCEPT:
- messageStr = "SSL_ERROR_WANT_ACCEPT occured. You should never see this.";
- break;
- default:
- messageStr = "Unknown SSL error";
- }
-
- // Prepend either our explicit message or a default one.
- if (asprintf(&str, "%s: %s",
- (message != NULL) ? message : "SSL error", messageStr) <= 0) {
- // problem with asprintf
- throwSSLExceptionStr(env, messageStr);
- LOGV("%s", messageStr);
- freeSslErrorState();
- return;
- }
-
- char* allocStr = str;
-
- // For SSL protocol errors, SSL might have more information.
- if (sslErrorCode == SSL_ERROR_SSL) {
- // Append each error as an additional line to the message.
- for (;;) {
- char errStr[256];
- const char* file;
- int line;
- const char* data;
- int flags;
- unsigned long err =
- ERR_get_error_line_data(&file, &line, &data, &flags);
- if (err == 0) {
- break;
- }
-
- ERR_error_string_n(err, errStr, sizeof(errStr));
-
- ret = asprintf(&str, "%s\n%s (%s:%d %p:0x%08x)",
- (allocStr == NULL) ? "" : allocStr,
- errStr,
- file,
- line,
- data,
- flags);
-
- if (ret < 0) {
- break;
- }
-
- free(allocStr);
- allocStr = str;
- }
- // For errors during system calls, errno might be our friend.
- } else if (sslErrorCode == SSL_ERROR_SYSCALL) {
- if (asprintf(&str, "%s, %s", allocStr, strerror(errno)) >= 0) {
- free(allocStr);
- allocStr = str;
- }
- // If the error code is invalid, print it.
- } else if (sslErrorCode > SSL_ERROR_WANT_ACCEPT) {
- if (asprintf(&str, ", error code is %d", sslErrorCode) >= 0) {
- free(allocStr);
- allocStr = str;
- }
- }
-
- throwSSLExceptionStr(env, allocStr);
-
- LOGV("%s", allocStr);
- free(allocStr);
- freeSslErrorState();
-}
-
-/**
- * Helper function that grabs the casts an ssl pointer and then checks for nullness.
- * If this function returns NULL and <code>throwIfNull</code> is
- * passed as <code>true</code>, then this function will call
- * <code>throwSSLExceptionStr</code> before returning, so in this case of
- * NULL, a caller of this function should simply return and allow JNI
- * to do its thing.
- *
- * @param env the JNI environment
- * @param ssl_address; the ssl_address pointer as an integer
- * @param throwIfNull whether to throw if the SSL pointer is NULL
- * @returns the pointer, which may be NULL
- */
-static SSL* getSslPointer(JNIEnv* env, int ssl_address, bool throwIfNull) {
- SSL* ssl = reinterpret_cast<SSL*>(static_cast<uintptr_t>(ssl_address));
- if ((ssl == NULL) && throwIfNull) {
- throwSSLExceptionStr(env, "null SSL pointer");
- }
-
- return ssl;
-}
-
-/**
- * Converts a Java byte[] to an OpenSSL BIGNUM, allocating the BIGNUM on the
- * fly.
- */
-static BIGNUM* arrayToBignum(JNIEnv* env, jbyteArray source) {
- // LOGD("Entering arrayToBignum()");
-
- jbyte* sourceBytes = env->GetByteArrayElements(source, NULL);
- int sourceLength = env->GetArrayLength(source);
- BIGNUM* bignum = BN_bin2bn((unsigned char*) sourceBytes, sourceLength, NULL);
- env->ReleaseByteArrayElements(source, sourceBytes, JNI_ABORT);
- return bignum;
-}
-
-/**
- * OpenSSL locking support. Taken from the O'Reilly book by Viega et al., but I
- * suppose there are not many other ways to do this on a Linux system (modulo
- * isomorphism).
- */
-#define MUTEX_TYPE pthread_mutex_t
-#define MUTEX_SETUP(x) pthread_mutex_init(&(x), NULL)
-#define MUTEX_CLEANUP(x) pthread_mutex_destroy(&(x))
-#define MUTEX_LOCK(x) pthread_mutex_lock(&(x))
-#define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x))
-#define THREAD_ID pthread_self()
-#define THROW_EXCEPTION (-2)
-#define THROW_SOCKETTIMEOUTEXCEPTION (-3)
-
-static MUTEX_TYPE *mutex_buf = NULL;
-
-static void locking_function(int mode, int n, const char * file, int line) {
- if (mode & CRYPTO_LOCK) {
- MUTEX_LOCK(mutex_buf[n]);
- } else {
- MUTEX_UNLOCK(mutex_buf[n]);
- }
-}
-
-static unsigned long id_function(void) {
- return ((unsigned long)THREAD_ID);
-}
-
-int THREAD_setup(void) {
- int i;
-
- mutex_buf = (MUTEX_TYPE *)malloc(CRYPTO_num_locks( ) * sizeof(MUTEX_TYPE));
-
- if(!mutex_buf) {
- return 0;
- }
-
- for (i = 0; i < CRYPTO_num_locks( ); i++) {
- MUTEX_SETUP(mutex_buf[i]);
- }
-
- CRYPTO_set_id_callback(id_function);
- CRYPTO_set_locking_callback(locking_function);
-
- return 1;
-}
-
-int THREAD_cleanup(void) {
- int i;
-
- if (!mutex_buf) {
- return 0;
- }
-
- CRYPTO_set_id_callback(NULL);
- CRYPTO_set_locking_callback(NULL);
-
- for (i = 0; i < CRYPTO_num_locks( ); i++) {
- MUTEX_CLEANUP(mutex_buf[i]);
- }
-
- free(mutex_buf);
- mutex_buf = NULL;
-
- return 1;
-}
-
-/**
- * Initialization phase for every OpenSSL job: Loads the Error strings, the
- * crypto algorithms and reset the OpenSSL library
- */
-static void NativeCrypto_clinit(JNIEnv* env, jclass)
-{
- SSL_load_error_strings();
- ERR_load_crypto_strings();
- SSL_library_init();
- OpenSSL_add_all_algorithms();
- THREAD_setup();
-}
-
-/**
- * public static native int EVP_PKEY_new_DSA(byte[] p, byte[] q, byte[] g, byte[] pub_key, byte[] priv_key);
- */
-static EVP_PKEY* NativeCrypto_EVP_PKEY_new_DSA(JNIEnv* env, jclass clazz, jbyteArray p, jbyteArray q, jbyteArray g, jbyteArray pub_key, jbyteArray priv_key) {
- // LOGD("Entering EVP_PKEY_new_DSA()");
-
- DSA* dsa = DSA_new();
-
- dsa->p = arrayToBignum(env, p);
- dsa->q = arrayToBignum(env, q);
- dsa->g = arrayToBignum(env, g);
- dsa->pub_key = arrayToBignum(env, pub_key);
-
- if (priv_key != NULL) {
- dsa->priv_key = arrayToBignum(env, priv_key);
- }
-
- if (dsa->p == NULL || dsa->q == NULL || dsa->g == NULL || dsa->pub_key == NULL) {
- DSA_free(dsa);
- jniThrowRuntimeException(env, "Unable to convert BigInteger to BIGNUM");
- return NULL;
- }
-
- EVP_PKEY* pkey = EVP_PKEY_new();
- EVP_PKEY_assign_DSA(pkey, dsa);
-
- return pkey;
-}
-
-/**
- * private static native int EVP_PKEY_new_RSA(byte[] n, byte[] e, byte[] d, byte[] p, byte[] q);
- */
-static EVP_PKEY* NativeCrypto_EVP_PKEY_new_RSA(JNIEnv* env, jclass clazz, jbyteArray n, jbyteArray e, jbyteArray d, jbyteArray p, jbyteArray q) {
- // LOGD("Entering EVP_PKEY_new_RSA()");
-
- RSA* rsa = RSA_new();
-
- rsa->n = arrayToBignum(env, n);
- rsa->e = arrayToBignum(env, e);
-
- if (d != NULL) {
- rsa->d = arrayToBignum(env, d);
- }
-
- if (p != NULL) {
- rsa->p = arrayToBignum(env, p);
- }
-
- if (q != NULL) {
- rsa->q = arrayToBignum(env, q);
- }
-
- // int check = RSA_check_key(rsa);
- // LOGI("RSA_check_key returns %d", check);
-
- if (rsa->n == NULL || rsa->e == NULL) {
- RSA_free(rsa);
- jniThrowRuntimeException(env, "Unable to convert BigInteger to BIGNUM");
- return NULL;
- }
-
- EVP_PKEY* pkey = EVP_PKEY_new();
- EVP_PKEY_assign_RSA(pkey, rsa);
-
- return pkey;
-}
-
-/**
- * private static native void EVP_PKEY_free(int pkey);
- */
-static void NativeCrypto_EVP_PKEY_free(JNIEnv* env, jclass clazz, EVP_PKEY* pkey) {
- // LOGD("Entering EVP_PKEY_free()");
-
- if (pkey != NULL) {
- EVP_PKEY_free(pkey);
- }
-}
-
-/*
- * public static native int EVP_new()
- */
-static jint NativeCrypto_EVP_new(JNIEnv* env, jclass clazz) {
- // LOGI("NativeCrypto_EVP_DigestNew");
-
- return (jint)EVP_MD_CTX_create();
-}
-
-/*
- * public static native void EVP_free(int)
- */
-static void NativeCrypto_EVP_free(JNIEnv* env, jclass clazz, EVP_MD_CTX* ctx) {
- // LOGI("NativeCrypto_EVP_DigestFree");
-
- if (ctx != NULL) {
- EVP_MD_CTX_destroy(ctx);
- }
-}
-
-/*
- * public static native int EVP_DigestFinal(int, byte[], int)
- */
-static jint NativeCrypto_EVP_DigestFinal(JNIEnv* env, jclass clazz, EVP_MD_CTX* ctx, jbyteArray hash, jint offset) {
- // LOGI("NativeCrypto_EVP_DigestFinal%x, %x, %d, %d", ctx, hash, offset);
-
- if (ctx == NULL || hash == NULL) {
- jniThrowNullPointerException(env, NULL);
- return -1;
- }
-
- int result = -1;
-
- jbyte* hashBytes = env->GetByteArrayElements(hash, NULL);
- EVP_DigestFinal(ctx, (unsigned char*) (hashBytes + offset), (unsigned int*)&result);
- env->ReleaseByteArrayElements(hash, hashBytes, 0);
-
- throwExceptionIfNecessary(env);
-
- return result;
-}
-
-/*
- * public static native void EVP_DigestInit(int, java.lang.String)
- */
-static void NativeCrypto_EVP_DigestInit(JNIEnv* env, jclass clazz, EVP_MD_CTX* ctx, jstring algorithm) {
- // LOGI("NativeCrypto_EVP_DigestInit");
-
- if (ctx == NULL || algorithm == NULL) {
- jniThrowNullPointerException(env, NULL);
- return;
- }
-
- const char* algorithmChars = env->GetStringUTFChars(algorithm, NULL);
-
- const EVP_MD *digest = EVP_get_digestbynid(OBJ_txt2nid(algorithmChars));
- env->ReleaseStringUTFChars(algorithm, algorithmChars);
-
- if (digest == NULL) {
- jniThrowRuntimeException(env, "Hash algorithm not found");
- return;
- }
-
- EVP_DigestInit(ctx, digest);
-
- throwExceptionIfNecessary(env);
-}
-
-/*
- * public static native void EVP_DigestSize(int)
- */
-static jint NativeCrypto_EVP_DigestSize(JNIEnv* env, jclass clazz, EVP_MD_CTX* ctx) {
- // LOGI("NativeCrypto_EVP_DigestSize");
-
- if (ctx == NULL) {
- jniThrowNullPointerException(env, NULL);
- return -1;
- }
-
- int result = EVP_MD_CTX_size(ctx);
-
- throwExceptionIfNecessary(env);
-
- return result;
-}
-
-/*
- * public static native void EVP_DigestBlockSize(int)
- */
-static jint NativeCrypto_EVP_DigestBlockSize(JNIEnv* env, jclass clazz, EVP_MD_CTX* ctx) {
- // LOGI("NativeCrypto_EVP_DigestBlockSize");
-
- if (ctx == NULL) {
- jniThrowNullPointerException(env, NULL);
- return -1;
- }
-
- int result = EVP_MD_CTX_block_size(ctx);
-
- throwExceptionIfNecessary(env);
-
- return result;
-}
-
-/*
- * public static native void EVP_DigestUpdate(int, byte[], int, int)
- */
-static void NativeCrypto_EVP_DigestUpdate(JNIEnv* env, jclass clazz, EVP_MD_CTX* ctx, jbyteArray buffer, jint offset, jint length) {
- // LOGI("NativeCrypto_EVP_DigestUpdate %x, %x, %d, %d", ctx, buffer, offset, length);
-
- if (ctx == NULL || buffer == NULL) {
- jniThrowNullPointerException(env, NULL);
- return;
- }
-
- jbyte* bufferBytes = env->GetByteArrayElements(buffer, NULL);
- EVP_DigestUpdate(ctx, (unsigned char*) (bufferBytes + offset), length);
- env->ReleaseByteArrayElements(buffer, bufferBytes, JNI_ABORT);
-
- throwExceptionIfNecessary(env);
-}
-
-/*
- * public static native void EVP_VerifyInit(int, java.lang.String)
- */
-static void NativeCrypto_EVP_VerifyInit(JNIEnv* env, jclass clazz, EVP_MD_CTX* ctx, jstring algorithm) {
- // LOGI("NativeCrypto_EVP_VerifyInit");
-
- if (ctx == NULL || algorithm == NULL) {
- jniThrowNullPointerException(env, NULL);
- return;
- }
-
- const char* algorithmChars = env->GetStringUTFChars(algorithm, NULL);
-
- const EVP_MD *digest = EVP_get_digestbynid(OBJ_txt2nid(algorithmChars));
- env->ReleaseStringUTFChars(algorithm, algorithmChars);
-
- if (digest == NULL) {
- jniThrowRuntimeException(env, "Hash algorithm not found");
- return;
- }
-
- EVP_VerifyInit(ctx, digest);
-
- throwExceptionIfNecessary(env);
-}
-
-/*
- * public static native void EVP_VerifyUpdate(int, byte[], int, int)
- */
-static void NativeCrypto_EVP_VerifyUpdate(JNIEnv* env, jclass clazz, EVP_MD_CTX* ctx, jbyteArray buffer, jint offset, jint length) {
- // LOGI("NativeCrypto_EVP_VerifyUpdate %x, %x, %d, %d", ctx, buffer, offset, length);
-
- if (ctx == NULL || buffer == NULL) {
- jniThrowNullPointerException(env, NULL);
- return;
- }
-
- jbyte* bufferBytes = env->GetByteArrayElements(buffer, NULL);
- EVP_VerifyUpdate(ctx, (unsigned char*) (bufferBytes + offset), length);
- env->ReleaseByteArrayElements(buffer, bufferBytes, JNI_ABORT);
-
- throwExceptionIfNecessary(env);
-}
-
-/*
- * public static native void EVP_VerifyFinal(int, byte[], int, int, int)
- */
-static int NativeCrypto_EVP_VerifyFinal(JNIEnv* env, jclass clazz, EVP_MD_CTX* ctx, jbyteArray buffer, jint offset, jint length, EVP_PKEY* pkey) {
- // LOGI("NativeCrypto_EVP_VerifyFinal %x, %x, %d, %d %x", ctx, buffer, offset, length, pkey);
-
- if (ctx == NULL || buffer == NULL || pkey == NULL) {
- jniThrowNullPointerException(env, NULL);
- return -1;
- }
-
- jbyte* bufferBytes = env->GetByteArrayElements(buffer, NULL);
- int result = EVP_VerifyFinal(ctx, (unsigned char*) (bufferBytes + offset), length, pkey);
- env->ReleaseByteArrayElements(buffer, bufferBytes, JNI_ABORT);
-
- throwExceptionIfNecessary(env);
-
- return result;
-}
-
-/**
- * Convert ssl version constant to string. Based on SSL_get_version
- */
-static const char* get_ssl_version(int ssl_version) {
- switch (ssl_version) {
- // newest to oldest
- case TLS1_VERSION: {
- return SSL_TXT_TLSV1;
- }
- case SSL3_VERSION: {
- return SSL_TXT_SSLV3;
- }
- case SSL2_VERSION: {
- return SSL_TXT_SSLV2;
- }
- default: {
- return "unknown";
- }
- }
-}
-
-/**
- * Convert content type constant to string.
- */
-static const char* get_content_type(int content_type) {
- switch (content_type) {
- case SSL3_RT_CHANGE_CIPHER_SPEC: {
- return "SSL3_RT_CHANGE_CIPHER_SPEC";
- }
- case SSL3_RT_ALERT: {
- return "SSL3_RT_ALERT";
- }
- case SSL3_RT_HANDSHAKE: {
- return "SSL3_RT_HANDSHAKE";
- }
- case SSL3_RT_APPLICATION_DATA: {
- return "SSL3_RT_APPLICATION_DATA";
- }
- default: {
- LOGD("Unknown TLS/SSL content type %d", content_type);
- return "<unknown>";
- }
- }
-}
-
-/**
- * Simple logging call back to show hand shake messages
- */
-static void ssl_msg_callback_LOG(int write_p, int ssl_version, int content_type,
- const void *buf, size_t len, SSL* ssl, void* arg) {
- JNI_TRACE("ssl=%p SSL msg %s %s %s %p %d %p",
- ssl,
- (write_p) ? "send" : "recv",
- get_ssl_version(ssl_version),
- get_content_type(content_type),
- buf,
- len,
- arg);
-}
-
-/**
- * Based on example logging call back from SSL_CTX_set_info_callback man page
- */
-static void info_callback_LOG(const SSL *s, int where, int ret)
-{
- int w = where & ~SSL_ST_MASK;
- const char* str;
- if (w & SSL_ST_CONNECT) {
- str = "SSL_connect";
- } else if (w & SSL_ST_ACCEPT) {
- str = "SSL_accept";
- } else {
- str = "undefined";
- }
-
- if (where & SSL_CB_LOOP) {
- JNI_TRACE("ssl=%p %s:%s %s", s, str, SSL_state_string(s), SSL_state_string_long(s));
- } else if (where & SSL_CB_ALERT) {
- str = (where & SSL_CB_READ) ? "read" : "write";
- JNI_TRACE("ssl=%p SSL3 alert %s:%s:%s %s %s",
- s,
- str,
- SSL_alert_type_string(ret),
- SSL_alert_desc_string(ret),
- SSL_alert_type_string_long(ret),
- SSL_alert_desc_string_long(ret));
- } else if (where & SSL_CB_EXIT) {
- if (ret == 0) {
- JNI_TRACE("ssl=%p %s:failed exit in %s %s",
- s, str, SSL_state_string(s), SSL_state_string_long(s));
- } else if (ret < 0) {
- JNI_TRACE("ssl=%p %s:error exit in %s %s",
- s, str, SSL_state_string(s), SSL_state_string_long(s));
- } else if (ret == 1) {
- JNI_TRACE("ssl=%p %s:ok exit in %s %s",
- s, str, SSL_state_string(s), SSL_state_string_long(s));
- } else {
- JNI_TRACE("ssl=%p %s:unknown exit %d in %s %s",
- s, str, ret, SSL_state_string(s), SSL_state_string_long(s));
- }
- } else if (where & SSL_CB_HANDSHAKE_START) {
- JNI_TRACE("ssl=%p handshake start in %s %s",
- s, SSL_state_string(s), SSL_state_string_long(s));
- } else if (where & SSL_CB_HANDSHAKE_DONE) {
- JNI_TRACE("ssl=%p handshake done in %s %s",
- s, SSL_state_string(s), SSL_state_string_long(s));
- } else {
- JNI_TRACE("ssl=%p %s:unknown where %d in %s %s",
- s, str, where, SSL_state_string(s), SSL_state_string_long(s));
- }
-}
-
-/**
- * Returns an array containing all the X509 certificate's bytes.
- */
-static jobjectArray getCertificateBytes(JNIEnv* env,
- const STACK_OF(X509) *chain)
-{
- if (chain == NULL) {
- // Chain can be NULL if the associated cipher doesn't do certs.
- return NULL;
- }
-
- int count = sk_X509_num(chain);
- if (count <= 0) {
- NULL;
- }
-
- jobjectArray joa = env->NewObjectArray(count, env->FindClass("[B"), NULL);
- if (joa == NULL) {
- return NULL;
- }
-
- BIO* bio = BIO_new(BIO_s_mem());
-
- // LOGD("Start fetching the certificates");
- for (int i = 0; i < count; i++) {
- X509* cert = sk_X509_value(chain, i);
-
- BIO_reset(bio);
- PEM_write_bio_X509(bio, cert);
-
- BUF_MEM* bptr;
- BIO_get_mem_ptr(bio, &bptr);
- jbyteArray bytes = env->NewByteArray(bptr->length);
-
- if (bytes == NULL) {
- /*
- * Indicate an error by resetting joa to NULL. It will
- * eventually get gc'ed.
- */
- joa = NULL;
- break;
- }
- jbyte* src = reinterpret_cast<jbyte*>(bptr->data);
- env->SetByteArrayRegion(bytes, 0, bptr->length, src);
- env->SetObjectArrayElement(joa, i, bytes);
- }
-
- // LOGD("Certificate fetching complete");
- BIO_free(bio);
- return joa;
-}
-
-/**
- * Our additional application data needed for getting synchronization right.
- * This maybe warrants a bit of lengthy prose:
- *
- * (1) We use a flag to reflect whether we consider the SSL connection alive.
- * Any read or write attempt loops will be cancelled once this flag becomes 0.
- *
- * (2) We use an int to count the number of threads that are blocked by the
- * underlying socket. This may be at most two (one reader and one writer), since
- * the Java layer ensures that no more threads will enter the native code at the
- * same time.
- *
- * (3) The pipe is used primarily as a means of cancelling a blocking select()
- * when we want to close the connection (aka "emergency button"). It is also
- * necessary for dealing with a possible race condition situation: There might
- * be cases where both threads see an SSL_ERROR_WANT_READ or
- * SSL_ERROR_WANT_WRITE. Both will enter a select() with the proper argument.
- * If one leaves the select() successfully before the other enters it, the
- * "success" event is already consumed and the second thread will be blocked,
- * possibly forever (depending on network conditions).
- *
- * The idea for solving the problem looks like this: Whenever a thread is
- * successful in moving around data on the network, and it knows there is
- * another thread stuck in a select(), it will write a byte to the pipe, waking
- * up the other thread. A thread that returned from select(), on the other hand,
- * knows whether it's been woken up by the pipe. If so, it will consume the
- * byte, and the original state of affairs has been restored.
- *
- * The pipe may seem like a bit of overhead, but it fits in nicely with the
- * other file descriptors of the select(), so there's only one condition to wait
- * for.
- *
- * (4) Finally, a mutex is needed to make sure that at most one thread is in
- * either SSL_read() or SSL_write() at any given time. This is an OpenSSL
- * requirement. We use the same mutex to guard the field for counting the
- * waiting threads.
- *
- * Note: The current implementation assumes that we don't have to deal with
- * problems induced by multiple cores or processors and their respective
- * memory caches. One possible problem is that of inconsistent views on the
- * "aliveAndKicking" field. This could be worked around by also enclosing all
- * accesses to that field inside a lock/unlock sequence of our mutex, but
- * currently this seems a bit like overkill. Marking volatile at the very least.
- *
- * During handshaking, three additional fields are used to up-call into
- * Java to perform certificate verification and handshake completion.
- *
- * (5) the JNIEnv so we can invoke the Java callback
- *
- * (6) a NativeCrypto.CertificateChainVerifier to call with the peer certificate chain
- *
- * (7) a NativeCrypto.HandshakeCompletedCallback to call back when handshake is done
- *
- * These fields are cleared by the info_callback the handshake has
- * completed. SSL_VERIFY_CLIENT_ONCE is currently used to disable
- * renegotiation but if that changes, care would need to be taken to
- * maintain an appropriate JNIEnv on any downcall to openssl that
- * could result in an upcall to Java. The current code does try to
- * cover these cases by conditionally setting the JNIenv on calls that
- * can read and write to the SSL such as SSL_do_handshake, SSL_read,
- * SSL_write, and SSL_shutdown if handshaking is not complete.
- *
- */
-class AppData {
- public:
- volatile int aliveAndKicking;
- int waitingThreads;
- int fdsEmergency[2];
- MUTEX_TYPE mutex;
- JNIEnv* env;
- jobject certificateChainVerifier;
- jobject handshakeCompletedCallback;
-
- /**
- * Creates our application data and attaches it to a given SSL connection.
- *
- * @param ssl The SSL connection to attach the data to.
- * @param env The JNIEnv
- * @param ccv The CertificateChainVerifier
- * @param hcc The HandshakeCompletedCallback
- */
- public:
- static AppData* create(JNIEnv* e, jobject ccv, jobject hcc) {
- AppData* appData = new AppData(e, ccv, hcc);
- appData->fdsEmergency[0] = -1;
- appData->fdsEmergency[1] = -1;
- if (pipe(appData->fdsEmergency) == -1) {
- return NULL;
- }
- if (MUTEX_SETUP(appData->mutex) == -1) {
- return NULL;
- }
- return appData;
- }
-
- private:
- AppData(JNIEnv* e, jobject ccv, jobject hcc) :
- aliveAndKicking(1),
- waitingThreads(0),
- env(e),
- certificateChainVerifier(ccv),
- handshakeCompletedCallback(hcc) {}
-
- /**
- * Destroys our application data, cleaning up everything in the process.
- */
- public:
- ~AppData() {
- aliveAndKicking = 0;
- if (fdsEmergency[0] != -1) {
- close(fdsEmergency[0]);
- }
- if (fdsEmergency[1] != -1) {
- close(fdsEmergency[1]);
- }
- MUTEX_CLEANUP(mutex);
- }
-
- void setEnv(JNIEnv* e) {
- if (handshakeCompletedCallback == NULL) {
- return;
- }
- env = e;
- }
- void clearEnv() {
- env = NULL;
- }
-};
-
-/**
- * Dark magic helper function that checks, for a given SSL session, whether it
- * can SSL_read() or SSL_write() without blocking. Takes into account any
- * concurrent attempts to close the SSL session from the Java side. This is
- * needed to get rid of the hangs that occur when thread #1 closes the SSLSocket
- * while thread #2 is sitting in a blocking read or write. The type argument
- * specifies whether we are waiting for readability or writability. It expects
- * to be passed either SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE, since we
- * only need to wait in case one of these problems occurs.
- *
- * @param type Either SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE
- * @param fd The file descriptor to wait for (the underlying socket)
- * @param data The application data structure with mutex info etc.
- * @param timeout The timeout value for select call, with the special value
- * 0 meaning no timeout at all (wait indefinitely). Note: This is
- * the Java semantics of the timeout value, not the usual
- * select() semantics.
- * @return The result of the inner select() call, -1 on additional errors
- */
-static int sslSelect(int type, int fd, AppData* appData, int timeout) {
- fd_set rfds;
- fd_set wfds;
-
- FD_ZERO(&rfds);
- FD_ZERO(&wfds);
-
- if (type == SSL_ERROR_WANT_READ) {
- FD_SET(fd, &rfds);
- } else {
- FD_SET(fd, &wfds);
- }
-
- FD_SET(appData->fdsEmergency[0], &rfds);
-
- int max = fd > appData->fdsEmergency[0] ? fd : appData->fdsEmergency[0];
-
- // Build a struct for the timeout data if we actually want a timeout.
- struct timeval tv;
- struct timeval *ptv;
- if (timeout > 0) {
- tv.tv_sec = timeout / 1000;
- tv.tv_usec = 0;
- ptv = &tv;
- } else {
- ptv = NULL;
- }
-
- // LOGD("Doing select() for SSL_ERROR_WANT_%s...", type == SSL_ERROR_WANT_READ ? "READ" : "WRITE");
- int result = select(max + 1, &rfds, &wfds, NULL, ptv);
- // LOGD("Returned from select(), result is %d", result);
-
- // Lock
- if (MUTEX_LOCK(appData->mutex) == -1) {
- return -1;
- }
-
- // If we have been woken up by the emergency pipe, there must be a token in
- // it. Thus we can safely read it (even in a blocking way).
- if (FD_ISSET(appData->fdsEmergency[0], &rfds)) {
- char token;
- do {
- read(appData->fdsEmergency[0], &token, 1);
- } while (errno == EINTR);
- }
-
- // Tell the world that there is now one thread less waiting for the
- // underlying network.
- appData->waitingThreads--;
-
- // Unlock
- MUTEX_UNLOCK(appData->mutex);
- // LOGD("leave sslSelect");
- return result;
-}
-
-/**
- * Helper function that wakes up a thread blocked in select(), in case there is
- * one. Is being called by sslRead() and sslWrite() as well as by JNI glue
- * before closing the connection.
- *
- * @param data The application data structure with mutex info etc.
- */
-static void sslNotify(AppData* appData) {
- // Write a byte to the emergency pipe, so a concurrent select() can return.
- // Note we have to restore the errno of the original system call, since the
- // caller relies on it for generating error messages.
- int errnoBackup = errno;
- char token = '*';
- do {
- errno = 0;
- write(appData->fdsEmergency[1], &token, 1);
- } while (errno == EINTR);
- errno = errnoBackup;
-}
-
-// From private header file external/openssl/ssl_locl.h
-#define SSL_aRSA 0x00000001L
-#define SSL_aDSS 0x00000002L
-#define SSL_aNULL 0x00000004L
-#define SSL_aDH 0x00000008L
-#define SSL_aECDH 0x00000010L
-#define SSL_aKRB5 0x00000020L
-#define SSL_aECDSA 0x00000040L
-#define SSL_aPSK 0x00000080L
-
-/**
- * Converts an SSL_CIPHER's algorithms field to a TrustManager auth argument
- */
-static const char* SSL_CIPHER_authentication_method(const SSL_CIPHER* cipher)
-{
- unsigned long alg_auth = cipher->algorithm_auth;
-
- const char *au;
- switch (alg_auth) {
- case SSL_aRSA:
- au="RSA";
- break;
- case SSL_aDSS:
- au="DSS";
- break;
- case SSL_aDH:
- au="DH";
- break;
- case SSL_aKRB5:
- au="KRB5";
- break;
- case SSL_aECDH:
- au = "ECDH";
- break;
- case SSL_aNULL:
- au="None";
- break;
- case SSL_aECDSA:
- au="ECDSA";
- break;
- case SSL_aPSK:
- au="PSK";
- break;
- default:
- au="unknown";
- break;
- }
- return au;
-}
-
-/**
- * Verify the X509 certificate via SSL_CTX_set_cert_verify_callback
- */
-static int cert_verify_callback(X509_STORE_CTX* x509_store_ctx, void* arg)
-{
- /* Get the correct index to the SSLobject stored into X509_STORE_CTX. */
- SSL* ssl = (SSL*)X509_STORE_CTX_get_ex_data(x509_store_ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
- JNI_TRACE("ssl=%p cert_verify_callback x509_store_ctx=%p arg=%p", ssl, x509_store_ctx, arg);
-
- AppData* appData = (AppData*) SSL_get_app_data(ssl);
- JNIEnv* env = appData->env;
- if (env == NULL) {
- LOGE("AppData->env missing in cert_verify_callback");
- JNI_TRACE("ssl=%p cert_verify_callback => 0", ssl, result);
- return 0;
- }
- jobject certificateChainVerifier = appData->certificateChainVerifier;
-
- jclass cls = env->GetObjectClass(certificateChainVerifier);
- jmethodID methodID = env->GetMethodID(cls, "verifyCertificateChain", "([[BLjava/lang/String;)V");
-
- jobjectArray objectArray = getCertificateBytes(env, x509_store_ctx->untrusted);
-
- const char* authMethod;
- switch (ssl->version) {
- case SSL2_VERSION:
- authMethod = "RSA";
- break;
- case SSL3_VERSION:
- case TLS1_VERSION:
- case DTLS1_VERSION:
- authMethod = SSL_CIPHER_authentication_method(ssl->s3->tmp.new_cipher);
- break;
- default:
- authMethod = "unknown";
- break;
- }
- jstring authMethodString = env->NewStringUTF(authMethod);
-
- env->CallVoidMethod(certificateChainVerifier, methodID, objectArray, authMethodString);
-
- int result = (env->ExceptionCheck()) ? 0 : 1;
- JNI_TRACE("ssl=%p cert_verify_callback => %d", ssl, result);
- return result;
-}
-
-/**
- * Call back to watch for handshake to be completed. This is necessary
- * for SSL_MODE_HANDSHAKE_CUTTHROUGH support, since SSL_do_handshake
- * returns before the handshake is completed in this case.
- */
-static void info_callback(const SSL *ssl, int where, int ret) {
- JNI_TRACE("ssl=%p info_callback where=0x%x ret=%d", ssl, where, ret);
-#ifdef WITH_JNI_TRACE
- info_callback_LOG(ssl, where, ret);
-#endif
- if (!(where & SSL_CB_HANDSHAKE_DONE)) {
- JNI_TRACE("ssl=%p info_callback ignored", ssl);
- return;
- }
-
- AppData* appData = (AppData*) SSL_get_app_data(ssl);
- JNIEnv* env = appData->env;
- if (env == NULL) {
- LOGE("AppData->env missing in info_callback");
- JNI_TRACE("ssl=%p info_callback env error", ssl, result);
- return;
- }
- jobject handshakeCompletedCallback = appData->handshakeCompletedCallback;
-
- jclass cls = env->GetObjectClass(handshakeCompletedCallback);
- jmethodID methodID = env->GetMethodID(cls, "handshakeCompleted", "()V");
-
- JNI_TRACE("ssl=%p info_callback calling handshakeCompleted", ssl);
- env->CallVoidMethod(handshakeCompletedCallback, methodID);
-
- if (env->ExceptionCheck()) {
- JNI_TRACE("ssl=%p info_callback exception", ssl);
- }
-
- // no longer needed after handshake is complete
- appData->env = NULL;
- appData->certificateChainVerifier = NULL;
- appData->handshakeCompletedCallback = NULL;
- JNI_TRACE("ssl=%p info_callback completed", ssl);
-}
-
-/*
- * public static native int SSL_CTX_new();
- */
-static int NativeCrypto_SSL_CTX_new(JNIEnv* env, jclass clazz) {
- SSL_CTX* sslCtx = SSL_CTX_new(SSLv23_method());
- // Note: We explicitly do not allow SSLv2 to be used.
- SSL_CTX_set_options(sslCtx, SSL_OP_ALL | SSL_OP_NO_SSLv2);
-
- int mode = SSL_CTX_get_mode(sslCtx);
- /*
- * Turn on "partial write" mode. This means that SSL_write() will
- * behave like Posix write() and possibly return after only
- * writing a partial buffer. Note: The alternative, perhaps
- * surprisingly, is not that SSL_write() always does full writes
- * but that it will force you to retry write calls having
- * preserved the full state of the original call. (This is icky
- * and undesirable.)
- */
- mode |= SSL_MODE_ENABLE_PARTIAL_WRITE;
-#if defined(SSL_MODE_SMALL_BUFFERS) /* not all SSL versions have this */
- mode |= SSL_MODE_SMALL_BUFFERS; /* lazily allocate record buffers; usually saves
- * 44k over the default */
-#endif
-#if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH) /* not all SSL versions have this */
- mode |= SSL_MODE_HANDSHAKE_CUTTHROUGH; /* enable sending of client data as soon as
- * ClientCCS and ClientFinished are sent */
-#endif
- SSL_CTX_set_mode(sslCtx, mode);
-
- SSL_CTX_set_cert_verify_callback(sslCtx, cert_verify_callback, NULL);
- SSL_CTX_set_info_callback(sslCtx, info_callback);
-
-#ifdef WITH_JNI_TRACE
- SSL_CTX_set_msg_callback(sslCtx, ssl_msg_callback_LOG); /* enable for message debug */
-#endif
- JNI_TRACE("NativeCrypto_SSL_CTX_new => %p", sslCtx);
- return (jint) sslCtx;
-}
-
-static jobjectArray makeCipherList(JNIEnv* env, STACK_OF(SSL_CIPHER)* cipher_list) {
- // Create a String[].
- jclass stringClass = env->FindClass("java/lang/String");
- if (stringClass == NULL) {
- return NULL;
- }
- int cipherCount = sk_SSL_CIPHER_num(cipher_list);
- jobjectArray array = env->NewObjectArray(cipherCount, stringClass, NULL);
- if (array == NULL) {
- return NULL;
- }
-
- // Fill in the cipher names.
- for (int i = 0; i < cipherCount; ++i) {
- const char* c = sk_SSL_CIPHER_value(cipher_list, i)->name;
- JNI_TRACE("makeCipherList[i=%d]=%s", i, c);
- env->SetObjectArrayElement(array, i, env->NewStringUTF(c));
- }
- return array;
-}
-
-/**
- * Loads the ciphers suites that are supported by an SSL_CTX
- * and returns them in a string array.
- */
-static jobjectArray NativeCrypto_SSL_CTX_get_ciphers(JNIEnv* env,
- jclass, jint ssl_ctx_address)
-{
- SSL_CTX* ssl_ctx = reinterpret_cast<SSL_CTX*>(static_cast<uintptr_t>(ssl_ctx_address));
- JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_get_ciphers", ssl_ctx);
- if (ssl_ctx == NULL) {
- jniThrowNullPointerException(env, "SSL_CTX is null");
- return NULL;
- }
- return makeCipherList(env, ssl_ctx->cipher_list);
-}
-
-/**
- * public static native void SSL_CTX_free(int ssl_ctx)
- */
-static void NativeCrypto_SSL_CTX_free(JNIEnv* env,
- jclass, jint ssl_ctx_address)
-{
- SSL_CTX* ssl_ctx = reinterpret_cast<SSL_CTX*>(static_cast<uintptr_t>(ssl_ctx_address));
- JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_free", ssl_ctx);
- if (ssl_ctx == NULL) {
- jniThrowNullPointerException(env, "SSL_CTX is null");
- return;
- }
- env->DeleteGlobalRef((jobject) ssl_ctx->app_verify_arg);
- SSL_CTX_free(ssl_ctx);
-}
-
-/**
- * Gets the chars of a String object as a '\0'-terminated UTF-8 string,
- * stored in a freshly-allocated BIO memory buffer.
- */
-static BIO* stringToMemBuf(JNIEnv* env, jstring string) {
- jsize byteCount = env->GetStringUTFLength(string);
- LocalArray<1024> buf(byteCount + 1);
- env->GetStringUTFRegion(string, 0, env->GetStringLength(string), &buf[0]);
-
- BIO* result = BIO_new(BIO_s_mem());
- BIO_puts(result, &buf[0]);
- return result;
-}
-
-/**
- * public static native int SSL_new(int ssl_ctx, String privatekey, String certificate, byte[] seed,
- * CertificateChainVerifier ccv) throws SSLException;
- */
-static jint NativeCrypto_SSL_new(JNIEnv* env, jclass,
- jint ssl_ctx_address, jstring privatekey, jstring certificates, jbyteArray seed, jobject ccv)
-{
- SSL_CTX* ssl_ctx = reinterpret_cast<SSL_CTX*>(static_cast<uintptr_t>(ssl_ctx_address));
- JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new privatekey=%p certificates=%p seed=%p ccv=%p",
- ssl_ctx, privatekey, certificates, seed, ccv);
- if (ssl_ctx == NULL) {
- jniThrowNullPointerException(env, "SSL_CTX is null");
- JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new => NULL", ssl_ctx);
- return NULL;
- }
-
- // 'seed == null' when no SecureRandom Object is set
- // in the SSLContext.
- if (seed != NULL) {
- jbyte* randseed = env->GetByteArrayElements(seed, NULL);
- RAND_seed((unsigned char*) randseed, 1024);
- env->ReleaseByteArrayElements(seed, randseed, 0);
- } else {
- RAND_load_file("/dev/urandom", 1024);
- }
-
- SSL* ssl = SSL_new(ssl_ctx);
- if (ssl == NULL) {
- throwSSLExceptionWithSslErrors(env, 0, 0,
- "Unable to create SSL structure");
- JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new => NULL", ssl_ctx);
- return NULL;
- }
-
- /* Java code in class OpenSSLSocketImpl does the verification. Meaning of
- * SSL_VERIFY_NONE flag in client mode: if not using an anonymous cipher
- * (by default disabled), the server will send a certificate which will
- * be checked. The result of the certificate verification process can be
- * checked after the TLS/SSL handshake using the SSL_get_verify_result(3)
- * function. The handshake will be continued regardless of the
- * verification result.
- */
- SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL);
-
- if (privatekey != NULL) {
- BIO* privatekeybio = stringToMemBuf(env, (jstring) privatekey);
- EVP_PKEY* privatekeyevp =
- PEM_read_bio_PrivateKey(privatekeybio, NULL, 0, NULL);
- BIO_free(privatekeybio);
-
- if (privatekeyevp == NULL) {
- LOGE(ERR_error_string(ERR_get_error(), NULL));
- throwSSLExceptionWithSslErrors(env, 0, 0,
- "Error parsing the private key");
- SSL_free(ssl);
- JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new => NULL", ssl_ctx);
- return NULL;
- }
-
- BIO* certificatesbio = stringToMemBuf(env, (jstring) certificates);
- X509* certificatesx509 =
- PEM_read_bio_X509(certificatesbio, NULL, 0, NULL);
- BIO_free(certificatesbio);
-
- if (certificatesx509 == NULL) {
- LOGE(ERR_error_string(ERR_get_error(), NULL));
- throwSSLExceptionWithSslErrors(env, 0, 0,
- "Error parsing the certificates");
- EVP_PKEY_free(privatekeyevp);
- SSL_free(ssl);
- JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new => NULL", ssl_ctx);
- return NULL;
- }
-
- int ret = SSL_use_certificate(ssl, certificatesx509);
- if (ret != 1) {
- LOGE(ERR_error_string(ERR_get_error(), NULL));
- throwSSLExceptionWithSslErrors(env, ret, 0,
- "Error setting the certificates");
- X509_free(certificatesx509);
- EVP_PKEY_free(privatekeyevp);
- SSL_free(ssl);
- JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new => NULL", ssl_ctx);
- return NULL;
- }
-
- ret = SSL_use_PrivateKey(ssl, privatekeyevp);
- if (ret != 1) {
- LOGE(ERR_error_string(ERR_get_error(), NULL));
- throwSSLExceptionWithSslErrors(env, ret, 0,
- "Error setting the private key");
- X509_free(certificatesx509);
- EVP_PKEY_free(privatekeyevp);
- SSL_free(ssl);
- JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new => NULL", ssl_ctx);
- return NULL;
- }
-
- ret = SSL_check_private_key(ssl);
- if (ret != 1) {
- throwSSLExceptionWithSslErrors(env, ret, 0,
- "Error checking the private key");
- X509_free(certificatesx509);
- EVP_PKEY_free(privatekeyevp);
- SSL_free(ssl);
- JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new => NULL", ssl_ctx);
- return NULL;
- }
- }
- JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new => ssl=%p", ssl_ctx, ssl);
- return (jint)ssl;
-}
-
-/**
- * public static native long SSL_get_mode(int ssl);
- */
-static jlong NativeCrypto_SSL_get_mode(JNIEnv* env, jclass,
- jint ssl_address) {
- SSL* ssl = getSslPointer(env, ssl_address, true);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_get_mode", ssl);
- if (ssl == NULL) {
- JNI_TRACE("ssl=%p NativeCrypto_SSL_get_mode => 0", ssl);
- return 0;
- }
- long mode = SSL_get_mode(ssl);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_get_mode => 0x%lx", ssl, mode);
- return mode;
-}
-
-/**
- * public static native long SSL_set_mode(int ssl, long mode);
- */
-static jlong NativeCrypto_SSL_set_mode(JNIEnv* env, jclass,
- jint ssl_address, jlong mode) {
- SSL* ssl = getSslPointer(env, ssl_address, true);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_set_mode mode=0x%llx", ssl, mode);
- if (ssl == NULL) {
- return 0;
- }
- long result = SSL_set_mode(ssl, mode);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_set_mode => 0x%lx", ssl, result);
- return result;
-}
-
-/**
- * public static native long SSL_clear_mode(int ssl, long mode);
- */
-static jlong NativeCrypto_SSL_clear_mode(JNIEnv* env, jclass,
- jint ssl_address, jlong mode) {
- SSL* ssl = getSslPointer(env, ssl_address, true);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_mode mode=0x%llx", ssl, mode);
- if (ssl == NULL) {
- return 0;
- }
- long result = SSL_clear_mode(ssl, mode);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_mode => 0x%lx", ssl, result);
- return result;
-}
-
-/**
- * public static native long SSL_get_options(int ssl);
- */
-static jlong NativeCrypto_SSL_get_options(JNIEnv* env, jclass,
- jint ssl_address) {
- SSL* ssl = getSslPointer(env, ssl_address, true);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_get_options", ssl);
- if (ssl == NULL) {
- JNI_TRACE("ssl=%p NativeCrypto_SSL_get_options => 0", ssl);
- return 0;
- }
- long options = SSL_get_options(ssl);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_get_options => 0x%lx", ssl, options);
- return options;
-}
-
-/**
- * public static native long SSL_set_options(int ssl, long options);
- */
-static jlong NativeCrypto_SSL_set_options(JNIEnv* env, jclass,
- jint ssl_address, jlong options) {
- SSL* ssl = getSslPointer(env, ssl_address, true);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_set_options options=0x%llx", ssl, options);
- if (ssl == NULL) {
- return 0;
- }
- long result = SSL_set_options(ssl, options);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_set_options => 0x%lx", ssl, result);
- return result;
-}
-
-/**
- * public static native long SSL_clear_options(int ssl, long options);
- */
-static jlong NativeCrypto_SSL_clear_options(JNIEnv* env, jclass,
- jint ssl_address, jlong options) {
- SSL* ssl = getSslPointer(env, ssl_address, true);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_options options=0x%llx", ssl, options);
- if (ssl == NULL) {
- return 0;
- }
- long result = SSL_clear_options(ssl, options);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_options => 0x%lx", ssl, result);
- return result;
-}
-
-/**
- * Loads the ciphers suites that are enabled in the SSL
- * and returns them in a string array.
- */
-static jobjectArray NativeCrypto_SSL_get_ciphers(JNIEnv* env,
- jclass, jint ssl_address)
-{
- SSL* ssl = getSslPointer(env, ssl_address, true);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_get_ciphers", ssl);
- if (ssl == NULL) {
- return NULL;
- }
- return makeCipherList(env, SSL_get_ciphers(ssl));
-}
-
-/**
- * Sets the ciphers suites that are enabled in the SSL
- */
-static void NativeCrypto_SSL_set_cipher_list(JNIEnv* env, jclass,
- jint ssl_address, jstring controlString)
-{
- SSL* ssl = getSslPointer(env, ssl_address, true);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_set_cipher_list controlString=%p", ssl, controlString);
- if (ssl == NULL) {
- return;
- }
- const char* str = env->GetStringUTFChars(controlString, NULL);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_controlString str=%s", ssl, str);
- int rc = SSL_set_cipher_list(ssl, str);
- env->ReleaseStringUTFChars(controlString, str);
- if (rc == 0) {
- freeSslErrorState();
- jniThrowException(env, "java/lang/IllegalArgumentException",
- "Illegal cipher suite strings.");
- }
-}
-
-/**
- * Sets certificate expectations, especially for server to request client auth
- */
-static void NativeCrypto_SSL_set_verify(JNIEnv* env,
- jclass, jint ssl_address, jint mode)
-{
- SSL* ssl = getSslPointer(env, ssl_address, true);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_set_verify", ssl);
- if (ssl == NULL) {
- return;
- }
- SSL_set_verify(ssl, (int)mode, NULL);
-}
-
-/**
- * Sets the ciphers suites that are enabled in the SSL
- */
-static void NativeCrypto_SSL_set_session(JNIEnv* env, jclass,
- jint ssl_address, jint ssl_session_address)
-{
- SSL* ssl = getSslPointer(env, ssl_address, true);
- SSL_SESSION* ssl_session = reinterpret_cast<SSL_SESSION*>(static_cast<uintptr_t>(ssl_session_address));
- JNI_TRACE("ssl=%p NativeCrypto_SSL_set_session ssl_session=%p", ssl, ssl_session);
- if (ssl == NULL) {
- return;
- }
-
- int ret = SSL_set_session(ssl, ssl_session);
- if (ret != 1) {
- /*
- * Translate the error, and throw if it turns out to be a real
- * problem.
- */
- int sslErrorCode = SSL_get_error(ssl, ret);
- if (sslErrorCode != SSL_ERROR_ZERO_RETURN) {
- throwSSLExceptionWithSslErrors(env, ret, sslErrorCode,
- "SSL session set");
- SSL_clear(ssl);
- }
- }
-}
-
-/**
- * Sets the ciphers suites that are enabled in the SSL
- */
-static void NativeCrypto_SSL_set_session_creation_enabled(JNIEnv* env, jclass,
- jint ssl_address, jboolean creation_enabled)
-{
- SSL* ssl = getSslPointer(env, ssl_address, true);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_set_session_creation_enabled creation_enabled=%d", ssl, creation_enabled);
- if (ssl == NULL) {
- return;
- }
- SSL_set_session_creation_enabled(ssl, creation_enabled);
-}
-
-/**
- * Module scope variables initialized during JNI registration.
- */
-static jfieldID field_Socket_mImpl;
-static jfieldID field_Socket_mFD;
-
-/**
- * Perform SSL handshake
- */
-static jint NativeCrypto_SSL_do_handshake(JNIEnv* env, jclass,
- jint ssl_address, jobject socketObject, jobject ccv, jobject hcc, jint timeout, jboolean client_mode)
-{
- SSL* ssl = getSslPointer(env, ssl_address, true);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake socketObject=%p ccv=%p timeout=%d client_mode=%d",
- ssl, socketObject, ccv, timeout, client_mode);
- if (ssl == NULL) {
- JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake => 0", ssl);
- return 0;
- }
-
- if (socketObject == NULL) {
- jniThrowNullPointerException(env, "Socket is null");
- JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake => 0", ssl);
- return 0;
- }
- if (ccv == NULL) {
- jniThrowNullPointerException(env, "CertificateChainVerifier is null");
- JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake => 0", ssl);
- return 0;
- }
-
- jobject socketImplObject = env->GetObjectField(socketObject, field_Socket_mImpl);
- if (socketImplObject == NULL) {
- throwSSLExceptionStr(env,
- "couldn't get the socket impl from the socket");
- JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake => 0", ssl);
- return 0;
- }
-
- jobject fdObject = env->GetObjectField(socketImplObject, field_Socket_mFD);
- if (fdObject == NULL) {
- throwSSLExceptionStr(env,
- "couldn't get the file descriptor from the socket impl");
- JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake => 0", ssl);
- return 0;
- }
-
- int fd = jniGetFDFromFileDescriptor(env, fdObject);
- if (fd == -1) {
- throwSSLExceptionStr(env, "Invalid file descriptor");
- SSL_clear(ssl);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake => 0", ssl);
- return 0;
- }
-
- int ret = SSL_set_fd(ssl, fd);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake s=%d", ssl, fd);
-
- if (ret != 1) {
- throwSSLExceptionWithSslErrors(env, ret, 0,
- "Error setting the file descriptor");
- SSL_clear(ssl);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake => 0", ssl);
- return 0;
- }
-
- /*
- * Make socket non-blocking, so SSL_connect SSL_read() and SSL_write() don't hang
- * forever and we can use select() to find out if the socket is ready.
- */
- int mode = fcntl(fd, F_GETFL);
- if (mode == -1 || fcntl(fd, F_SETFL, mode | O_NONBLOCK) == -1) {
- throwSSLExceptionStr(env, "Unable to make socket non blocking");
- SSL_clear(ssl);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake => 0", ssl);
- return 0;
- }
-
- /*
- * Create our special application data.
- */
- AppData* appData = AppData::create(env, ccv, hcc);
- if (appData == NULL) {
- throwSSLExceptionStr(env, "Unable to create application data");
- SSL_clear(ssl);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake => 0", ssl);
- return 0;
- }
- SSL_set_app_data(ssl, (char*) appData);
-
- if (client_mode) {
- SSL_set_connect_state(ssl);
- } else {
- SSL_set_accept_state(ssl);
- }
-
- while (appData->aliveAndKicking) {
- errno = 0;
- appData->setEnv(env);
- ret = SSL_do_handshake(ssl);
- appData->clearEnv();
- // cert_verify_callback threw exception
- if (env->ExceptionCheck()) {
- SSL_clear(ssl);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake => 0", ssl);
- return 0;
- }
- if (ret == 1) {
- break;
- } else if (errno == EINTR) {
- continue;
- } else {
- // LOGD("SSL_connect: result %d, errno %d, timeout %d", ret, errno, timeout);
- int error = SSL_get_error(ssl, ret);
-
- /*
- * If SSL_connect doesn't succeed due to the socket being
- * either unreadable or unwritable, we use sslSelect to
- * wait for it to become ready. If that doesn't happen
- * before the specified timeout or an error occurs, we
- * cancel the handshake. Otherwise we try the SSL_connect
- * again.
- */
- if (error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE) {
- appData->waitingThreads++;
- int selectResult = sslSelect(error, fd, appData, timeout);
-
- if (selectResult == -1) {
- throwSSLExceptionWithSslErrors(env, -1, error,
- "handshake error");
- SSL_clear(ssl);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake => 0", ssl);
- return 0;
- } else if (selectResult == 0) {
- throwSocketTimeoutException(env, "SSL handshake timed out");
- SSL_clear(ssl);
- freeSslErrorState();
- JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake => 0", ssl);
- return 0;
- }
- } else {
- LOGE("Unknown error %d during handshake", error);
- break;
- }
- }
- }
-
- if (ret == 0) {
- /*
- * The other side closed the socket before the handshake could be
- * completed, but everything is within the bounds of the TLS protocol.
- * We still might want to find out the real reason of the failure.
- */
- int sslErrorCode = SSL_get_error(ssl, ret);
- if (sslErrorCode == SSL_ERROR_NONE ||
- (sslErrorCode == SSL_ERROR_SYSCALL && errno == 0)) {
- throwSSLExceptionStr(env, "Connection closed by peer");
- } else {
- throwSSLExceptionWithSslErrors(env, ret, sslErrorCode,
- "Trouble accepting connection");
- }
- SSL_clear(ssl);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake => 0", ssl);
- return 0;
- }
- if (ret < 0) {
- /*
- * Translate the error and throw exception. We are sure it is an error
- * at this point.
- */
- int sslErrorCode = SSL_get_error(ssl, ret);
- throwSSLExceptionWithSslErrors(env, ret, sslErrorCode,
- "Trouble accepting connection");
- SSL_clear(ssl);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake => 0", ssl);
- return 0;
- }
- SSL_SESSION* ssl_session = SSL_get1_session(ssl);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake => ssl_session=%p", ssl, ssl_session);
- return (jint) ssl_session;
-}
-
-/**
- * public static native byte[][] SSL_get_certificate(int ssl);
- */
-static jobjectArray NativeCrypto_SSL_get_certificate(JNIEnv* env, jclass, jint ssl_address)
-{
- SSL* ssl = getSslPointer(env, ssl_address, true);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate", ssl);
- if (ssl == NULL) {
- JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl);
- return NULL;
- }
- X509* certificate = SSL_get_certificate(ssl);
- if (certificate == NULL) {
- JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl);
- return NULL;
- }
- // TODO convert from single certificate to chain properly. One
- // option would be to have the chain remembered where
- // SSL_use_certificate is used. Another would be to save the
- // intermediate CAs with SSL_CTX SSL_CTX_add_extra_chain_cert.
- STACK_OF(X509)* chain = sk_X509_new_null();
- if (chain == NULL) {
- jniThrowRuntimeException(env, "Unable to allocate local certificate chain");
- JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl);
- return NULL;
- }
- sk_X509_push(chain, certificate);
- jobjectArray objectArray = getCertificateBytes(env, chain);
- sk_X509_free(chain);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => %p", ssl, objectArray);
- return objectArray;
-}
-
-
-/**
- * public static native void SSL_free(int ssl);
- */
-static void NativeCrypto_SSL_free(JNIEnv* env, jclass, jint ssl_address)
-{
- SSL* ssl = getSslPointer(env, ssl_address, true);
- JNI_TRACE("ssl=%p NativeCrypto_SSL_free", ssl);
- if (ssl == NULL) {
- return;
- }
- AppData* appData = (AppData*) SSL_get_app_data(ssl);
- delete appData;
- SSL_set_app_data(ssl, NULL);
- SSL_free(ssl);
-}
-
-/*
- * Defines the mapping from Java methods and their signatures
- * to native functions. Order is (1) Java name, (2) signature,
- * (3) pointer to C function.
- */
-static JNINativeMethod sNativeCryptoMethods[] = {
- { "clinit", "()V", (void*)NativeCrypto_clinit},
- { "EVP_PKEY_new_DSA", "([B[B[B[B[B)I", (void*)NativeCrypto_EVP_PKEY_new_DSA },
- { "EVP_PKEY_new_RSA", "([B[B[B[B[B)I", (void*)NativeCrypto_EVP_PKEY_new_RSA },
- { "EVP_PKEY_free", "(I)V", (void*)NativeCrypto_EVP_PKEY_free },
- { "EVP_new", "()I", (void*)NativeCrypto_EVP_new },
- { "EVP_free", "(I)V", (void*)NativeCrypto_EVP_free },
- { "EVP_DigestFinal", "(I[BI)I", (void*)NativeCrypto_EVP_DigestFinal },
- { "EVP_DigestInit", "(ILjava/lang/String;)V", (void*)NativeCrypto_EVP_DigestInit },
- { "EVP_DigestBlockSize", "(I)I", (void*)NativeCrypto_EVP_DigestBlockSize },
- { "EVP_DigestSize", "(I)I", (void*)NativeCrypto_EVP_DigestSize },
- { "EVP_DigestUpdate", "(I[BII)V", (void*)NativeCrypto_EVP_DigestUpdate },
- { "EVP_VerifyInit", "(ILjava/lang/String;)V", (void*)NativeCrypto_EVP_VerifyInit },
- { "EVP_VerifyUpdate", "(I[BII)V", (void*)NativeCrypto_EVP_VerifyUpdate },
- { "EVP_VerifyFinal", "(I[BIII)I", (void*)NativeCrypto_EVP_VerifyFinal },
- { "SSL_CTX_new", "()I", (void*)NativeCrypto_SSL_CTX_new },
- { "SSL_CTX_get_ciphers", "(I)[Ljava/lang/String;", (void*)NativeCrypto_SSL_CTX_get_ciphers},
- { "SSL_CTX_free", "(I)V", (void*)NativeCrypto_SSL_CTX_free },
- { "SSL_new", "(ILjava/lang/String;Ljava/lang/String;[B)I", (void*)NativeCrypto_SSL_new},
- { "SSL_get_mode", "(I)J", (void*)NativeCrypto_SSL_get_mode },
- { "SSL_set_mode", "(IJ)J", (void*)NativeCrypto_SSL_set_mode },
- { "SSL_clear_mode", "(IJ)J", (void*)NativeCrypto_SSL_clear_mode },
- { "SSL_get_options", "(I)J", (void*)NativeCrypto_SSL_get_options },
- { "SSL_set_options", "(IJ)J", (void*)NativeCrypto_SSL_set_options },
- { "SSL_clear_options", "(IJ)J", (void*)NativeCrypto_SSL_clear_options },
- { "SSL_get_ciphers", "(I)[Ljava/lang/String;", (void*)NativeCrypto_SSL_get_ciphers },
- { "SSL_set_cipher_list", "(ILjava/lang/String;)V", (void*)NativeCrypto_SSL_set_cipher_list },
- { "SSL_set_verify", "(II)V", (void*)NativeCrypto_SSL_set_verify},
- { "SSL_set_session", "(II)V", (void*)NativeCrypto_SSL_set_session },
- { "SSL_set_session_creation_enabled", "(IZ)V", (void*)NativeCrypto_SSL_set_session_creation_enabled },
- { "SSL_do_handshake", "(ILjava/net/Socket;Lorg/apache/harmony/xnet/provider/jsse/NativeCrypto$CertificateChainVerifier;Lorg/apache/harmony/xnet/provider/jsse/NativeCrypto$HandshakeCompletedCallback;IZ)I",(void*)NativeCrypto_SSL_do_handshake},
- { "SSL_get_certificate", "(I)[[B", (void*)NativeCrypto_SSL_get_certificate},
- { "SSL_free", "(I)V", (void*)NativeCrypto_SSL_free},
-};
-
-// ============================================================================
-// === OpenSSL-related helper stuff begins here. ==============================
-// ============================================================================
-
-/**
- * Helper function which does the actual reading. The Java layer guarantees that
- * at most one thread will enter this function at any given time.
- *
- * @param ssl non-null; the SSL context
- * @param buf non-null; buffer to read into
- * @param len length of the buffer, in bytes
- * @param sslReturnCode original SSL return code
- * @param sslErrorCode filled in with the SSL error code in case of error
- * @return number of bytes read on success, -1 if the connection was
- * cleanly shut down, or THROW_EXCEPTION if an exception should be thrown.
- */
-static int sslRead(JNIEnv* env, SSL* ssl, char* buf, jint len, int* sslReturnCode,
- int* sslErrorCode, int timeout) {
-
- // LOGD("Entering sslRead, caller requests to read %d bytes...", len);
-
- if (len == 0) {
- // Don't bother doing anything in this case.
- return 0;
- }
-
- int fd = SSL_get_fd(ssl);
- BIO* bio = SSL_get_rbio(ssl);
-
- AppData* appData = (AppData*) SSL_get_app_data(ssl);
-
- while (appData->aliveAndKicking) {
- errno = 0;
-
- // Lock
- if (MUTEX_LOCK(appData->mutex) == -1) {
- return -1;
- }
-
- unsigned int bytesMoved = BIO_number_read(bio) + BIO_number_written(bio);
-
- // LOGD("Doing SSL_Read()");
- AppData* appData = (AppData*) SSL_get_app_data(ssl);
- appData->setEnv(env);
- int result = SSL_read(ssl, buf, len);
- appData->clearEnv();
- int error = SSL_ERROR_NONE;
- if (result <= 0) {
- error = SSL_get_error(ssl, result);
- freeSslErrorState();
- }
- // LOGD("Returned from SSL_Read() with result %d, error code %d", result, error);
-
- // If we have been successful in moving data around, check whether it
- // might make sense to wake up other blocked threads, so they can give
- // it a try, too.
- if (BIO_number_read(bio) + BIO_number_written(bio) != bytesMoved && appData->waitingThreads > 0) {
- sslNotify(appData);
- }
-
- // If we are blocked by the underlying socket, tell the world that
- // there will be one more waiting thread now.
- if (error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE) {
- appData->waitingThreads++;
- }
-
- // Unlock
- MUTEX_UNLOCK(appData->mutex);
-
- switch (error) {
- // Sucessfully read at least one byte.
- case SSL_ERROR_NONE: {
- return result;
- }
-
- // Read zero bytes. End of stream reached.
- case SSL_ERROR_ZERO_RETURN: {
- return -1;
- }
-
- // Need to wait for availability of underlying layer, then retry.
- case SSL_ERROR_WANT_READ:
- case SSL_ERROR_WANT_WRITE: {
- int selectResult = sslSelect(error, fd, appData, timeout);
- if (selectResult == -1) {
- *sslReturnCode = -1;
- *sslErrorCode = error;
- return THROW_EXCEPTION;
- } else if (selectResult == 0) {
- return THROW_SOCKETTIMEOUTEXCEPTION;
- }
-
- break;
- }
-
- // A problem occured during a system call, but this is not
- // necessarily an error.
- case SSL_ERROR_SYSCALL: {
- // Connection closed without proper shutdown. Tell caller we
- // have reached end-of-stream.
- if (result == 0) {
- return -1;
- }
-
- // System call has been interrupted. Simply retry.
- if (errno == EINTR) {
- break;
- }
-
- // Note that for all other system call errors we fall through
- // to the default case, which results in an Exception.
- }
-
- // Everything else is basically an error.
- default: {
- *sslReturnCode = result;
- *sslErrorCode = error;
- return THROW_EXCEPTION;
- }
- }
- }
-
- return -1;
-}
-
-/**
- * Helper function which does the actual writing. The Java layer guarantees that
- * at most one thread will enter this function at any given time.
- *
- * @param ssl non-null; the SSL context
- * @param buf non-null; buffer to write
- * @param len length of the buffer, in bytes
- * @param sslReturnCode original SSL return code
- * @param sslErrorCode filled in with the SSL error code in case of error
- * @return number of bytes read on success, -1 if the connection was
- * cleanly shut down, or THROW_EXCEPTION if an exception should be thrown.
- */
-static int sslWrite(JNIEnv* env, SSL* ssl, const char* buf, jint len, int* sslReturnCode,
- int* sslErrorCode) {
-
- // LOGD("Entering sslWrite(), caller requests to write %d bytes...", len);
-
- if (len == 0) {
- // Don't bother doing anything in this case.
- return 0;
- }
-
- int fd = SSL_get_fd(ssl);
- BIO* bio = SSL_get_wbio(ssl);
-
- AppData* appData = (AppData*) SSL_get_app_data(ssl);
-
- int count = len;
-
- while (appData->aliveAndKicking && len > 0) {
- errno = 0;
- if (MUTEX_LOCK(appData->mutex) == -1) {
- return -1;
- }
-
- unsigned int bytesMoved = BIO_number_read(bio) + BIO_number_written(bio);
-
- // LOGD("Doing SSL_write() with %d bytes to go", len);
- appData->setEnv(env);
- int result = SSL_write(ssl, buf, len);
- appData->clearEnv();
- int error = SSL_ERROR_NONE;
- if (result <= 0) {
- error = SSL_get_error(ssl, result);
- freeSslErrorState();
- }
- // LOGD("Returned from SSL_write() with result %d, error code %d", result, error);
-
- // If we have been successful in moving data around, check whether it
- // might make sense to wake up other blocked threads, so they can give
- // it a try, too.
- if (BIO_number_read(bio) + BIO_number_written(bio) != bytesMoved && appData->waitingThreads > 0) {
- sslNotify(appData);
- }
-
- // If we are blocked by the underlying socket, tell the world that
- // there will be one more waiting thread now.
- if (error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE) {
- appData->waitingThreads++;
- }
-
- MUTEX_UNLOCK(appData->mutex);
-
- switch (error) {
- // Sucessfully write at least one byte.
- case SSL_ERROR_NONE: {
- buf += result;
- len -= result;
- break;
- }
-
- // Wrote zero bytes. End of stream reached.
- case SSL_ERROR_ZERO_RETURN: {
- return -1;
- }
-
- // Need to wait for availability of underlying layer, then retry.
- // The concept of a write timeout doesn't really make sense, and
- // it's also not standard Java behavior, so we wait forever here.
- case SSL_ERROR_WANT_READ:
- case SSL_ERROR_WANT_WRITE: {
- int selectResult = sslSelect(error, fd, appData, 0);
- if (selectResult == -1) {
- *sslReturnCode = -1;
- *sslErrorCode = error;
- return THROW_EXCEPTION;
- } else if (selectResult == 0) {
- return THROW_SOCKETTIMEOUTEXCEPTION;
- }
-
- break;
- }
-
- // An problem occured during a system call, but this is not
- // necessarily an error.
- case SSL_ERROR_SYSCALL: {
- // Connection closed without proper shutdown. Tell caller we
- // have reached end-of-stream.
- if (result == 0) {
- return -1;
- }
-
- // System call has been interrupted. Simply retry.
- if (errno == EINTR) {
- break;
- }
-
- // Note that for all other system call errors we fall through
- // to the default case, which results in an Exception.
- }
-
- // Everything else is basically an error.
- default: {
- *sslReturnCode = result;
- *sslErrorCode = error;
- return THROW_EXCEPTION;
- }
- }
- }
- // LOGD("Successfully wrote %d bytes", count);
-
- return count;
-}
-
-/**
- * Helper function that creates an RSA public key from two buffers containing
- * the big-endian bit representation of the modulus and the public exponent.
- *
- * @param mod The data of the modulus
- * @param modLen The length of the modulus data
- * @param exp The data of the exponent
- * @param expLen The length of the exponent data
- *
- * @return A pointer to the new RSA structure, or NULL on error
- */
-static RSA* rsaCreateKey(unsigned char* mod, int modLen, unsigned char* exp, int expLen) {
- // LOGD("Entering rsaCreateKey()");
-
- RSA* rsa = RSA_new();
-
- rsa->n = BN_bin2bn((unsigned char*) mod, modLen, NULL);
- rsa->e = BN_bin2bn((unsigned char*) exp, expLen, NULL);
-
- if (rsa->n == NULL || rsa->e == NULL) {
- RSA_free(rsa);
- return NULL;
- }
-
- return rsa;
-}
-
-/**
- * Helper function that frees an RSA key. Just calls the corresponding OpenSSL
- * function.
- *
- * @param rsa The pointer to the new RSA structure to free.
- */
-static void rsaFreeKey(RSA* rsa) {
- // LOGD("Entering rsaFreeKey()");
-
- if (rsa != NULL) {
- RSA_free(rsa);
- }
-}
-
-/**
- * Helper function that verifies a given RSA signature for a given message.
- *
- * @param msg The message to verify
- * @param msgLen The length of the message
- * @param sig The signature to verify
- * @param sigLen The length of the signature
- * @param algorithm The name of the hash/sign algorithm to use, e.g. "RSA-SHA1"
- * @param rsa The RSA public key to use
- *
- * @return 1 on success, 0 on failure, -1 on error (check SSL errors then)
- *
- */
-static int rsaVerify(unsigned char* msg, unsigned int msgLen, unsigned char* sig,
- unsigned int sigLen, char* algorithm, RSA* rsa) {
-
- // LOGD("Entering rsaVerify(%x, %d, %x, %d, %s, %x)", msg, msgLen, sig, sigLen, algorithm, rsa);
-
- int result = -1;
-
- EVP_PKEY* key = EVP_PKEY_new();
- EVP_PKEY_set1_RSA(key, rsa);
-
- const EVP_MD *type = EVP_get_digestbyname(algorithm);
- if (type == NULL) {
- goto cleanup;
- }
-
- EVP_MD_CTX ctx;
-
- EVP_MD_CTX_init(&ctx);
- if (EVP_VerifyInit_ex(&ctx, type, NULL) == 0) {
- goto cleanup;
- }
-
- EVP_VerifyUpdate(&ctx, msg, msgLen);
- result = EVP_VerifyFinal(&ctx, sig, sigLen, key);
- EVP_MD_CTX_cleanup(&ctx);
-
- cleanup:
-
- if (key != NULL) {
- EVP_PKEY_free(key);
- }
-
- return result;
-}
-
-// ============================================================================
-// === OpenSSL-related helper stuff ends here. JNI glue follows. ==============
-// ============================================================================
-
-static jint org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_getsslsession(JNIEnv* env, jclass,
- jint ssl_address)
-{
- SSL* ssl = getSslPointer(env, ssl_address, true);
- JNI_TRACE("ssl=%p OpenSSLSocketImpl_getsslsession", ssl);
- if (ssl == NULL) {
- JNI_TRACE("ssl=%p OpenSSLSocketImpl_getsslsession => NULL", ssl);
- return NULL;
- }
- SSL_SESSION* ssl_session = SSL_get1_session(ssl);
- JNI_TRACE("ssl=%p OpenSSLSocketImpl_getsslsession => ssl_session=%p", ssl, ssl_session);
- return (jint) ssl_session;
-}
-
-/**
- * OpenSSL read function (1): only one chunk is read (returned as jint).
- */
-static jint org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_read(JNIEnv* env, jclass, jint ssl_address, jint timeout)
-{
- SSL* ssl = getSslPointer(env, ssl_address, true);
- JNI_TRACE("ssl=%p OpenSSLSocketImpl_readba timeout=%d", ssl, timeout);
- if (ssl == NULL) {
- return 0;
- }
-
- unsigned char byteRead;
- int returnCode = 0;
- int errorCode = 0;
-
- int ret = sslRead(env, ssl, (char *) &byteRead, 1, &returnCode, &errorCode, timeout);
-
- int result;
- switch (ret) {
- case THROW_EXCEPTION:
- // See sslRead() regarding improper failure to handle normal cases.
- throwSSLExceptionWithSslErrors(env, returnCode, errorCode,
- "Read error");
- result = -1;
- break;
- case THROW_SOCKETTIMEOUTEXCEPTION:
- throwSocketTimeoutException(env, "Read timed out");
- result = -1;
- break;
- case -1:
- // Propagate EOF upwards.
- result = -1;
- break;
- default:
- // Return the actual char read, make sure it stays 8 bits wide.
- result = ((jint) byteRead) & 0xFF;
- break;
- }
- JNI_TRACE("ssl=%p OpenSSLSocketImpl_read => %d", ssl, result);
- return result;
-}
-
-/**
- * OpenSSL read function (2): read into buffer at offset n chunks.
- * Returns 1 (success) or value <= 0 (failure).
- */
-static jint org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_readba(JNIEnv* env, jclass, jint ssl_address, jbyteArray dest, jint offset, jint len, jint timeout)
-{
- SSL* ssl = getSslPointer(env, ssl_address, true);
- JNI_TRACE("ssl=%p OpenSSLSocketImpl_readba dest=%p offset=%d len=%d timeout=%d", ssl, dest, offset, len, timeout);
- if (ssl == NULL) {
- return 0;
- }
-
- jbyte* bytes = env->GetByteArrayElements(dest, NULL);
- int returnCode = 0;
- int errorCode = 0;
-
- int ret = sslRead(env, ssl, (char*) (bytes + offset), len, &returnCode, &errorCode, timeout);
-
- env->ReleaseByteArrayElements(dest, bytes, 0);
-
- int result;
- if (ret == THROW_EXCEPTION) {
- // See sslRead() regarding improper failure to handle normal cases.
- throwSSLExceptionWithSslErrors(env, returnCode, errorCode,
- "Read error");
- result = -1;
- } else if(ret == THROW_SOCKETTIMEOUTEXCEPTION) {
- throwSocketTimeoutException(env, "Read timed out");
- result = -1;
- } else {
- result = ret;
- }
-
- JNI_TRACE("ssl=%p OpenSSLSocketImpl_readba => %d", ssl, result);
- return result;
-}
-
-/**
- * OpenSSL write function (1): only one chunk is written.
- */
-static void org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_write(JNIEnv* env, jclass, jint ssl_address, jint b)
-{
- SSL* ssl = getSslPointer(env, ssl_address, true);
- JNI_TRACE("ssl=%p OpenSSLSocketImpl_write b=%d", ssl, b);
- if (ssl == NULL) {
- return;
- }
-
- int returnCode = 0;
- int errorCode = 0;
- char buf[1] = { (char) b };
- int ret = sslWrite(env, ssl, buf, 1, &returnCode, &errorCode);
-
- if (ret == THROW_EXCEPTION) {
- // See sslWrite() regarding improper failure to handle normal cases.
- throwSSLExceptionWithSslErrors(env, returnCode, errorCode,
- "Write error");
- } else if(ret == THROW_SOCKETTIMEOUTEXCEPTION) {
- throwSocketTimeoutException(env, "Write timed out");
- }
-}
-
-/**
- * OpenSSL write function (2): write into buffer at offset n chunks.
- */
-static void org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_writeba(JNIEnv* env, jclass,
- jint ssl_address, jbyteArray dest, jint offset, jint len)
-{
- SSL* ssl = getSslPointer(env, ssl_address, true);
- JNI_TRACE("ssl=%p OpenSSLSocketImpl_writeba dest=%p offset=%d len=%d", ssl, dest, offset, len);
- if (ssl == NULL) {
- return;
- }
-
- jbyte* bytes = env->GetByteArrayElements(dest, NULL);
- int returnCode = 0;
- int errorCode = 0;
- int ret = sslWrite(env, ssl, (const char *) (bytes + offset), len, &returnCode, &errorCode);
-
- env->ReleaseByteArrayElements(dest, bytes, 0);
-
- if (ret == THROW_EXCEPTION) {
- // See sslWrite() regarding improper failure to handle normal cases.
- throwSSLExceptionWithSslErrors(env, returnCode, errorCode,
- "Write error");
- } else if(ret == THROW_SOCKETTIMEOUTEXCEPTION) {
- throwSocketTimeoutException(env, "Write timed out");
- }
-}
-
-/**
- * Interrupt any pending IO before closing the socket.
- */
-static void org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_interrupt(
- JNIEnv* env, jclass, jint ssl_address) {
- SSL* ssl = getSslPointer(env, ssl_address, false);
- JNI_TRACE("ssl=%p OpenSSLSocketImpl_interrupt", ssl);
- if (ssl == NULL) {
- return;
- }
-
- /*
- * Mark the connection as quasi-dead, then send something to the emergency
- * file descriptor, so any blocking select() calls are woken up.
- */
- AppData* appData = (AppData*) SSL_get_app_data(ssl);
- if (appData != NULL) {
- appData->aliveAndKicking = 0;
-
- // At most two threads can be waiting.
- sslNotify(appData);
- sslNotify(appData);
- }
-}
-
-/**
- * OpenSSL close SSL socket function.
- */
-static void org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_close(
- JNIEnv* env, jclass, jint ssl_address) {
- SSL* ssl = getSslPointer(env, ssl_address, false);
- JNI_TRACE("ssl=%p OpenSSLSocketImpl_close", ssl);
- if (ssl == NULL) {
- return;
- }
- /*
- * Try to make socket blocking again. OpenSSL literature recommends this.
- */
- int fd = SSL_get_fd(ssl);
- JNI_TRACE("ssl=%p OpenSSLSocketImpl_close s=%d", ssl, fd);
- if (fd != -1) {
- int mode = fcntl(fd, F_GETFL);
- if (mode == -1 || fcntl(fd, F_SETFL, mode & ~O_NONBLOCK) == -1) {
-// throwSSLExceptionStr(env, "Unable to make socket blocking again");
-// LOGW("Unable to make socket blocking again");
- }
- }
-
- AppData* appData = (AppData*) SSL_get_app_data(ssl);
- appData->setEnv(env);
- int ret = SSL_shutdown(ssl);
- appData->clearEnv();
- switch (ret) {
- case 0:
- /*
- * Shutdown was not successful (yet), but there also
- * is no error. Since we can't know whether the remote
- * server is actually still there, and we don't want to
- * get stuck forever in a second SSL_shutdown() call, we
- * simply return. This is not security a problem as long
- * as we close the underlying socket, which we actually
- * do, because that's where we are just coming from.
- */
- break;
- case 1:
- /*
- * Shutdown was sucessful. We can safely return. Hooray!
- */
- break;
- default:
- /*
- * Everything else is a real error condition. We should
- * let the Java layer know about this by throwing an
- * exception.
- */
- int sslErrorCode = SSL_get_error(ssl, ret);
- throwSSLExceptionWithSslErrors(env, ret, sslErrorCode, "SSL shutdown failed");
- break;
- }
-
- SSL_clear(ssl);
- freeSslErrorState();
-}
-
-/**
- * Verifies an RSA signature.
- */
-static int org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_verifysignature(JNIEnv* env, jclass clazz,
- jbyteArray msg, jbyteArray sig, jstring algorithm, jbyteArray mod, jbyteArray exp) {
-
- JNI_TRACE("OpenSSLSocketImpl_verifysignature msg=%p sig=%p algorithm=%p mod=%p exp%p",
- msg, sig, algorithm, mod, exp);
-
- if (msg == NULL || sig == NULL || algorithm == NULL || mod == NULL || exp == NULL) {
- jniThrowNullPointerException(env, NULL);
- JNI_TRACE("OpenSSLSocketImpl_verifysignature => -1");
- return -1;
- }
-
- int result = -1;
-
- jbyte* msgBytes = env->GetByteArrayElements(msg, NULL);
- jint msgLength = env->GetArrayLength(msg);
-
- jbyte* sigBytes = env->GetByteArrayElements(sig, NULL);
- jint sigLength = env->GetArrayLength(sig);
-
- jbyte* modBytes = env->GetByteArrayElements(mod, NULL);
- jint modLength = env->GetArrayLength(mod);
-
- jbyte* expBytes = env->GetByteArrayElements(exp, NULL);
- jint expLength = env->GetArrayLength(exp);
-
- const char* algorithmChars = env->GetStringUTFChars(algorithm, NULL);
- JNI_TRACE("OpenSSLSocketImpl_verifysignature algorithmChars=%s", algorithmChars);
-
- RSA* rsa = rsaCreateKey((unsigned char*) modBytes, modLength, (unsigned char*) expBytes, expLength);
- if (rsa != NULL) {
- result = rsaVerify((unsigned char*) msgBytes, msgLength, (unsigned char*) sigBytes, sigLength,
- (char*) algorithmChars, rsa);
- rsaFreeKey(rsa);
- }
-
- env->ReleaseStringUTFChars(algorithm, algorithmChars);
-
- env->ReleaseByteArrayElements(exp, expBytes, JNI_ABORT);
- env->ReleaseByteArrayElements(mod, modBytes, JNI_ABORT);
- env->ReleaseByteArrayElements(sig, sigBytes, JNI_ABORT);
- env->ReleaseByteArrayElements(msg, msgBytes, JNI_ABORT);
-
- if (result == -1) {
- int error = ERR_get_error();
- if (error != 0) {
- char message[50];
- ERR_error_string_n(error, message, sizeof(message));
- jniThrowRuntimeException(env, message);
- } else {
- jniThrowRuntimeException(env, "Internal error during verification");
- }
- freeSslErrorState();
- }
-
- JNI_TRACE("OpenSSLSocketImpl_verifysignature => %d", result);
- return result;
-}
-
-static JNINativeMethod sSocketImplMethods[] =
-{
- {"nativeread", "(II)I", (void*)org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_read},
- {"nativeread", "(I[BIII)I", (void*)org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_readba},
- {"nativewrite", "(II)V", (void*)org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_write},
- {"nativewrite", "(I[BII)V", (void*)org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_writeba},
- {"nativeinterrupt", "(I)V", (void*)org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_interrupt},
- {"nativeclose", "(I)V", (void*)org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_close},
- {"nativeverifysignature", "([B[BLjava/lang/String;[B[B)I", (void*)org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_verifysignature},
-};
-
-/**
- * Our implementation of what might be considered
- * SSL_SESSION_get_peer_cert_chain
- */
-static STACK_OF(X509)* SSL_SESSION_get_peer_cert_chain(SSL_CTX* ssl_ctx, SSL_SESSION* ssl_session) {
- SSL* ssl = SSL_new(ssl_ctx);
- SSL_set_session(ssl, ssl_session);
- STACK_OF(X509)* chain = SSL_get_peer_cert_chain(ssl);
- SSL_free(ssl);
- return chain;
-}
-
-// Fills a byte[][] with the peer certificates in the chain.
-static jobjectArray OpenSSLSessionImpl_getPeerCertificatesImpl(JNIEnv* env,
- jclass, jint ssl_ctx_address, jint ssl_session_address)
-{
- SSL_CTX* ssl_ctx = reinterpret_cast<SSL_CTX*>(static_cast<uintptr_t>(ssl_ctx_address));
- SSL_SESSION* ssl_session = reinterpret_cast<SSL_SESSION*>(static_cast<uintptr_t>(ssl_session_address));
- JNI_TRACE("ssl_session=%p OpenSSLSessionImpl_getPeerCertificatesImpl ssl_ctx=%p", ssl_session, ssl_ctx);
- if (ssl_ctx == NULL) {
- jniThrowNullPointerException(env, "SSL_CTX is null");
- JNI_TRACE("ssl_session=%p OpenSSLSessionImpl_getPeerCertificatesImpl => NULL", ssl_session);
- return NULL;
- }
- STACK_OF(X509)* chain = SSL_SESSION_get_peer_cert_chain(ssl_ctx, ssl_session);
- jobjectArray objectArray = getCertificateBytes(env, chain);
- JNI_TRACE("ssl_session=%p OpenSSLSessionImpl_getPeerCertificatesImpl => %p", ssl_session, objectArray);
- return objectArray;
-}
-
-/**
- * Serializes the native state of the session (ID, cipher, and keys but
- * not certificates). Returns a byte[] containing the DER-encoded state.
- * See apache mod_ssl.
- */
-static jbyteArray OpenSSLSessionImpl_getEncoded(JNIEnv* env, jclass, jint ssl_session_address) {
- SSL_SESSION* ssl_session = reinterpret_cast<SSL_SESSION*>(static_cast<uintptr_t>(ssl_session_address));
- JNI_TRACE("ssl_session=%p OpenSSLSessionImpl_getEncoded", ssl_session);
- if (ssl_session == NULL) {
- JNI_TRACE("ssl_session=%p OpenSSLSessionImpl_getEncoded => NULL", ssl_session);
- return NULL;
- }
-
- // Compute the size of the DER data
- int size = i2d_SSL_SESSION(ssl_session, NULL);
- if (size == 0) {
- JNI_TRACE("ssl_session=%p OpenSSLSessionImpl_getEncoded => NULL", ssl_session);
- return NULL;
- }
-
- jbyteArray bytes = env->NewByteArray(size);
- if (bytes != NULL) {
- jbyte* tmp = env->GetByteArrayElements(bytes, NULL);
- unsigned char* ucp = reinterpret_cast<unsigned char*>(tmp);
- i2d_SSL_SESSION(ssl_session, &ucp);
- env->ReleaseByteArrayElements(bytes, tmp, 0);
- }
-
- JNI_TRACE("ssl_session=%p OpenSSLSessionImpl_getEncoded => size=%d", ssl_session, size);
- return bytes;
-}
-
-/**
- * Deserialize the session.
- */
-static jint OpenSSLSessionImpl_initializeNativeImpl(JNIEnv* env, jclass, jbyteArray bytes, jint size) {
- JNI_TRACE("OpenSSLSessionImpl_initializeNativeImpl bytes=%p size=%d", bytes, size);
- if (bytes == NULL) {
- JNI_TRACE("OpenSSLSessionImpl_initializeNativeImpl => 0");
- return 0;
- }
-
- jbyte* tmp = env->GetByteArrayElements(bytes, NULL);
- const unsigned char* ucp = reinterpret_cast<const unsigned char*>(tmp);
- SSL_SESSION* ssl_session = d2i_SSL_SESSION(NULL, &ucp, size);
- env->ReleaseByteArrayElements(bytes, tmp, 0);
-
- JNI_TRACE("OpenSSLSessionImpl_initializeNativeImpl => %p", ssl_session);
- return static_cast<jint>(reinterpret_cast<uintptr_t>(ssl_session));
-}
-
-/**
- * Gets and returns in a byte array the ID of the actual SSL session.
- */
-static jbyteArray OpenSSLSessionImpl_getId(JNIEnv* env, jclass, jint ssl_session_address) {
- SSL_SESSION* ssl_session = reinterpret_cast<SSL_SESSION*>(static_cast<uintptr_t>(ssl_session_address));
- JNI_TRACE("ssl_session=%p OpenSSLSessionImpl_getId", ssl_session);
- jbyteArray result = env->NewByteArray(ssl_session->session_id_length);
- if (result != NULL) {
- jbyte* src = reinterpret_cast<jbyte*>(ssl_session->session_id);
- env->SetByteArrayRegion(result, 0, ssl_session->session_id_length, src);
- }
- JNI_TRACE("ssl_session=%p OpenSSLSessionImpl_getId => %p session_id_length=%d",
- ssl_session, result, ssl_session->session_id_length);
- return result;
-}
-
-/**
- * Gets and returns in a long integer the creation's time of the
- * actual SSL session.
- */
-static jlong OpenSSLSessionImpl_getCreationTime(JNIEnv* env, jclass, jint ssl_session_address) {
- SSL_SESSION* ssl_session = reinterpret_cast<SSL_SESSION*>(static_cast<uintptr_t>(ssl_session_address));
- JNI_TRACE("ssl_session=%p OpenSSLSessionImpl_getCreationTime", ssl_session);
- jlong result = SSL_SESSION_get_time(ssl_session); // must be jlong, not long or *1000 will overflow
- result *= 1000; // OpenSSL uses seconds, Java uses milliseconds.
- JNI_TRACE("ssl_session=%p OpenSSLSessionImpl_getCreationTime => %lld", ssl_session, result);
- return result;
-}
-
-/**
- * Our implementation of what might be considered
- * SSL_SESSION_get_version, based on SSL_get_version.
- * See get_ssl_version above.
- */
-static const char* SSL_SESSION_get_version(SSL_SESSION* ssl_session) {
- return get_ssl_version(ssl_session->ssl_version);
-}
-
-/**
- * Gets and returns in a string the version of the SSL protocol. If it
- * returns the string "unknown" it means that no connection is established.
- */
-static jstring OpenSSLSessionImpl_getProtocol(JNIEnv* env, jclass, jint ssl_session_address) {
- SSL_SESSION* ssl_session = reinterpret_cast<SSL_SESSION*>(static_cast<uintptr_t>(ssl_session_address));
- JNI_TRACE("ssl_session=%p OpenSSLSessionImpl_getProtocol", ssl_session);
- const char* protocol = SSL_SESSION_get_version(ssl_session);
- JNI_TRACE("ssl_session=%p OpenSSLSessionImpl_getProtocol => %s", ssl_session, protocol);
- jstring result = env->NewStringUTF(protocol);
- return result;
-}
-
-/**
- * Gets and returns in a string the set of ciphers the actual SSL session uses.
- */
-static jstring OpenSSLSessionImpl_getCipherSuite(JNIEnv* env, jclass, jint ssl_session_address) {
- SSL_SESSION* ssl_session = reinterpret_cast<SSL_SESSION*>(static_cast<uintptr_t>(ssl_session_address));
- JNI_TRACE("ssl_session=%p OpenSSLSessionImpl_getCipherSuite", ssl_session);
- const SSL_CIPHER* cipher = ssl_session->cipher;
- const char* name = SSL_CIPHER_get_name(cipher);
- JNI_TRACE("ssl_session=%p OpenSSLSessionImpl_getCipherSuite => %s", ssl_session, name);
- return env->NewStringUTF(name);
-}
-
-/**
- * Frees the SSL session.
- */
-static void OpenSSLSessionImpl_freeImpl(JNIEnv* env, jclass, jint session) {
- SSL_SESSION* ssl_session = reinterpret_cast<SSL_SESSION*>(session);
- JNI_TRACE("ssl_session=%p OpenSSLSessionImpl_freeImpl", ssl_session);
- SSL_SESSION_free(ssl_session);
-}
-
-static JNINativeMethod sSessionImplMethods[] = {
- { "freeImpl", "(I)V", (void*) OpenSSLSessionImpl_freeImpl },
- { "getCipherSuite", "(I)Ljava/lang/String;", (void*) OpenSSLSessionImpl_getCipherSuite },
- { "getCreationTime", "(I)J", (void*) OpenSSLSessionImpl_getCreationTime },
- { "getEncoded", "(I)[B", (void*) OpenSSLSessionImpl_getEncoded },
- { "getId", "(I)[B", (void*) OpenSSLSessionImpl_getId },
- { "getPeerCertificatesImpl", "(II)[[B", (void*) OpenSSLSessionImpl_getPeerCertificatesImpl },
- { "getProtocol", "(I)Ljava/lang/String;", (void*) OpenSSLSessionImpl_getProtocol },
- { "initializeNativeImpl", "([BI)I", (void*) OpenSSLSessionImpl_initializeNativeImpl },
-};
-
-typedef struct {
- const char* name;
- const JNINativeMethod* methods;
- jint nMethods;
-} JNINativeClass;
-
-static JNINativeClass sClasses[] = {
- { "org/apache/harmony/xnet/provider/jsse/NativeCrypto", sNativeCryptoMethods, NELEM(sNativeCryptoMethods) },
- { "org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImpl", sSocketImplMethods, NELEM(sSocketImplMethods) },
- { "org/apache/harmony/xnet/provider/jsse/OpenSSLSessionImpl", sSessionImplMethods, NELEM(sSessionImplMethods) },
-};
-int register_org_apache_harmony_xnet_provider_jsse_NativeCrypto(JNIEnv* env) {
- JNI_TRACE("register_org_apache_harmony_xnet_provider_jsse_NativeCrypto");
- // Register org.apache.harmony.xnet.provider.jsse.* methods
- for (int i = 0; i < NELEM(sClasses); i++) {
- int result = jniRegisterNativeMethods(env,
- sClasses[i].name,
- sClasses[i].methods,
- sClasses[i].nMethods);
- if (result == -1) {
- return -1;
- }
- }
-
- // java.net.Socket
- jclass socket = env->FindClass("java/net/Socket");
- if (socket == NULL) {
- LOGE("Can't find class java.net.Socket");
- return -1;
- }
- field_Socket_mImpl = env->GetFieldID(socket, "impl", "Ljava/net/SocketImpl;");
- if (field_Socket_mImpl == NULL) {
- LOGE("Can't find field impl in class java.net.Socket");
- return -1;
- }
-
- // java.net.SocketImpl
- jclass socketImplClass = env->FindClass("java/net/SocketImpl");
- if (socketImplClass == NULL) {
- LOGE("Can't find class java.net.SocketImpl");
- return -1;
- }
- field_Socket_mFD = env->GetFieldID(socketImplClass, "fd", "Ljava/io/FileDescriptor;");
- if (field_Socket_mFD == NULL) {
- LOGE("Can't find field fd in java.net.SocketImpl");
- return -1;
- }
-
- return 0;
-}
diff --git a/x-net/src/main/native/sub.mk b/x-net/src/main/native/sub.mk
deleted file mode 100644
index f5aa84a..0000000
--- a/x-net/src/main/native/sub.mk
+++ /dev/null
@@ -1,21 +0,0 @@
-# This file is included by the top-level libcore Android.mk.
-# It's not a normal makefile, so we don't include CLEAR_VARS
-# or BUILD_*_LIBRARY.
-
-LOCAL_SRC_FILES := \
- org_apache_harmony_xnet_provider_jsse_NativeCrypto.cpp
-
-LOCAL_C_INCLUDES += \
- external/openssl/include
-
-
-# Any shared/static libs that are listed here must also
-# be listed in libs/nativehelper/Android.mk.
-# TODO: fix this requirement
-
-LOCAL_SHARED_LIBRARIES += \
- libcrypto \
- libssl \
- libutils
-
-LOCAL_STATIC_LIBRARIES +=
diff --git a/x-net/src/test/impl/java.injected/org/apache/harmony/xnet/provider/jsse/ClientSessionContextTest.java b/x-net/src/test/impl/java.injected/org/apache/harmony/xnet/provider/jsse/ClientSessionContextTest.java
deleted file mode 100644
index af4490b..0000000
--- a/x-net/src/test/impl/java.injected/org/apache/harmony/xnet/provider/jsse/ClientSessionContextTest.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import junit.framework.TestCase;
-
-import javax.net.ssl.SSLSession;
-import java.util.Enumeration;
-import java.util.Set;
-import java.util.HashSet;
-
-public class ClientSessionContextTest extends TestCase {
-
- public void testGetSessionById() {
- ClientSessionContext context = new ClientSessionContext(null, null);
-
- SSLSession a = new FakeSession("a");
- SSLSession b = new FakeSession("b");
-
- context.putSession(a);
- context.putSession(b);
-
- assertSame(a, context.getSession("a".getBytes()));
- assertSame(b, context.getSession("b".getBytes()));
-
- assertSame(a, context.getSession("a", 443));
- assertSame(b, context.getSession("b", 443));
-
- assertEquals(2, context.sessions.size());
-
- Set<SSLSession> sessions = new HashSet<SSLSession>();
- Enumeration ids = context.getIds();
- while (ids.hasMoreElements()) {
- sessions.add(context.getSession((byte[]) ids.nextElement()));
- }
-
- Set<SSLSession> expected = new HashSet<SSLSession>();
- expected.add(a);
- expected.add(b);
-
- assertEquals(expected, sessions);
- }
-
- public void testTrimToSize() {
- ClientSessionContext context = new ClientSessionContext(null, null);
-
- FakeSession a = new FakeSession("a");
- FakeSession b = new FakeSession("b");
- FakeSession c = new FakeSession("c");
- FakeSession d = new FakeSession("d");
-
- context.putSession(a);
- context.putSession(b);
- context.putSession(c);
- context.putSession(d);
-
- context.setSessionCacheSize(2);
-
- Set<SSLSession> sessions = new HashSet<SSLSession>();
- Enumeration ids = context.getIds();
- while (ids.hasMoreElements()) {
- sessions.add(context.getSession((byte[]) ids.nextElement()));
- }
-
- Set<SSLSession> expected = new HashSet<SSLSession>();
- expected.add(c);
- expected.add(d);
-
- assertEquals(expected, sessions);
- }
-
-}
diff --git a/x-net/src/test/impl/java.injected/org/apache/harmony/xnet/provider/jsse/FakeSession.java b/x-net/src/test/impl/java.injected/org/apache/harmony/xnet/provider/jsse/FakeSession.java
deleted file mode 100644
index 4a793dd..0000000
--- a/x-net/src/test/impl/java.injected/org/apache/harmony/xnet/provider/jsse/FakeSession.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSessionContext;
-import java.security.cert.Certificate;
-import java.security.Principal;
-
-class FakeSession implements SSLSession {
- final String host;
-
- FakeSession(String host) {
- this.host = host;
- }
-
- public int getApplicationBufferSize() {
- throw new UnsupportedOperationException();
- }
-
- public String getCipherSuite() {
- throw new UnsupportedOperationException();
- }
-
- public long getCreationTime() {
- throw new UnsupportedOperationException();
- }
-
- public byte[] getId() {
- return host.getBytes();
- }
-
- public long getLastAccessedTime() {
- throw new UnsupportedOperationException();
- }
-
- public Certificate[] getLocalCertificates() {
- throw new UnsupportedOperationException();
- }
-
- public Principal getLocalPrincipal() {
- throw new UnsupportedOperationException();
- }
-
- public int getPacketBufferSize() {
- throw new UnsupportedOperationException();
- }
-
- public javax.security.cert.X509Certificate[] getPeerCertificateChain() {
- throw new UnsupportedOperationException();
- }
-
- public Certificate[] getPeerCertificates() {
- throw new UnsupportedOperationException();
- }
-
- public String getPeerHost() {
- return host;
- }
-
- public int getPeerPort() {
- return 443;
- }
-
- public Principal getPeerPrincipal() {
- throw new UnsupportedOperationException();
- }
-
- public String getProtocol() {
- throw new UnsupportedOperationException();
- }
-
- public SSLSessionContext getSessionContext() {
- throw new UnsupportedOperationException();
- }
-
- public Object getValue(String name) {
- throw new UnsupportedOperationException();
- }
-
- public String[] getValueNames() {
- throw new UnsupportedOperationException();
- }
-
- public void invalidate() {
- throw new UnsupportedOperationException();
- }
-
- public boolean isValid() {
- throw new UnsupportedOperationException();
- }
-
- public void putValue(String name, Object value) {
- throw new UnsupportedOperationException();
- }
-
- public void removeValue(String name) {
- throw new UnsupportedOperationException();
- }
-}
diff --git a/x-net/src/test/impl/java.injected/org/apache/harmony/xnet/provider/jsse/FileClientSessionCacheTest.java b/x-net/src/test/impl/java.injected/org/apache/harmony/xnet/provider/jsse/FileClientSessionCacheTest.java
deleted file mode 100644
index ee50863..0000000
--- a/x-net/src/test/impl/java.injected/org/apache/harmony/xnet/provider/jsse/FileClientSessionCacheTest.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import junit.framework.TestCase;
-
-import java.io.File;
-import java.io.IOException;
-
-public class FileClientSessionCacheTest extends TestCase {
-
- public void testMaxSize() throws IOException, InterruptedException {
- String tmpDir = System.getProperty("java.io.tmpdir");
- if (tmpDir == null) {
- fail("Please set 'java.io.tmpdir' system property.");
- }
- File cacheDir = new File(tmpDir
- + "/" + FileClientSessionCacheTest.class.getName() + "/cache");
- final SSLClientSessionCache cache
- = FileClientSessionCache.usingDirectory(cacheDir);
- Thread[] threads = new Thread[10];
- final int iterations = FileClientSessionCache.MAX_SIZE * 10;
- for (int i = 0; i < threads.length; i++) {
- final int id = i;
- threads[i] = new Thread() {
- @Override
- public void run() {
- for (int i = 0; i < iterations; i++) {
- cache.putSessionData(new FakeSession(id + "." + i),
- new byte[10]);
- }
- }
- };
- }
- for (int i = 0; i < threads.length; i++) {
- threads[i].start();
- }
- for (int i = 0; i < threads.length; i++) {
- threads[i].join();
- }
- assertEquals(FileClientSessionCache.MAX_SIZE, cacheDir.list().length);
- }
-}
diff --git a/x-net/src/test/java/tests/api/javax/net/AllTests.java b/x-net/src/test/java/tests/api/javax/net/AllTests.java
deleted file mode 100644
index 35cd6f5..0000000
--- a/x-net/src/test/java/tests/api/javax/net/AllTests.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package tests.api.javax.net;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-/**
- * This is autogenerated source file. Includes tests for package tests.api.javax.net;
- */
-
-public class AllTests {
- public static Test suite() {
- TestSuite suite = new TestSuite("All tests for package tests.api.javax.net;");
- // $JUnit-BEGIN$
-
- suite.addTestSuite(ServerSocketFactoryTest.class);
- suite.addTestSuite(SocketFactoryTest.class);
-
- // $JUnit-END$
- return suite;
- }
-}
diff --git a/x-net/src/test/java/tests/api/javax/net/ServerSocketFactoryTest.java b/x-net/src/test/java/tests/api/javax/net/ServerSocketFactoryTest.java
deleted file mode 100644
index 1876f22..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ServerSocketFactoryTest.java
+++ /dev/null
@@ -1,251 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**
-* @author Boris V. Kuznetsov
-* @version $Revision$
-*/
-
-package tests.api.javax.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.ServerSocket;
-import java.net.SocketException;
-import javax.net.ServerSocketFactory;
-
-import junit.framework.TestCase;
-
-import tests.support.Support_PortManager;
-
-
-/**
- * Tests for <code>ServerSocketFactory</code> class constructors and methods.
- */
-@TestTargetClass(ServerSocketFactory.class)
-public class ServerSocketFactoryTest extends TestCase {
-
- /**
- * @tests javax.net.SocketFactory#SocketFactory()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ServerSocketFactory",
- args = {}
- )
- public void test_Constructor() {
- try {
- ServerSocketFactory sf = new MyServerSocketFactory();
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- /**
- * @tests javax.net.ServerSocketFactory#createServerSocket()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "IOException checking missed",
- method = "createServerSocket",
- args = {}
- )
- public final void test_createServerSocket_01() {
- ServerSocketFactory sf = ServerSocketFactory.getDefault();
- try {
- ServerSocket ss = sf.createServerSocket();
- assertNotNull(ss);
- } catch (SocketException e) {
- } catch (Exception e) {
- fail(e.toString());
- }
- }
-
- /**
- * @tests javax.net.ServerSocketFactory#createServerSocket(int port)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "createServerSocket",
- args = {int.class}
- )
- public final void test_createServerSocket_02() {
- ServerSocketFactory sf = ServerSocketFactory.getDefault();
- int portNumber = Support_PortManager.getNextPort();
-
- try {
- ServerSocket ss = sf.createServerSocket(portNumber);
- assertNotNull(ss);
- } catch (Exception ex) {
- fail("Unexpected exception: " + ex);
- }
-
- try {
- sf.createServerSocket(portNumber);
- fail("IOException wasn't thrown");
- } catch (IOException ioe) {
- //expected
- } catch (Exception ex) {
- fail(ex + " was thrown instead of IOException");
- }
-
- try {
- sf.createServerSocket(-1);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException ioe) {
- //expected
- } catch (Exception ex) {
- fail(ex + " was thrown instead of IllegalArgumentException");
- }
- }
-
- /**
- * @tests javax.net.ServerSocketFactory#createServerSocket(int port, int backlog)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "createServerSocket",
- args = {int.class, int.class}
- )
- public final void test_createServerSocket_03() {
- ServerSocketFactory sf = ServerSocketFactory.getDefault();
- int portNumber = Support_PortManager.getNextPort();
-
- try {
- ServerSocket ss = sf.createServerSocket(portNumber, 0);
- assertNotNull(ss);
- } catch (Exception ex) {
- fail("Unexpected exception: " + ex);
- }
-
- try {
- sf.createServerSocket(portNumber, 0);
- fail("IOException wasn't thrown");
- } catch (IOException ioe) {
- //expected
- } catch (Exception ex) {
- fail(ex + " was thrown instead of IOException");
- }
-
- try {
- sf.createServerSocket(65536, 0);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException ioe) {
- //expected
- } catch (Exception ex) {
- fail(ex + " was thrown instead of IllegalArgumentException");
- }
- }
-
- /**
- * @tests javax.net.ServerSocketFactory#createServerSocket(int port, int backlog, InetAddress ifAddress)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "createServerSocket",
- args = {int.class, int.class, InetAddress.class}
- )
- public final void test_createServerSocket_04() {
- ServerSocketFactory sf = ServerSocketFactory.getDefault();
- int portNumber = Support_PortManager.getNextPort();
-
- try {
- ServerSocket ss = sf.createServerSocket(portNumber, 0, InetAddress.getLocalHost());
- assertNotNull(ss);
- } catch (Exception ex) {
- fail("Unexpected exception: " + ex);
- }
-
- try {
- sf.createServerSocket(portNumber, 0, InetAddress.getLocalHost());
- fail("IOException wasn't thrown");
- } catch (IOException ioe) {
- //expected
- } catch (Exception ex) {
- fail(ex + " was thrown instead of IOException");
- }
-
- try {
- sf.createServerSocket(Integer.MAX_VALUE, 0, InetAddress.getLocalHost());
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException ioe) {
- //expected
- } catch (Exception ex) {
- fail(ex + " was thrown instead of IllegalArgumentException");
- }
- }
-
- /**
- * @tests javax.net.ServerSocketFactory#getDefault()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDefault",
- args = {}
- )
- public final void test_getDefault() {
- ServerSocketFactory sf = ServerSocketFactory.getDefault();
- ServerSocket s;
- try {
- s = sf.createServerSocket(0);
- s.close();
- } catch (IOException e) {
- }
- try {
- s = sf.createServerSocket(0, 50);
- s.close();
- } catch (IOException e) {
- }
- try {
- s = sf.createServerSocket(0, 50, InetAddress.getLocalHost());
- s.close();
- } catch (IOException e) {
- }
- }
-}
-class MyServerSocketFactory extends ServerSocketFactory {
-
- public MyServerSocketFactory() {
- super();
- }
-
- @Override
- public ServerSocket createServerSocket(int port) throws IOException {
- return null;
- }
-
- @Override
- public ServerSocket createServerSocket(int port, int backlog)
- throws IOException {
- return null;
- }
-
- @Override
- public ServerSocket createServerSocket(int port, int backlog,
- InetAddress address) throws IOException {
- return null;
- }
-} \ No newline at end of file
diff --git a/x-net/src/test/java/tests/api/javax/net/SocketFactoryTest.java b/x-net/src/test/java/tests/api/javax/net/SocketFactoryTest.java
deleted file mode 100644
index 05fee79..0000000
--- a/x-net/src/test/java/tests/api/javax/net/SocketFactoryTest.java
+++ /dev/null
@@ -1,408 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**
-* @author Boris V. Kuznetsov
-* @version $Revision$
-*/
-
-package tests.api.javax.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.net.SocketException;
-import java.net.UnknownHostException;
-
-import javax.net.SocketFactory;
-
-import junit.framework.TestCase;
-
-import tests.support.Support_PortManager;
-
-
-/**
- * Tests for <code>SocketFactory</code> class methods.
- */
-@TestTargetClass(SocketFactory.class)
-public class SocketFactoryTest extends TestCase {
-
- /**
- * @tests javax.net.SocketFactory#SocketFactory()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SocketFactory",
- args = {}
- )
- public void test_Constructor() {
- try {
- MySocketFactory sf = new MySocketFactory();
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- /**
- * @tests javax.net.SocketFactory#createSocket()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "IOException check missed",
- method = "createSocket",
- args = {}
- )
- public final void test_createSocket_01() {
- SocketFactory sf = SocketFactory.getDefault();
-
- try {
- Socket s = sf.createSocket();
- assertNotNull(s);
- assertEquals(-1, s.getLocalPort());
- assertEquals(0, s.getPort());
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
-
- MySocketFactory msf = new MySocketFactory();
- try {
- msf.createSocket();
- fail("No expected SocketException");
- } catch (SocketException e) {
- } catch (IOException e) {
- fail(e.toString());
- }
- }
-
- /**
- * @tests javax.net.SocketFactory#createSocket(String host, int port)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "createSocket",
- args = {String.class, int.class}
- )
- public final void test_createSocket_02() {
- SocketFactory sf = SocketFactory.getDefault();
- int portNumber = Support_PortManager.getNextPort();
- int sport = startServer("Cons String,I");
- int[] invalidPorts = {Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE};
-
- try {
- Socket s = sf.createSocket(InetAddress.getLocalHost().getHostName(), sport);
- assertNotNull(s);
- assertTrue("Failed to create socket", s.getPort() == sport);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
-
- try {
- Socket s = sf.createSocket("bla-bla", sport);
- fail("UnknownHostException wasn't thrown");
- } catch (UnknownHostException uhe) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of UnknownHostException");
- }
-
- for (int i = 0; i < invalidPorts.length; i++) {
- try {
- Socket s = sf.createSocket(InetAddress.getLocalHost().getHostName(), invalidPorts[i]);
- fail("IllegalArgumentException wasn't thrown for " + invalidPorts[i]);
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException for " + invalidPorts[i]);
- }
- }
-
- try {
- Socket s = sf.createSocket(InetAddress.getLocalHost().getHostName(), portNumber);
- fail("IOException wasn't thrown");
- } catch (IOException ioe) {
- //expected
- }
-
- SocketFactory f = SocketFactory.getDefault();
- try {
- Socket s = f.createSocket("localhost", 8082);
- fail("IOException wasn't thrown ...");
- } catch (IOException e) {
- }
- }
-
- /**
- * @tests javax.net.SocketFactory#createSocket(InetAddress host, int port)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "createSocket",
- args = {InetAddress.class, int.class}
- )
- public final void test_createSocket_03() {
- SocketFactory sf = SocketFactory.getDefault();
- int portNumber = Support_PortManager.getNextPort();
- int sport = startServer("Cons InetAddress,I");
- int[] invalidPorts = {Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE};
-
- try {
- Socket s = sf.createSocket(InetAddress.getLocalHost(), sport);
- assertNotNull(s);
- assertTrue("Failed to create socket", s.getPort() == sport);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
-
- for (int i = 0; i < invalidPorts.length; i++) {
- try {
- Socket s = sf.createSocket(InetAddress.getLocalHost(), invalidPorts[i]);
- fail("IllegalArgumentException wasn't thrown for " + invalidPorts[i]);
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException for " + invalidPorts[i]);
- }
- }
-
- try {
- Socket s = sf.createSocket(InetAddress.getLocalHost(), portNumber);
- fail("IOException wasn't thrown");
- } catch (IOException ioe) {
- //expected
- }
-
- SocketFactory f = SocketFactory.getDefault();
- try {
- Socket s = f.createSocket(InetAddress.getLocalHost(), 8081);
- fail("IOException wasn't thrown ...");
- } catch (IOException e) {
- }
- }
-
- /**
- * @tests javax.net.SocketFactory#createSocket(InetAddress address, int port,
- * InetAddress localAddress, int localPort)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "createSocket",
- args = {InetAddress.class, int.class, InetAddress.class, int.class}
- )
- public final void test_createSocket_04() {
- SocketFactory sf = SocketFactory.getDefault();
- int portNumber = Support_PortManager.getNextPort();
- int sport = startServer("Cons InetAddress,I,InetAddress,I");
- int[] invalidPorts = {Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE};
-
- try {
- Socket s = sf.createSocket(InetAddress.getLocalHost(), sport,
- InetAddress.getLocalHost(), portNumber);
- assertNotNull(s);
- assertTrue("1: Failed to create socket", s.getPort() == sport);
- assertTrue("2: Failed to create socket", s.getLocalPort() == portNumber);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
-
- for (int i = 0; i < invalidPorts.length; i++) {
- try {
- Socket s = sf.createSocket(InetAddress.getLocalHost(), invalidPorts[i],
- InetAddress.getLocalHost(), portNumber);
- fail("IllegalArgumentException wasn't thrown for " + invalidPorts[i]);
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException for " + invalidPorts[i]);
- }
-
- try {
- Socket s = sf.createSocket(InetAddress.getLocalHost(), sport,
- InetAddress.getLocalHost(), invalidPorts[i]);
- fail("IllegalArgumentException wasn't thrown for " + invalidPorts[i]);
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException for " + invalidPorts[i]);
- }
- }
-
- try {
- Socket s = sf.createSocket(InetAddress.getLocalHost(), sport,
- InetAddress.getLocalHost(), portNumber);
- fail("IOException wasn't thrown");
- } catch (IOException ioe) {
- //expected
- }
-
- SocketFactory f = SocketFactory.getDefault();
- try {
- Socket s = f.createSocket(InetAddress.getLocalHost(), 8081, InetAddress.getLocalHost(), 8082);
- fail("IOException wasn't thrown ...");
- } catch (IOException e) {
- }
- }
-
- /**
- * @tests javax.net.SocketFactory#createSocket(String host, int port,
- * InetAddress localHost, int localPort)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "createSocket",
- args = {String.class, int.class, InetAddress.class, int.class}
- )
- public final void test_createSocket_05() {
- SocketFactory sf = SocketFactory.getDefault();
- int portNumber = Support_PortManager.getNextPort();
- int sport = startServer("Cons String,I,InetAddress,I");
- int[] invalidPorts = {Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE};
-
- try {
- Socket s = sf.createSocket(InetAddress.getLocalHost().getHostName(), sport,
- InetAddress.getLocalHost(), portNumber);
- assertNotNull(s);
- assertTrue("1: Failed to create socket", s.getPort() == sport);
- assertTrue("2: Failed to create socket", s.getLocalPort() == portNumber);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
-
- portNumber = Support_PortManager.getNextPort();
- try {
- Socket s = sf.createSocket("bla-bla", sport, InetAddress.getLocalHost(), portNumber);
- fail("UnknownHostException wasn't thrown");
- } catch (UnknownHostException uhe) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of UnknownHostException");
- }
-
- for (int i = 0; i < invalidPorts.length; i++) {
- portNumber = Support_PortManager.getNextPort();
- try {
- Socket s = sf.createSocket(InetAddress.getLocalHost().getHostName(), invalidPorts[i],
- InetAddress.getLocalHost(), portNumber);
- fail("IllegalArgumentException wasn't thrown for " + invalidPorts[i]);
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException for " + invalidPorts[i]);
- }
- try {
- Socket s = sf.createSocket(InetAddress.getLocalHost().getHostName(), sport,
- InetAddress.getLocalHost(), invalidPorts[i]);
- fail("IllegalArgumentException wasn't thrown for " + invalidPorts[i]);
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException for " + invalidPorts[i]);
- }
- }
-
- SocketFactory f = SocketFactory.getDefault();
- try {
- Socket s = f.createSocket("localhost", 8081, InetAddress.getLocalHost(), 8082);
- fail("IOException wasn't thrown ...");
- } catch (IOException e) {
- }
- }
-
- /**
- * @tests javax.net.SocketFactory#getDefault()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDefault",
- args = {}
- )
- public final void test_getDefault() {
- SocketFactory sf = SocketFactory.getDefault();
- Socket s;
- try {
- s = sf.createSocket("localhost", 8082);
- s.close();
- } catch (IOException e) {
- }
- try {
- s = sf.createSocket("localhost", 8081, InetAddress.getLocalHost(), 8082);
- s.close();
- } catch (IOException e) {
- }
- try {
- s = sf.createSocket(InetAddress.getLocalHost(), 8081);
- s.close();
- } catch (IOException e) {
- }
- try {
- s = sf.createSocket(InetAddress.getLocalHost(), 8081, InetAddress.getLocalHost(), 8082);
- s.close();
- } catch (IOException e) {
- }
- }
-
- protected int startServer(String name) {
- int portNumber = Support_PortManager.getNextPort();
- ServerSocket ss = null;
- try {
- ss = new ServerSocket(portNumber);
- } catch (IOException e) {
- fail(name + ": " + e);
- }
- return ss.getLocalPort();
- }
-}
-
-class MySocketFactory extends SocketFactory {
-
- public MySocketFactory() {
- super();
- }
-
- @Override
- public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
- return null;
- }
-
- @Override
- public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
- throws IOException, UnknownHostException {
- return null;
- }
-
- @Override
- public Socket createSocket(InetAddress host, int port) throws IOException {
- return null;
- }
-
- @Override
- public Socket createSocket(InetAddress address, int port,
- InetAddress localAddress, int localPort) throws IOException {
- return null;
- }
-
-}
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/AllTests.java b/x-net/src/test/java/tests/api/javax/net/ssl/AllTests.java
deleted file mode 100644
index 5f9c32d..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/AllTests.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package tests.api.javax.net.ssl;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-/**
- * This is autogenerated source file. Includes tests for package tests.api.javax.net.ssl;
- */
-
-public class AllTests {
- public static Test suite() {
- TestSuite suite = new TestSuite("All tests for package tests.api.javax.net.ssl;");
- // $JUnit-BEGIN$
-
- suite.addTestSuite(CertPathTrustManagerParametersTest.class);
- suite.addTestSuite(HandshakeCompletedEventTest.class);
- suite.addTestSuite(HttpsURLConnectionTest.class);
- suite.addTestSuite(KeyManagerFactory1Test.class);
- suite.addTestSuite(KeyManagerFactory2Test.class);
- suite.addTestSuite(KeyManagerFactorySpiTest.class);
- suite.addTestSuite(SSLContext1Test.class);
- suite.addTestSuite(SSLContext2Test.class);
- suite.addTestSuite(SSLContextSpiTest.class);
- suite.addTestSuite(SSLEngineResultTest.class);
- suite.addTestSuite(SSLEngineTest.class);
- suite.addTestSuite(SSLPermissionTest.class);
- suite.addTestSuite(SSLServerSocketFactoryTest.class);
- suite.addTestSuite(SSLSessionBindingEventTest.class);
- suite.addTestSuite(SSLSocketFactoryTest.class);
- suite.addTestSuite(TrustManagerFactory1Test.class);
- suite.addTestSuite(TrustManagerFactory2Test.class);
- suite.addTestSuite(TrustManagerFactorySpiTest.class);
- suite.addTestSuite(X509ExtendedKeyManagerTest.class);
- suite.addTestSuite(SSLSocketTest.class);
- suite.addTestSuite(SSLServerSocketTest.class);
- suite.addTestSuite(SSLProtocolExceptionTest.class);
- suite.addTestSuite(SSLPeerUnverifiedExceptionTest.class);
- suite.addTestSuite(SSLKeyExceptionTest.class);
- suite.addTestSuite(SSLHandshakeExceptionTest.class);
- suite.addTestSuite(SSLExceptionTest.class);
- suite.addTestSuite(SSLEngineResultStatusTest.class);
- suite.addTestSuite(SSLEngineResultHandshakeStatusTest.class);
- suite.addTestSuite(SSLEngineResultTest.class);
- suite.addTestSuite(KeyStoreBuilderParametersTest.class);
- suite.addTestSuite(SSLSessionContextTest.class);
- suite.addTestSuite(X509TrustManagerTest.class);
- suite.addTestSuite(X509KeyManagerTest.class);
- suite.addTestSuite(SSLSessionTest.class);
- suite.addTestSuite(SSLSessionBindingListenerTest.class);
- suite.addTestSuite(HostnameVerifierTest.class);
-
- // $JUnit-END$
- return suite;
- }
-}
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/CertPathTrustManagerParametersTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/CertPathTrustManagerParametersTest.java
deleted file mode 100644
index 45c8d73..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/CertPathTrustManagerParametersTest.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.security.cert.CertPathParameters;
-import javax.net.ssl.CertPathTrustManagerParameters;
-
-import junit.framework.TestCase;
-
-/**
- * Tests for <code>CertPathTrustManagerParameters</code> class constructors
- * and methods.
- *
- */
-@TestTargetClass(CertPathTrustManagerParameters.class)
-public class CertPathTrustManagerParametersTest extends TestCase {
-
- /**
- * @tests javax.net.ssl.CertPathTrustManagerParameters#
- * CertPathTrustManagerParameters(java.security.cert.CertPathParameters)
- * Case 1: Try to construct object.
- * Case 2: Check NullPointerException.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "CertPathTrustManagerParameters",
- args = {java.security.cert.CertPathParameters.class}
- )
- public void test_ConstructorLjava_security_cert_CertPathParameters() {
- // case 1: Try to construct object.
- try {
- CertPathParameters parameters = new MyCertPathParameters();
- CertPathTrustManagerParameters p =
- new CertPathTrustManagerParameters(parameters);
- assertNotSame("Parameters were cloned incorrectly",
- parameters, p.getParameters());
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
-
- // case 2: Check NullPointerException.
- try {
- new CertPathTrustManagerParameters(null);
- fail("Expected CertPathTrustManagerParameters was not thrown");
- } catch (NullPointerException npe) {
- // expected
- }
- }
-
- /**
- * @tests javax.net.ssl.CertPathTrustManagerParameters#getParameters()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getParameters",
- args = {}
- )
- public void test_getParameters() {
- CertPathParameters parameters = new MyCertPathParameters();
- CertPathTrustManagerParameters p = new CertPathTrustManagerParameters(
- parameters);
- if (!(p.getParameters() instanceof MyCertPathParameters)) {
- fail("incorrect parameters");
- }
- assertNotSame("Parameters were cloned incorrectly",
- parameters, p.getParameters());
- }
-}
-
-class MyCertPathParameters implements CertPathParameters {
- public Object clone() {
- return new MyCertPathParameters();
- }
-}
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/CertificatesToPlayWith.java b/x-net/src/test/java/tests/api/javax/net/ssl/CertificatesToPlayWith.java
deleted file mode 100644
index 04a17b2..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/CertificatesToPlayWith.java
+++ /dev/null
@@ -1,478 +0,0 @@
-/*
- * $HeadURL$
- * $Revision$
- * $Date$
- *
- * ====================================================================
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
- *
- */
-
-package tests.api.javax.net.ssl;
-
-/**
- * Some X509 certificates to test against.
- * <p/>
- * Note: some of these certificates have Japanese Kanji in the "subjectAlt"
- * field (UTF8). Not sure how realistic that is since international characters
- * in DNS names usually get translated into ASCII using "xn--" style DNS
- * entries. "xn--i8s592g.co.jp" is what FireFox actually uses when trying to
- * find &#x82b1;&#x5b50;.co.jp. So would the CN in the certificate contain
- * "xn--i8s592g.co.jp" in ASCII, or "&#x82b1;&#x5b50;.co.jp" in UTF8? (Both?)
- *
- * @since 11-Dec-2006
- */
-public interface CertificatesToPlayWith {
-
- /**
- * CN=foo.com
- */
- public final static byte[] X509_FOO = (
- "-----BEGIN CERTIFICATE-----\n" +
- "MIIERjCCAy6gAwIBAgIJAIz+EYMBU6aQMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
- "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
- "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
- "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
- "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzE0MVoXDTI4MTEwNTE1MzE0MVowgaQx\n" +
- "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
- "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
- "cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs\n" +
- "aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" +
- "ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" +
- "lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" +
- "zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" +
- "07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" +
- "BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" +
- "JTxpTKqym93whYk93l3ocEe55c0CAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgB\n" +
- "hvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYE\n" +
- "FJ8Ud78/OrbKOIJCSBYs2tDLXofYMB8GA1UdIwQYMBaAFHua2o+QmU5S0qzbswNS\n" +
- "yoemDT4NMA0GCSqGSIb3DQEBBQUAA4IBAQC3jRmEya6sQCkmieULcvx8zz1euCk9\n" +
- "fSez7BEtki8+dmfMXe3K7sH0lI8f4jJR0rbSCjpmCQLYmzC3NxBKeJOW0RcjNBpO\n" +
- "c2JlGO9auXv2GDP4IYiXElLJ6VSqc8WvDikv0JmCCWm0Zga+bZbR/EWN5DeEtFdF\n" +
- "815CLpJZNcYwiYwGy/CVQ7w2TnXlG+mraZOz+owr+cL6J/ZesbdEWfjoS1+cUEhE\n" +
- "HwlNrAu8jlZ2UqSgskSWlhYdMTAP9CPHiUv9N7FcT58Itv/I4fKREINQYjDpvQcx\n" +
- "SaTYb9dr5sB4WLNglk7zxDtM80H518VvihTcP7FHL+Gn6g4j5fkI98+S\n" +
- "-----END CERTIFICATE-----\n").getBytes();
-
- /**
- * CN=&#x82b1;&#x5b50;.co.jp
- */
- public final static byte[] X509_HANAKO = (
- "-----BEGIN CERTIFICATE-----\n" +
- "MIIESzCCAzOgAwIBAgIJAIz+EYMBU6aTMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
- "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
- "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
- "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
- "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1NDIxNVoXDTI4MTEwNTE1NDIxNVowgakx\n" +
- "CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0\n" +
- "IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl\n" +
- "cnRpZmljYXRlczEVMBMGA1UEAwwM6Iqx5a2QLmNvLmpwMSUwIwYJKoZIhvcNAQkB\n" +
- "FhZqdWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A\n" +
- "MIIBCgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjU\n" +
- "g4pNjYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQc\n" +
- "wHf0ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t\n" +
- "7iu1JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAn\n" +
- "AxK6q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArD\n" +
- "qUYxqJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwG\n" +
- "CWCGSAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNV\n" +
- "HQ4EFgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLS\n" +
- "rNuzA1LKh6YNPg0wDQYJKoZIhvcNAQEFBQADggEBALJ27i3okV/KvlDp6KMID3gd\n" +
- "ITl68PyItzzx+SquF8gahMh016NX73z/oVZoVUNdftla8wPUB1GwIkAnGkhQ9LHK\n" +
- "spBdbRiCj0gMmLCsX8SrjFvr7cYb2cK6J/fJe92l1tg/7Y4o7V/s4JBe/cy9U9w8\n" +
- "a0ctuDmEBCgC784JMDtT67klRfr/2LlqWhlOEq7pUFxRLbhpquaAHSOjmIcWnVpw\n" +
- "9BsO7qe46hidgn39hKh1WjKK2VcL/3YRsC4wUi0PBtFW6ScMCuMhgIRXSPU55Rae\n" +
- "UIlOdPjjr1SUNWGId1rD7W16Scpwnknn310FNxFMHVI0GTGFkNdkilNCFJcIoRA=\n" +
- "-----END CERTIFICATE-----\n").getBytes();
-
- /**
- * CN=foo.com, subjectAlt=bar.com
- */
- public final static byte[] X509_FOO_BAR = (
- "-----BEGIN CERTIFICATE-----\n" +
- "MIIEXDCCA0SgAwIBAgIJAIz+EYMBU6aRMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
- "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
- "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
- "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
- "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzYyOVoXDTI4MTEwNTE1MzYyOVowgaQx\n" +
- "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
- "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
- "cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs\n" +
- "aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" +
- "ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" +
- "lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" +
- "zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" +
- "07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" +
- "BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" +
- "JTxpTKqym93whYk93l3ocEe55c0CAwEAAaOBkDCBjTAJBgNVHRMEAjAAMCwGCWCG\n" +
- "SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E\n" +
- "FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz\n" +
- "A1LKh6YNPg0wEgYDVR0RBAswCYIHYmFyLmNvbTANBgkqhkiG9w0BAQUFAAOCAQEA\n" +
- "dQyprNZBmVnvuVWjV42sey/PTfkYShJwy1j0/jcFZR/ypZUovpiHGDO1DgL3Y3IP\n" +
- "zVQ26uhUsSw6G0gGRiaBDe/0LUclXZoJzXX1qpS55OadxW73brziS0sxRgGrZE/d\n" +
- "3g5kkio6IED47OP6wYnlmZ7EKP9cqjWwlnvHnnUcZ2SscoLNYs9rN9ccp8tuq2by\n" +
- "88OyhKwGjJfhOudqfTNZcDzRHx4Fzm7UsVaycVw4uDmhEHJrAsmMPpj/+XRK9/42\n" +
- "2xq+8bc6HojdtbCyug/fvBZvZqQXSmU8m8IVcMmWMz0ZQO8ee3QkBHMZfCy7P/kr\n" +
- "VbWx/uETImUu+NZg22ewEw==\n" +
- "-----END CERTIFICATE-----\n").getBytes();
-
- /**
- * CN=foo.com, subjectAlt=bar.com, subjectAlt=&#x82b1;&#x5b50;.co.jp
- * (hanako.co.jp in kanji)
- */
- public final static byte[] X509_FOO_BAR_HANAKO = (
- "-----BEGIN CERTIFICATE-----\n" +
- "MIIEajCCA1KgAwIBAgIJAIz+EYMBU6aSMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
- "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
- "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
- "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
- "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzgxM1oXDTI4MTEwNTE1MzgxM1owgaQx\n" +
- "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
- "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
- "cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs\n" +
- "aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" +
- "ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" +
- "lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" +
- "zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" +
- "07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" +
- "BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" +
- "JTxpTKqym93whYk93l3ocEe55c0CAwEAAaOBnjCBmzAJBgNVHRMEAjAAMCwGCWCG\n" +
- "SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E\n" +
- "FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz\n" +
- "A1LKh6YNPg0wIAYDVR0RBBkwF4IHYmFyLmNvbYIM6Iqx5a2QLmNvLmpwMA0GCSqG\n" +
- "SIb3DQEBBQUAA4IBAQBeZs7ZIYyKtdnVxVvdLgwySEPOE4pBSXii7XYv0Q9QUvG/\n" +
- "++gFGQh89HhABzA1mVUjH5dJTQqSLFvRfqTHqLpxSxSWqMHnvRM4cPBkIRp/XlMK\n" +
- "PlXadYtJLPTgpbgvulA1ickC9EwlNYWnowZ4uxnfsMghW4HskBqaV+PnQ8Zvy3L0\n" +
- "12c7Cg4mKKS5pb1HdRuiD2opZ+Hc77gRQLvtWNS8jQvd/iTbh6fuvTKfAOFoXw22\n" +
- "sWIKHYrmhCIRshUNohGXv50m2o+1w9oWmQ6Dkq7lCjfXfUB4wIbggJjpyEtbNqBt\n" +
- "j4MC2x5rfsLKKqToKmNE7pFEgqwe8//Aar1b+Qj+\n" +
- "-----END CERTIFICATE-----\n").getBytes();
-
- /**
- * CN=*.foo.com
- */
- public final static byte[] X509_WILD_FOO = (
- "-----BEGIN CERTIFICATE-----\n" +
- "MIIESDCCAzCgAwIBAgIJAIz+EYMBU6aUMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
- "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
- "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
- "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
- "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTU1NVoXDTI4MTEwNTE2MTU1NVowgaYx\n" +
- "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
- "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
- "cnRpZmljYXRlczESMBAGA1UEAxQJKi5mb28uY29tMSUwIwYJKoZIhvcNAQkBFhZq\n" +
- "dWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
- "CgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pN\n" +
- "jYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0\n" +
- "ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1\n" +
- "JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6\n" +
- "q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYx\n" +
- "qJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwGCWCG\n" +
- "SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E\n" +
- "FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz\n" +
- "A1LKh6YNPg0wDQYJKoZIhvcNAQEFBQADggEBAH0ipG6J561UKUfgkeW7GvYwW98B\n" +
- "N1ZooWX+JEEZK7+Pf/96d3Ij0rw9ACfN4bpfnCq0VUNZVSYB+GthQ2zYuz7tf/UY\n" +
- "A6nxVgR/IjG69BmsBl92uFO7JTNtHztuiPqBn59pt+vNx4yPvno7zmxsfI7jv0ww\n" +
- "yfs+0FNm7FwdsC1k47GBSOaGw38kuIVWqXSAbL4EX9GkryGGOKGNh0qvAENCdRSB\n" +
- "G9Z6tyMbmfRY+dLSh3a9JwoEcBUso6EWYBakLbq4nG/nvYdYvG9ehrnLVwZFL82e\n" +
- "l3Q/RK95bnA6cuRClGusLad0e6bjkBzx/VQ3VarDEpAkTLUGVAa0CLXtnyc=\n" +
- "-----END CERTIFICATE-----\n").getBytes();
-
- /**
- * CN=*.co.jp
- */
- public final static byte[] X509_WILD_CO_JP = (
- "-----BEGIN CERTIFICATE-----\n" +
- "MIIERjCCAy6gAwIBAgIJAIz+EYMBU6aVMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
- "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
- "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
- "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
- "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTYzMFoXDTI4MTEwNTE2MTYzMFowgaQx\n" +
- "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
- "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
- "cnRpZmljYXRlczEQMA4GA1UEAxQHKi5jby5qcDElMCMGCSqGSIb3DQEJARYWanVs\n" +
- "aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" +
- "ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" +
- "lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" +
- "zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" +
- "07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" +
- "BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" +
- "JTxpTKqym93whYk93l3ocEe55c0CAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgB\n" +
- "hvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYE\n" +
- "FJ8Ud78/OrbKOIJCSBYs2tDLXofYMB8GA1UdIwQYMBaAFHua2o+QmU5S0qzbswNS\n" +
- "yoemDT4NMA0GCSqGSIb3DQEBBQUAA4IBAQA0sWglVlMx2zNGvUqFC73XtREwii53\n" +
- "CfMM6mtf2+f3k/d8KXhLNySrg8RRlN11zgmpPaLtbdTLrmG4UdAHHYr8O4y2BBmE\n" +
- "1cxNfGxxechgF8HX10QV4dkyzp6Z1cfwvCeMrT5G/V1pejago0ayXx+GPLbWlNeZ\n" +
- "S+Kl0m3p+QplXujtwG5fYcIpaGpiYraBLx3Tadih39QN65CnAh/zRDhLCUzKyt9l\n" +
- "UGPLEUDzRHMPHLnSqT1n5UU5UDRytbjJPXzF+l/+WZIsanefWLsxnkgAuZe/oMMF\n" +
- "EJMryEzOjg4Tfuc5qM0EXoPcQ/JlheaxZ40p2IyHqbsWV4MRYuFH4bkM\n" +
- "-----END CERTIFICATE-----\n").getBytes();
-
- /**
- * CN=*.foo.com, subjectAlt=*.bar.com, subjectAlt=*.&#x82b1;&#x5b50;.co.jp
- * (*.hanako.co.jp in kanji)
- */
- public final static byte[] X509_WILD_FOO_BAR_HANAKO = (
- "-----BEGIN CERTIFICATE-----\n" +
- "MIIEcDCCA1igAwIBAgIJAIz+EYMBU6aWMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
- "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
- "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
- "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
- "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTczMVoXDTI4MTEwNTE2MTczMVowgaYx\n" +
- "CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
- "IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
- "cnRpZmljYXRlczESMBAGA1UEAxQJKi5mb28uY29tMSUwIwYJKoZIhvcNAQkBFhZq\n" +
- "dWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
- "CgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pN\n" +
- "jYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0\n" +
- "ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1\n" +
- "JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6\n" +
- "q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYx\n" +
- "qJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo4GiMIGfMAkGA1UdEwQCMAAwLAYJ\n" +
- "YIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0GA1Ud\n" +
- "DgQWBBSfFHe/Pzq2yjiCQkgWLNrQy16H2DAfBgNVHSMEGDAWgBR7mtqPkJlOUtKs\n" +
- "27MDUsqHpg0+DTAkBgNVHREEHTAbggkqLmJhci5jb22CDiou6Iqx5a2QLmNvLmpw\n" +
- "MA0GCSqGSIb3DQEBBQUAA4IBAQBobWC+D5/lx6YhX64CwZ26XLjxaE0S415ajbBq\n" +
- "DK7lz+Rg7zOE3GsTAMi+ldUYnhyz0wDiXB8UwKXl0SDToB2Z4GOgqQjAqoMmrP0u\n" +
- "WB6Y6dpkfd1qDRUzI120zPYgSdsXjHW9q2H77iV238hqIU7qCvEz+lfqqWEY504z\n" +
- "hYNlknbUnR525ItosEVwXFBJTkZ3Yw8gg02c19yi8TAh5Li3Ad8XQmmSJMWBV4XK\n" +
- "qFr0AIZKBlg6NZZFf/0dP9zcKhzSriW27bY0XfzA6GSiRDXrDjgXq6baRT6YwgIg\n" +
- "pgJsDbJtZfHnV1nd3M6zOtQPm1TIQpNmMMMd/DPrGcUQerD3\n" +
- "-----END CERTIFICATE-----\n").getBytes();
-
- /**
- * CN=foo.com, CN=bar.com, CN=&#x82b1;&#x5b50;.co.jp
- */
- public final static byte[] X509_THREE_CNS_FOO_BAR_HANAKO = (
- "-----BEGIN CERTIFICATE-----\n" +
- "MIIEbzCCA1egAwIBAgIJAIz+EYMBU6aXMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
- "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
- "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
- "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
- "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTk0NVoXDTI4MTEwNTE2MTk0NVowgc0x\n" +
- "CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0\n" +
- "IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl\n" +
- "cnRpZmljYXRlczEQMA4GA1UEAwwHZm9vLmNvbTEQMA4GA1UEAwwHYmFyLmNvbTEV\n" +
- "MBMGA1UEAwwM6Iqx5a2QLmNvLmpwMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
- "ZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyGOv\n" +
- "loI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pNjYGViGjg7zhf\n" +
- "bjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0ZHLN6sD9m2uV\n" +
- "Sp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1JVjTuE0pcBva\n" +
- "h2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6q/wGqcZ3zvFB\n" +
- "TcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYxqJUlPGlMqrKb\n" +
- "3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQf\n" +
- "Fh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUnxR3vz86\n" +
- "tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuzA1LKh6YNPg0w\n" +
- "DQYJKoZIhvcNAQEFBQADggEBAGuZb8ai1NO2j4v3y9TLZvd5s0vh5/TE7n7RX+8U\n" +
- "y37OL5k7x9nt0mM1TyAKxlCcY+9h6frue8MemZIILSIvMrtzccqNz0V1WKgA+Orf\n" +
- "uUrabmn+CxHF5gpy6g1Qs2IjVYWA5f7FROn/J+Ad8gJYc1azOWCLQqSyfpNRLSvY\n" +
- "EriQFEV63XvkJ8JrG62b+2OT2lqT4OO07gSPetppdlSa8NBSKP6Aro9RIX1ZjUZQ\n" +
- "SpQFCfo02NO0uNRDPUdJx2huycdNb+AXHaO7eXevDLJ+QnqImIzxWiY6zLOdzjjI\n" +
- "VBMkLHmnP7SjGSQ3XA4ByrQOxfOUTyLyE7NuemhHppuQPxE=\n" +
- "-----END CERTIFICATE-----\n").getBytes();
-
- /**
- * subjectAlt=foo.com
- */
- public final static byte[] X509_NO_CNS_FOO = (
- "-----BEGIN CERTIFICATE-----\n" +
- "MIIESjCCAzKgAwIBAgIJAIz+EYMBU6aYMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
- "VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
- "ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
- "FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
- "ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MjYxMFoXDTI4MTEwNTE2MjYxMFowgZIx\n" +
- "CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0\n" +
- "IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl\n" +
- "cnRpZmljYXRlczElMCMGCSqGSIb3DQEJARYWanVsaXVzZGF2aWVzQGdtYWlsLmNv\n" +
- "bTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMhjr5aCPoyp0R1iroWA\n" +
- "fnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2BlYho4O84X244QrZTRl8kQbYt\n" +
- "xnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRyzerA/ZtrlUqf+lKo0uWcocxe\n" +
- "Rc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY07hNKXAb2odnVqgzcYiDkLV8\n" +
- "ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8BqnGd87xQU3FVZI4tbtkB+Kz\n" +
- "jD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiVJTxpTKqym93whYk93l3ocEe5\n" +
- "5c0CAwEAAaOBkDCBjTAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQfFh1PcGVuU1NM\n" +
- "IEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUnxR3vz86tso4gkJIFiza\n" +
- "0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuzA1LKh6YNPg0wEgYDVR0RBAsw\n" +
- "CYIHZm9vLmNvbTANBgkqhkiG9w0BAQUFAAOCAQEAjl78oMjzFdsMy6F1sGg/IkO8\n" +
- "tF5yUgPgFYrs41yzAca7IQu6G9qtFDJz/7ehh/9HoG+oqCCIHPuIOmS7Sd0wnkyJ\n" +
- "Y7Y04jVXIb3a6f6AgBkEFP1nOT0z6kjT7vkA5LJ2y3MiDcXuRNMSta5PYVnrX8aZ\n" +
- "yiqVUNi40peuZ2R8mAUSBvWgD7z2qWhF8YgDb7wWaFjg53I36vWKn90ZEti3wNCw\n" +
- "qAVqixM+J0qJmQStgAc53i2aTMvAQu3A3snvH/PHTBo+5UL72n9S1kZyNCsVf1Qo\n" +
- "n8jKTiRriEM+fMFlcgQP284EBFzYHyCXFb9O/hMjK2+6mY9euMB1U1aFFzM/Bg==\n" +
- "-----END CERTIFICATE-----\n").getBytes();
-
- /**
- * Intermediate CA for all of these.
- */
- public final static byte[] X509_INTERMEDIATE_CA = (
- "-----BEGIN CERTIFICATE-----\n" +
- "MIIEnDCCA4SgAwIBAgIJAJTNwZ6yNa5cMA0GCSqGSIb3DQEBBQUAMIGGMQswCQYD\n" +
- "VQQGEwJDQTELMAkGA1UECBMCQkMxFjAUBgNVBAoTDXd3dy5jdWNiYy5jb20xFDAS\n" +
- "BgNVBAsUC2NvbW1vbnNfc3NsMRUwEwYDVQQDFAxkZW1vX3Jvb3RfY2ExJTAjBgkq\n" +
- "hkiG9w0BCQEWFmp1bGl1c2Rhdmllc0BnbWFpbC5jb20wHhcNMDYxMTA1MjE0OTMx\n" +
- "WhcNMDcxMTA1MjE0OTMxWjCBojELMAkGA1UEBhMCQ0ExCzAJBgNVBAgTAkJDMRIw\n" +
- "EAYDVQQHEwlWYW5jb3V2ZXIxFjAUBgNVBAoTDXd3dy5jdWNiYy5jb20xFDASBgNV\n" +
- "BAsUC2NvbW1vbnNfc3NsMR0wGwYDVQQDFBRkZW1vX2ludGVybWVkaWF0ZV9jYTEl\n" +
- "MCMGCSqGSIb3DQEJARYWanVsaXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZI\n" +
- "hvcNAQEBBQADggEPADCCAQoCggEBAL0S4y3vUO0EM6lwqOEfK8fvrUprIbsikXaG\n" +
- "XzejcZ+T3l2Dc7t8WtBfRf78i4JypMqJQSijrUicj3H6mOMIReKaXm6ls4hA5d8w\n" +
- "Lhmgiqsz/kW+gA8SeWGWRN683BD/RbQmzOls6ynBvap9jZlthXWBrSIlPCQoBLXY\n" +
- "KVaxGzbL4ezaq+XFMKMQSm2uKwVmHHQNbfmZlPsuendBVomb/ked53Ab9IH6dwwN\n" +
- "qJH9WIrvIzIVEXWlpvQ5MCqozM7u1akU+G8cazr8theGPCaYkzoXnigWua4OjdpV\n" +
- "9z5ZDknhfBzG1AjapdG07FIirwWWgIyZXqZSD96ikmLtwT29qnsCAwEAAaOB7jCB\n" +
- "6zAdBgNVHQ4EFgQUe5raj5CZTlLSrNuzA1LKh6YNPg0wgbsGA1UdIwSBszCBsIAU\n" +
- "rN8eFIvMiRFXXgDqKumS0/W2AhOhgYykgYkwgYYxCzAJBgNVBAYTAkNBMQswCQYD\n" +
- "VQQIEwJCQzEWMBQGA1UEChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9u\n" +
- "c19zc2wxFTATBgNVBAMUDGRlbW9fcm9vdF9jYTElMCMGCSqGSIb3DQEJARYWanVs\n" +
- "aXVzZGF2aWVzQGdtYWlsLmNvbYIJAJTNwZ6yNa5bMAwGA1UdEwQFMAMBAf8wDQYJ\n" +
- "KoZIhvcNAQEFBQADggEBAIB4KMZvHD20pdKajFtMBpL7X4W4soq6EeTtjml3NYa9\n" +
- "Qc52bsQEGNccKY9afYSBIndaQvFdtmz6HdoN+B8TjYShw2KhyjtKimGLpWYoi1YF\n" +
- "e4aHdmA/Gp5xk8pZzR18FmooxC9RqBux+NAM2iTFSLgDtGIIj4sg2rbn6Bb6ZlQT\n" +
- "1rg6VucXCA1629lNfMeNcu7CBNmUKIdaxHR/YJQallE0KfGRiOIWPrPj/VNk0YA6\n" +
- "XFg0ocjqXJ2/N0N9rWVshMUaXgOh7m4D/5zga5/nuxDU+PoToA6mQ4bV6eCYqZbh\n" +
- "aa1kQYtR9B4ZiG6pB82qVc2dCqStOH2FAEWos2gAVkQ=\n" +
- "-----END CERTIFICATE-----\n").getBytes();
-
- /**
- * Root CA for all of these.
- */
- public final static byte[] X509_ROOT_CA = (
- "-----BEGIN CERTIFICATE-----\n" +
- "MIIEgDCCA2igAwIBAgIJAJTNwZ6yNa5bMA0GCSqGSIb3DQEBBQUAMIGGMQswCQYD\n" +
- "VQQGEwJDQTELMAkGA1UECBMCQkMxFjAUBgNVBAoTDXd3dy5jdWNiYy5jb20xFDAS\n" +
- "BgNVBAsUC2NvbW1vbnNfc3NsMRUwEwYDVQQDFAxkZW1vX3Jvb3RfY2ExJTAjBgkq\n" +
- "hkiG9w0BCQEWFmp1bGl1c2Rhdmllc0BnbWFpbC5jb20wHhcNMDYxMTA1MjEzNjQz\n" +
- "WhcNMjYxMTA1MjEzNjQzWjCBhjELMAkGA1UEBhMCQ0ExCzAJBgNVBAgTAkJDMRYw\n" +
- "FAYDVQQKEw13d3cuY3VjYmMuY29tMRQwEgYDVQQLFAtjb21tb25zX3NzbDEVMBMG\n" +
- "A1UEAxQMZGVtb19yb290X2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZpZXNA\n" +
- "Z21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv+OnocmJ\n" +
- "79UeO2hlCwK+Cle5uZWnU6uwJl+08z5cvebb5tT64WL9+psDbfgUH/Gm9JsuxKTg\n" +
- "w1tZO/4duIgnaLNSx4HoqaTjwigd/hR3TsoGEPXTCkz1ikgTCOEDvl+iMid6aOrd\n" +
- "mViE8HhscxKZ+h5FE7oHZyuT6gFoiaIXhFq+xK2w4ZwDz9L+paiwqywyUJJMnh9U\n" +
- "jKorY+nua81N0oxpIhHPspCanDU4neMzCzYOZyLR/LqV5xORvHcFY84GWMz5hI25\n" +
- "JbgaWJsYKuCAvNsnQwVoqKPGa7x1fn7x6oGsXJaCVt8weUwIj2xwg1lxMhrNaisH\n" +
- "EvKpEAEnGGwWKQIDAQABo4HuMIHrMB0GA1UdDgQWBBSs3x4Ui8yJEVdeAOoq6ZLT\n" +
- "9bYCEzCBuwYDVR0jBIGzMIGwgBSs3x4Ui8yJEVdeAOoq6ZLT9bYCE6GBjKSBiTCB\n" +
- "hjELMAkGA1UEBhMCQ0ExCzAJBgNVBAgTAkJDMRYwFAYDVQQKEw13d3cuY3VjYmMu\n" +
- "Y29tMRQwEgYDVQQLFAtjb21tb25zX3NzbDEVMBMGA1UEAxQMZGVtb19yb290X2Nh\n" +
- "MSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZpZXNAZ21haWwuY29tggkAlM3BnrI1\n" +
- "rlswDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAlPl3/8h1LttR1svC\n" +
- "S8RXbHpAWIT2BEDhGHUNjSmgDQNkE/itf/FCEXh0tlU4bYdtBSOHzflbnzOyIPId\n" +
- "VZeSWs33V38xDFy6KoVg1gT8JxkLmE5S1vWkpsHIlpw/U6r7KD0Kx9FYx5AiXjw0\n" +
- "lzz/zlVNuO2U09KIDwDPVG1mBzQiMiSWj1U1pM4KxINkWQwDy/fvu/I983s8lW5z\n" +
- "hf2WuFNzQN3fcMK5dpBE9NVIu27oYuGYh2sak34v+7T700W2ooBB71qFXtm9P5rl\n" +
- "Yp9RCEsg3KEEPNTtCBs8fROeXvLDrP0cmBIqwGYDuRNCxFDTOdjv6YGdA8nLOjaH\n" +
- "2dDk0g==\n" +
- "-----END CERTIFICATE-----\n").getBytes();
-
- /**
- * Below is the private key for all the server certificates above (but
- * not the intermediate CA or the root CA). All of those server certs
- * came from the same private key.
- */
- public final static String RSA_PUBLIC_MODULUS =
- "00c863af96823e8ca9d11d62ae85807e713204c1985a80a2747f7ac863c5" +
- "8d82e8c1ecf9698298d4838a4d8d81958868e0ef385f6e3842b653465f24" +
- "41b62dc671a1e204820fe67c82367f80cbcb52586a39bf965cf0141cc077" +
- "f46472cdeac0fd9b6b954a9ffa52a8d2e59ca1cc5e45cefbd4a37c70f1f7" +
- "9c7674ad5d07c78640672e94e31c4e6dee2bb52558d3b84d29701bda8767" +
- "56a83371888390b57c8a5bc49a8356316ae9f1406a913729121621098a77" +
- "713920270312baabfc06a9c677cef1414dc5559238b5bb6407e2b38c3f73" +
- "cfc4020c901f0e3647474dca350e66c4e817c31c0ac3a94631a895253c69" +
- "4caab29bddf085893dde5de87047b9e5cd";
-
- public final static String RSA_PUBLIC_EXPONENT = "65537";
-
- public final static String RSA_PRIVATE_EXPONENT =
- "577abd3295553d0efd4d38c13b62a6d03fa7b7e40cce4f1d5071877d96c6" +
- "7a39a63f0f7ab21a89db8acae45587b3ef251309a70f74dc1ac02bde68f3" +
- "8ed658e54e685ed370a18c054449512ea66a2252ed36e82b565b5159ec83" +
- "f23df40ae189550a183865b25fd77789e960f0d8cedcd72f32d7a66edb4b" +
- "a0a2baf3fbeb6c7d75f56ef0af9a7cff1c8c7f297d72eae7982164e50a89" +
- "d450698cf598d39343201094241d2d180a95882a7111e58f4a5bdbc5c125" +
- "a967dd6ed9ec614c5853e88e4c71e8b682a7cf89cb1d82b6fe78cc865084" +
- "c8c5dfbb50c939df2b839c977b0245bfa3615e0592b527b1013d5b675ecb" +
- "44e6b355c1df581f50997175166eef39";
-
- public final static String RSA_PRIME1 =
- "00fe759c4f0ce8b763880215e82767e7a937297668f4e4b1e119c6b22a3c" +
- "a2c7b06c547d88d0aa45f645d7d3aeadaf7f8bc594deae0978529592977c" +
- "b1ff890f05033a9e9e15551cad9fbf9c41d12139ccd99c1c3ac7b2197eff" +
- "350d236bb900c1440953b64956e0a058ef824a2e16894af175177c77dbe1" +
- "fef7d8b532608d2513";
-
- public final static String RSA_PRIME2 =
- "00c99a45878737a4cf73f9896680b75487f1b669b7686a6ba07103856f31" +
- "db668c2c440c44cdd116f708f631c37a9adf119f5b5cb58ffe3dc62e20af" +
- "af72693d936dc6bb3c5194996468389c1f094079b81522e94572b4ad7d39" +
- "529178e9b8ebaeb1f0fdd83b8731c5223f1dea125341d1d64917f6b1a6ae" +
- "c18d320510d79f859f";
-
- public final static String RSA_EXPONENT1 =
- "029febf0d4cd41b7011c2465b4a259bd6118486464c247236f44a169d61e" +
- "47b9062508f674508d5031003ceabc57e714e600d71b2c75d5443db2da52" +
- "6bb45a374f0537c5a1aab3150764ce93cf386c84346a6bd01f6732e42075" +
- "c7a0e9e78a9e73b934e7d871d0f75673820089e129a1604438edcbbeb4e2" +
- "106467da112ce389";
-
- public final static String RSA_EXPONENT2 =
- "00827e76650c946afcd170038d32e1f8386ab00d6be78d830efe382e45d4" +
- "7ad4bd04e6231ee22e66740efbf52838134932c9f8c460cdccdec58a1424" +
- "4427859192fd6ab6c58b74e97941b0eaf577f2a11713af5e5952af3ae124" +
- "9a9a892e98410dfa2628d9af668a43b5302fb7d496c9b2fec69f595292b6" +
- "e997f079b0f6314eb7";
-
- public final static String RSA_COEFFICIENT =
- "00e6b62add350f1a2a8968903ff76c31cf703b0d7326c4a620aef01225b7" +
- "1640b3f2ec375208c5f7299863f6005b7799b6e529bb1133c8435bf5fdb5" +
- "a786f6cd8a19ee7094a384e6557c600a38845a0960ddbfd1df18d0af5740" +
- "001853788f1b5ccbf9affb4c52c9d2efdb8aab0183d86735b32737fb4e79" +
- "2b8a9c7d91c7d175ae";
-
- /**
- * subjectAlt=IP Address:127.0.0.1, email:oleg@ural.ru, DNS:localhost.localdomain
- */
- public final static byte[] X509_MULTIPLE_SUBJECT_ALT = (
- "-----BEGIN CERTIFICATE-----\n" +
- "MIIDcTCCAtqgAwIBAgIBATANBgkqhkiG9w0BAQUFADBAMQswCQYDVQQGEwJDSDEL\n" +
- "MAkGA1UECBMCWkgxDzANBgNVBAcTBlp1cmljaDETMBEGA1UEAxMKTXkgVGVzdCBD\n" +
- "QTAeFw0wODEwMzExMTU3NDVaFw0wOTEwMzExMTU3NDVaMGkxCzAJBgNVBAYTAkNI\n" +
- "MRAwDgYDVQQIEwdVbmtub3duMRAwDgYDVQQHEwdVbmtub3duMRAwDgYDVQQKEwdV\n" +
- "bmtub3duMRAwDgYDVQQLEwdVbmtub3duMRIwEAYDVQQDEwlsb2NhbGhvc3QwggG4\n" +
- "MIIBLAYHKoZIzjgEATCCAR8CgYEA/X9TgR11EilS30qcLuzk5/YRt1I870QAwx4/\n" +
- "gLZRJmlFXUAiUftZPY1Y+r/F9bow9subVWzXgTuAHTRv8mZgt2uZUKWkn5/oBHsQ\n" +
- "IsJPu6nX/rfGG/g7V+fGqKYVDwT7g/bTxR7DAjVUE1oWkTL2dfOuK2HXKu/yIgMZ\n" +
- "ndFIAccCFQCXYFCPFSMLzLKSuYKi64QL8Fgc9QKBgQD34aCF1ps93su8q1w2uFe5\n" +
- "eZSvu/o66oL5V0wLPQeCZ1FZV4661FlP5nEHEIGAtEkWcSPoTCgWE7fPCTKMyKbh\n" +
- "PBZ6i1R8jSjgo64eK7OmdZFuo38L+iE1YvH7YnoBJDvMpPG+qFGQiaiD3+Fa5Z8G\n" +
- "kotmXoB7VSVkAUw7/s9JKgOBhQACgYEA6ogAb/YLM1Rz9AoXKW4LA70VtFf7Mqqp\n" +
- "divdu9f72WQc1vMKo1YMf3dQadkMfBYRvAAa1IXDnoiFCHhXnVRkWkoUBJyNebLB\n" +
- "N92CZc0RVFZiMFgQMEh8UldnvAIi4cBk0/YuN3BGl4MzmquVIGrFovdWGqeaveOu\n" +
- "Xcu4lKGJNiqjODA2MDQGA1UdEQQtMCuHBH8AAAGBDG9sZWdAdXJhbC5ydYIVbG9j\n" +
- "YWxob3N0LmxvY2FsZG9tYWluMA0GCSqGSIb3DQEBBQUAA4GBAIgEwIoCSRkU3O7K\n" +
- "USYaOYyfJB9hsvs6YpClvYXiQ/5kPGARP60pM62v4wC7wI9shEizokIAxY2+O3cC\n" +
- "vwuJhNYaa2FJMELIwRN3XES8X8R6JHWbPaRjaAAPhczuEd8SZYy8yiVLmJTgw0gH\n" +
- "BSW775NHlkjsscFVgXkNf0PobqJ9\n" +
- "-----END CERTIFICATE-----").getBytes();
-
-}
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/HandshakeCompletedEventTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/HandshakeCompletedEventTest.java
deleted file mode 100644
index aebde6b..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/HandshakeCompletedEventTest.java
+++ /dev/null
@@ -1,743 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.InetSocketAddress;
-import java.security.KeyStore;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateException;
-
-import javax.net.ssl.HandshakeCompletedEvent;
-import javax.net.ssl.HandshakeCompletedListener;
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLPeerUnverifiedException;
-import javax.net.ssl.SSLServerSocket;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.SSLSocketFactory;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.X509TrustManager;
-import javax.security.cert.X509Certificate;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.luni.util.Base64;
-import org.apache.harmony.xnet.tests.support.mySSLSession;
-
-import tests.support.Support_PortManager;
-
-/**
- * Tests for <code>HandshakeCompletedEvent</code> class constructors and methods.
- *
- */
-@TestTargetClass(HandshakeCompletedEvent.class)
-public class HandshakeCompletedEventTest extends TestCase {
-
- String certificate = "-----BEGIN CERTIFICATE-----\n"
- + "MIICZTCCAdICBQL3AAC2MA0GCSqGSIb3DQEBAgUAMF8xCzAJBgNVBAYTAlVTMSAw\n"
- + "HgYDVQQKExdSU0EgRGF0YSBTZWN1cml0eSwgSW5jLjEuMCwGA1UECxMlU2VjdXJl\n"
- + "IFNlcnZlciBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw05NzAyMjAwMDAwMDBa\n"
- + "Fw05ODAyMjAyMzU5NTlaMIGWMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZv\n"
- + "cm5pYTESMBAGA1UEBxMJUGFsbyBBbHRvMR8wHQYDVQQKExZTdW4gTWljcm9zeXN0\n"
- + "ZW1zLCBJbmMuMSEwHwYDVQQLExhUZXN0IGFuZCBFdmFsdWF0aW9uIE9ubHkxGjAY\n"
- + "BgNVBAMTEWFyZ29uLmVuZy5zdW4uY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB\n"
- + "iQKBgQCofmdY+PiUWN01FOzEewf+GaG+lFf132UpzATmYJkA4AEA/juW7jSi+LJk\n"
- + "wJKi5GO4RyZoyimAL/5yIWDV6l1KlvxyKslr0REhMBaD/3Z3EsLTTEf5gVrQS6sT\n"
- + "WMoSZAyzB39kFfsB6oUXNtV8+UKKxSxKbxvhQn267PeCz5VX2QIDAQABMA0GCSqG\n"
- + "SIb3DQEBAgUAA34AXl3at6luiV/7I9MN5CXYoPJYI8Bcdc1hBagJvTMcmlqL2uOZ\n"
- + "H9T5hNMEL9Tk6aI7yZPXcw/xI2K6pOR/FrMp0UwJmdxX7ljV6ZtUZf7pY492UqwC\n"
- + "1777XQ9UEZyrKJvF5ntleeO0ayBqLGVKCWzWZX9YsXCpv47FNLZbupE=\n"
- + "-----END CERTIFICATE-----\n";
-
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.HandshakeCompletedEvent#HandshakeCompletedEvent(SSLSocket sock, SSLSession s)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Exceptions for null/incorrect parameters are not provided",
- method = "HandshakeCompletedEvent",
- args = {javax.net.ssl.SSLSocket.class, javax.net.ssl.SSLSession.class}
- )
- public final void test_Constructor() throws IOException {
- mySSLSession session = new mySSLSession();
- SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
- try {
- HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- try {
- HandshakeCompletedEvent event = new HandshakeCompletedEvent(null, null);
- fail("Any exception wasn't thrown for null parameters");
- } catch (Exception e) {
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.HandshakeCompletedEvent#getCipherSuite()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCipherSuite",
- args = {}
- )
- public final void test_getCipherSuite() throws IOException {
- mySSLSession session = new mySSLSession("localhost", 1080, null);
- SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
- HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
- try {
- assertEquals("SuiteName", event.getCipherSuite());
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.HandshakeCompletedEvent#getLocalCertificates()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocalCertificates",
- args = {}
- )
- public final void test_getLocalCertificates() throws IOException {
- mySSLSession session = new mySSLSession("localhost", 1080, null);
- SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
- HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
- try {
- assertNull(event.getLocalCertificates());
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.HandshakeCompletedEvent#getLocalPrincipal()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocalPrincipal",
- args = {}
- )
- public final void test_getLocalPrincipal() throws IOException {
- mySSLSession session = new mySSLSession("localhost", 1080, null);
- SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
- HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
- try {
- assertNull(event.getLocalPrincipal());
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.HandshakeCompletedEvent#getPeerCertificateChain()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPeerCertificateChain",
- args = {}
- )
- public final void test_getPeerCertificateChain() throws IOException {
- ByteArrayInputStream bis = new ByteArrayInputStream(certificate.getBytes());
- mySSLSession session = new mySSLSession((X509Certificate[]) null);
- SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
- HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
- try {
- X509Certificate[] res = event.getPeerCertificateChain();
- fail("SSLPeerUnverifiedException wasn't thrown");
- } catch (SSLPeerUnverifiedException spue) {
- //expected
- }
-
- try {
- X509Certificate xc = X509Certificate.getInstance(bis);
- X509Certificate[] xcs = {xc};
- session = new mySSLSession(xcs);
- event = new HandshakeCompletedEvent(socket, session);
- } catch (Exception e) {
- fail(e + " was thrown for configuration");
- }
- try {
- X509Certificate[] res = event.getPeerCertificateChain();
- assertEquals(res.length, 1);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.HandshakeCompletedEvent#getPeerCertificates()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPeerCertificates",
- args = {}
- )
- public final void test_getPeerCertificates() throws IOException {
- mySSLSession session = new mySSLSession("localhost", 1080, null);
- SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
- HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
- try {
- Certificate[] res = event.getPeerCertificates();
- fail("SSLPeerUnverifiedException wasn't thrown");
- } catch (SSLPeerUnverifiedException spue) {
- //expected
- }
-
- session = new mySSLSession((X509Certificate[]) null);
- event = new HandshakeCompletedEvent(socket, session);
- try {
- Certificate[] res = event.getPeerCertificates();
- assertEquals(res.length, 3);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.HandshakeCompletedEvent#getPeerPrincipal()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "",
- method = "getPeerPrincipal",
- args = {}
- )
- public final void test_getPeerPrincipal() throws IOException {
- mySSLSession session = new mySSLSession("localhost", 1080, null);
- SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
- HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
- try {
- assertNull(event.getPeerPrincipal());
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.HandshakeCompletedEvent#getSession()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSession",
- args = {}
- )
- public final void test_getSession() throws IOException {
- mySSLSession session = new mySSLSession("localhost", 1080, null);
- SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
- HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
- try {
- SSLSession ss = event.getSession();
- assertNotNull(ss);
- assertEquals(session, ss);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.HandshakeCompletedEvent#getSocket()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSocket",
- args = {}
- )
- public final void test_getSocket() throws IOException {
- SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
- HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, null);
- try {
- SSLSocket ss = event.getSocket();
- assertNotNull(ss);
- assertEquals(socket, ss);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
-
- // Regression test for CompletedHandshakeEvent not firing with a custom
- // TrustManager
-
-
- SSLSocket socket;
- SSLSocket serverSocket;
- MyHandshakeListener listener;
- int port = Support_PortManager.getNextPort();
- String host = "localhost";
-
- private String PASSWORD = "android";
-
- /**
- * Defines the keystore contents for the server, BKS version. Holds just a
- * single self-generated key. The subject name is "Test Server".
- */
- private static final String SERVER_KEYS_BKS =
- "AAAAAQAAABQDkebzoP1XwqyWKRCJEpn/t8dqIQAABDkEAAVteWtleQAAARpYl20nAAAAAQAFWC41" +
- "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU1jANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET" +
- "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV" +
- "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMB4XDTA4MDYwNTExNTgxNFoXDTA4MDkw" +
- "MzExNTgxNFowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U" +
- "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IFNlcnZl" +
- "cjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0LIdKaIr9/vsTq8BZlA3R+NFWRaH4lGsTAQy" +
- "DPMF9ZqEDOaL6DJuu0colSBBBQ85hQTPa9m9nyJoN3pEi1hgamqOvQIWcXBk+SOpUGRZZFXwniJV" +
- "zDKU5nE9MYgn2B9AoiH3CSuMz6HRqgVaqtppIe1jhukMc/kHVJvlKRNy9XMCAwEAATANBgkqhkiG" +
- "9w0BAQUFAAOBgQC7yBmJ9O/eWDGtSH9BH0R3dh2NdST3W9hNZ8hIa8U8klhNHbUCSSktZmZkvbPU" +
- "hse5LI3dh6RyNDuqDrbYwcqzKbFJaq/jX9kCoeb3vgbQElMRX8D2ID1vRjxwlALFISrtaN4VpWzV" +
- "yeoHPW4xldeZmoVtjn8zXNzQhLuBqX2MmAAAAqwAAAAUvkUScfw9yCSmALruURNmtBai7kQAAAZx" +
- "4Jmijxs/l8EBaleaUru6EOPioWkUAEVWCxjM/TxbGHOi2VMsQWqRr/DZ3wsDmtQgw3QTrUK666sR" +
- "MBnbqdnyCyvM1J2V1xxLXPUeRBmR2CXorYGF9Dye7NkgVdfA+9g9L/0Au6Ugn+2Cj5leoIgkgApN" +
- "vuEcZegFlNOUPVEs3SlBgUF1BY6OBM0UBHTPwGGxFBBcetcuMRbUnu65vyDG0pslT59qpaR0TMVs" +
- "P+tcheEzhyjbfM32/vwhnL9dBEgM8qMt0sqF6itNOQU/F4WGkK2Cm2v4CYEyKYw325fEhzTXosck" +
- "MhbqmcyLab8EPceWF3dweoUT76+jEZx8lV2dapR+CmczQI43tV9btsd1xiBbBHAKvymm9Ep9bPzM" +
- "J0MQi+OtURL9Lxke/70/MRueqbPeUlOaGvANTmXQD2OnW7PISwJ9lpeLfTG0LcqkoqkbtLKQLYHI" +
- "rQfV5j0j+wmvmpMxzjN3uvNajLa4zQ8l0Eok9SFaRr2RL0gN8Q2JegfOL4pUiHPsh64WWya2NB7f" +
- "V+1s65eA5ospXYsShRjo046QhGTmymwXXzdzuxu8IlnTEont6P4+J+GsWk6cldGbl20hctuUKzyx" +
- "OptjEPOKejV60iDCYGmHbCWAzQ8h5MILV82IclzNViZmzAapeeCnexhpXhWTs+xDEYSKEiG/camt" +
- "bhmZc3BcyVJrW23PktSfpBQ6D8ZxoMfF0L7V2GQMaUg+3r7ucrx82kpqotjv0xHghNIm95aBr1Qw" +
- "1gaEjsC/0wGmmBDg1dTDH+F1p9TInzr3EFuYD0YiQ7YlAHq3cPuyGoLXJ5dXYuSBfhDXJSeddUkl" +
- "k1ufZyOOcskeInQge7jzaRfmKg3U94r+spMEvb0AzDQVOKvjjo1ivxMSgFRZaDb/4qw=";
-
- /**
- * Defines the keystore contents for the server, JKS version. Holds just a
- * single self-generated key. The subject name is "Test Server".
- */
- private static final String SERVER_KEYS_JKS =
- "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFfBeAAAArowggK2MA4GCisGAQQBKgIRAQEFAASC" +
- "AqI2kp5XjnF8YZkhcF92YsJNQkvsmH7zqMM87j23zSoV4DwyE3XeC/gZWq1ToScIhoqZkzlbWcu4" +
- "T/Zfc/DrfGk/rKbBL1uWKGZ8fMtlZk8KoAhxZk1JSyJvdkyKxqmzUbxk1OFMlN2VJNu97FPVH+du" +
- "dvjTvmpdoM81INWBW/1fZJeQeDvn4mMbbe0IxgpiLnI9WSevlaDP/sm1X3iO9yEyzHLL+M5Erspo" +
- "Cwa558fOu5DdsICMXhvDQxjWFKFhPHnKtGe+VvwkG9/bAaDgx3kfhk0w5zvdnkKb+8Ed9ylNRzdk" +
- "ocAa/mxlMTOsTvDKXjjsBupNPIIj7OP4GNnZaxkJjSs98pEO67op1GX2qhy6FSOPNuq8k/65HzUc" +
- "PYn6voEeh6vm02U/sjEnzRevQ2+2wXoAdp0EwtQ/DlMe+NvcwPGWKuMgX4A4L93DZGb04N2VmAU3" +
- "YLOtZwTO0LbuWrcCM/q99G/7LcczkxIVrO2I/rh8RXVczlf9QzcrFObFv4ATuspWJ8xG7DhsMbnk" +
- "rT94Pq6TogYeoz8o8ZMykesAqN6mt/9+ToIemmXv+e+KU1hI5oLwWMnUG6dXM6hIvrULY6o+QCPH" +
- "172YQJMa+68HAeS+itBTAF4Clm/bLn6reHCGGU6vNdwU0lYldpiOj9cB3t+u2UuLo6tiFWjLf5Zs" +
- "EQJETd4g/EK9nHxJn0GAKrWnTw7pEHQJ08elzUuy04C/jEEG+4QXU1InzS4o/kR0Sqz2WTGDoSoq" +
- "ewuPRU5bzQs/b9daq3mXrnPtRBL6HfSDAdpTK76iHqLCGdqx3avHjVSBm4zFvEuYBCev+3iKOBmg" +
- "yh7eQRTjz4UOWfy85omMBr7lK8PtfVBDzOXpasxS0uBgdUyBDX4tO6k9jZ8a1kmQRQAAAAEABVgu" +
- "NTA5AAACSDCCAkQwggGtAgRIR8SKMA0GCSqGSIb3DQEBBAUAMGkxCzAJBgNVBAYTAlVTMRMwEQYD" +
- "VQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzANBgNVBAoTBkdvb2dsZTEQMA4GA1UECxMH" +
- "QW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBTZXJ2ZXIwHhcNMDgwNjA1MTA0ODQyWhcNMDgwOTAzMTA0" +
- "ODQyWjBpMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8w" +
- "DQYDVQQKEwZHb29nbGUxEDAOBgNVBAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMIGf" +
- "MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwoC6chqCI84rj1PrXuJgbiit4EV909zR6N0jNlYfg" +
- "itwB39bP39wH03rFm8T59b3mbSptnGmCIpLZn25KPPFsYD3JJ+wFlmiUdEP9H05flfwtFQJnw9uT" +
- "3rRIdYVMPcQ3RoZzwAMliGr882I2thIDbA6xjGU/1nRIdvk0LtxH3QIDAQABMA0GCSqGSIb3DQEB" +
- "BAUAA4GBAJn+6YgUlY18Ie+0+Vt8oEi81DNi/bfPrAUAh63fhhBikx/3R9dl3wh09Z6p7cIdNxjW" +
- "n2ll+cRW9eqF7z75F0Omm0C7/KAEPjukVbszmzeU5VqzkpSt0j84YWi+TfcHRrfvhLbrlmGITVpY" +
- "ol5pHLDyqGmDs53pgwipWqsn/nEXEBgj3EoqPeqHbDf7YaP8h/5BSt0=";
-
- /**
- * Defines the keystore contents for the client, JKS version. Holds just a
- * single self-generated key. The subject name is "Test Client".
- */
- private static final String CLIENT_KEYS_JKS =
- "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFhyMAAAArkwggK1MA4GCisGAQQBKgIRAQEFAASC" +
- "AqGVSfXolBStZy4nnRNn4fAr+S7kfU2BS23wwW8uB2Ru3GvtLzlK9q08Gvq/LNqBafjyFTVL5FV5" +
- "SED/8YomO5a98GpskSeRvytCiTBLJdgGhws5TOGekgIAcBROPGIyOtJPQ0HfOQs+BqgzGDHzHQhw" +
- "u/8Tm6yQwiP+W/1I9B1QnaEztZA3mhTyMMJsmsFTYroGgAog885D5Cmzd8sYGfxec3R6I+xcmBAY" +
- "eibR5kGpWwt1R+qMvRrtBqh5r6WSKhCBNax+SJVbtUNRiKyjKccdJg6fGqIWWeivwYTy0OhjA6b4" +
- "NiZ/ZZs5pxFGWUj/Rlp0RYy8fCF6aw5/5s4Bf4MI6dPSqMG8Hf7sJR91GbcELyzPdM0h5lNavgit" +
- "QPEzKeuDrGxhY1frJThBsNsS0gxeu+OgfJPEb/H4lpYX5IvuIGbWKcxoO9zq4/fimIZkdA8A+3eY" +
- "mfDaowvy65NBVQPJSxaOyFhLHfeLqOeCsVENAea02vA7andZHTZehvcrqyKtm+z8ncHGRC2H9H8O" +
- "jKwKHfxxrYY/jMAKLl00+PBb3kspO+BHI2EcQnQuMw/zr83OR9Meq4TJ0TMuNkApZELAeFckIBbS" +
- "rBr8NNjAIfjuCTuKHhsTFWiHfk9ZIzigxXagfeDRiyVc6khOuF/bGorj23N2o7Rf3uLoU6PyXWi4" +
- "uhctR1aL6NzxDoK2PbYCeA9hxbDv8emaVPIzlVwpPK3Ruvv9mkjcOhZ74J8bPK2fQmbplbOljcZi" +
- "tZijOfzcO/11JrwhuJZRA6wanTqHoujgChV9EukVrmbWGGAcewFnAsSbFXIik7/+QznXaDIt5NgL" +
- "H/Bcz4Z/fdV7Ae1eUaxKXdPbI//4J+8liVT/d8awjW2tldIaDlmGMR3aoc830+3mAAAAAQAFWC41" +
- "MDkAAAJIMIICRDCCAa0CBEhHxLgwDQYJKoZIhvcNAQEEBQAwaTELMAkGA1UEBhMCVVMxEzARBgNV" +
- "BAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01UVjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdB" +
- "bmRyb2lkMRQwEgYDVQQDEwtUZXN0IENsaWVudDAeFw0wODA2MDUxMDQ5MjhaFw0wODA5MDMxMDQ5" +
- "MjhaMGkxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzAN" +
- "BgNVBAoTBkdvb2dsZTEQMA4GA1UECxMHQW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBDbGllbnQwgZ8w" +
- "DQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAIK3Q+KiFbmCGg422TAo4gggdhMH6FJhiuz8DxRyeMKR" +
- "UAfP4MK0wtc8N42waZ6OKvxpBFUy0BRfBsX0GD4Ku99yu9/tavSigTraeJtwV3WWRRjIqk7L3wX5" +
- "cmgS2KSD43Y0rNUKrko26lnt9N4qiYRBSj+tcAN3Lx9+ptqk1LApAgMBAAEwDQYJKoZIhvcNAQEE" +
- "BQADgYEANb7Q1GVSuy1RPJ0FmiXoMYCCtvlRLkmJphwxovK0cAQK12Vll+yAzBhHiQHy/RA11mng" +
- "wYudC7u3P8X/tBT8GR1Yk7QW3KgFyPafp3lQBBCraSsfrjKj+dCLig1uBLUr4f68W8VFWZWWTHqp" +
- "NMGpCX6qmjbkJQLVK/Yfo1ePaUexPSOX0G9m8+DoV3iyNw6at01NRw==";
-
- /**
- * Defines the keystore contents for the client, BKS version. Holds just a
- * single self-generated key. The subject name is "Test Client".
- */
- private static final String CLIENT_KEYS_BKS =
- "AAAAAQAAABT4Rka6fxbFps98Y5k2VilmbibNkQAABfQEAAVteWtleQAAARpYl+POAAAAAQAFWC41" +
- "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU9TANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET" +
- "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV" +
- "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgQ2xpZW50MB4XDTA4MDYwNTExNTg0NVoXDTA4MDkw" +
- "MzExNTg0NVowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U" +
- "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IENsaWVu" +
- "dDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEApUvmWsQDHPpbDKK13Yez2/q54tTOmRml/qva" +
- "2K6dZjkjSTW0iRuk7ztaVEvdJpfVIDv1oBsCI51ttyLHROy1epjF+GoL74mJb7fkcd0VOoSOTjtD" +
- "+3GgZkHPAm5YmUYxiJXqxKKJJqMCTIW46eJaA2nAep9QIwZ14/NFAs4ObV8CAwEAATANBgkqhkiG" +
- "9w0BAQUFAAOBgQCJrCr3hZQFDlLIfsSKI1/w+BLvyf4fubOid0pBxfklR8KBNPTiqjSmu7pd/C/F" +
- "1FR8CdZUDoPflZHCOU+fj5r5KUC1HyigY/tEUvlforBpfB0uCF+tXW4DbUfOWhfMtLV4nCOJOOZg" +
- "awfZLJWBJouLKOp427vDftxTSB+Ks8YjlgAAAqwAAAAU+NH6TtrzjyDdCXm5B6Vo7xX5G4YAAAZx" +
- "EAUkcZtmykn7YdaYxC1jRFJ+GEJpC8nZVg83QClVuCSIS8a5f8Hl44Bk4oepOZsPzhtz3RdVzDVi" +
- "RFfoyZFsrk9F5bDTVJ6sQbb/1nfJkLhZFXokka0vND5AXMSoD5Bj1Fqem3cK7fSUyqKvFoRKC3XD" +
- "FQvhqoam29F1rbl8FaYdPvhhZo8TfZQYUyUKwW+RbR44M5iHPx+ykieMe/C/4bcM3z8cwIbYI1aO" +
- "gjQKS2MK9bs17xaDzeAh4sBKrskFGrDe+2dgvrSKdoakJhLTNTBSG6m+rzqMSCeQpafLKMSjTSSz" +
- "+KoQ9bLyax8cbvViGGju0SlVhquloZmKOfHr8TukIoV64h3uCGFOVFtQjCYDOq6NbfRvMh14UVF5" +
- "zgDIGczoD9dMoULWxBmniGSntoNgZM+QP6Id7DBasZGKfrHIAw3lHBqcvB5smemSu7F4itRoa3D8" +
- "N7hhUEKAc+xA+8NKmXfiCBoHfPHTwDvt4IR7gWjeP3Xv5vitcKQ/MAfO5RwfzkYCXQ3FfjfzmsE1" +
- "1IfLRDiBj+lhQSulhRVStKI88Che3M4JUNGKllrc0nt1pWa1vgzmUhhC4LSdm6trTHgyJnB6OcS9" +
- "t2furYjK88j1AuB4921oxMxRm8c4Crq8Pyuf+n3YKi8Pl2BzBtw++0gj0ODlgwut8SrVj66/nvIB" +
- "jN3kLVahR8nZrEFF6vTTmyXi761pzq9yOVqI57wJGx8o3Ygox1p+pWUPl1hQR7rrhUbgK/Q5wno9" +
- "uJk07h3IZnNxE+/IKgeMTP/H4+jmyT4mhsexJ2BFHeiKF1KT/FMcJdSi+ZK5yoNVcYuY8aZbx0Ef" +
- "lHorCXAmLFB0W6Cz4KPP01nD9YBB4olxiK1t7m0AU9zscdivNiuUaB5OIEr+JuZ6dNw=";
-
-
- /**
- * Implements the actual test case. Launches a server and a client, requires
- * client authentication and checks the certificates afterwards (not in the
- * usual sense, we just make sure that we got the expected certificates,
- * because our self-signed test certificates are not valid.)
- */
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- clazz = SSLSocket.class,
- method = "addHandshakeCompletedListener",
- args = {HandshakeCompletedListener.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- clazz = HandshakeCompletedListener.class,
- method = "handshakeCompleted",
- args = {HandshakeCompletedEvent.class}
- )
- })
- @AndroidOnly("Uses bks key store. Change useBKS to false to run on the RI")
- public void testClientAuth() {
-
- boolean useBKS = true;
-
- listener = new MyHandshakeListener();
- try {
- String serverKeys = (useBKS ? SERVER_KEYS_BKS : SERVER_KEYS_JKS);
- String clientKeys = (useBKS ? CLIENT_KEYS_BKS : CLIENT_KEYS_JKS);
- TestServer server = new TestServer(true,
- TestServer.CLIENT_AUTH_WANTED, serverKeys);
- TestClient client = new TestClient(true, clientKeys);
-
- Thread serverThread = new Thread(server);
- Thread clientThread = new Thread(client);
-
- serverThread.start();
- Thread.currentThread().sleep(3000);
- clientThread.start();
-
- serverThread.join();
- clientThread.join();
-
- // The server must have completed without an exception.
- if (server.getException() != null) {
- throw new RuntimeException(server.getException());
- }
-
- // The client must have completed without an exception.
- if (client.getException() != null) {
- throw new RuntimeException(client.getException());
- }
-
- assertTrue(listener.completeDone);
-
- } catch (Exception ex) {
- throw new RuntimeException(ex);
- }
- }
-
- /**
- * Implements a test SSL socket server. It wait for a connection on a given
- * port, requests client authentication (if specified), reads 256 bytes
- * from the socket, and writes 256 bytes to the socket.
- */
- class TestServer implements Runnable {
-
- public static final int CLIENT_AUTH_NONE = 0;
-
- public static final int CLIENT_AUTH_WANTED = 1;
-
- public static final int CLIENT_AUTH_NEEDED = 2;
-
- private TestTrustManager trustManager;
-
- private Exception exception;
-
- String keys;
-
- private int clientAuth;
-
- private boolean provideKeys;
-
- public TestServer(boolean provideKeys, int clientAuth, String keys) {
- this.keys = keys;
- this.clientAuth = clientAuth;
- this.provideKeys = provideKeys;
-
- trustManager = new TestTrustManager();
- }
-
- public void run() {
- try {
- KeyManager[] keyManagers = provideKeys ? getKeyManagers(keys) : null;
- TrustManager[] trustManagers = new TrustManager[] { trustManager };
-
- SSLContext sslContext = SSLContext.getInstance("TLS");
- sslContext.init(keyManagers, trustManagers, null);
-
- SSLServerSocket serverSocket = (SSLServerSocket)sslContext.getServerSocketFactory().createServerSocket();
-
- if (clientAuth == CLIENT_AUTH_WANTED) {
- serverSocket.setWantClientAuth(true);
- } else if (clientAuth == CLIENT_AUTH_NEEDED) {
- serverSocket.setNeedClientAuth(true);
- } else {
- serverSocket.setWantClientAuth(false);
- }
-
- serverSocket.bind(new InetSocketAddress(port));
-
- SSLSocket clientSocket = (SSLSocket)serverSocket.accept();
-
- InputStream istream = clientSocket.getInputStream();
-
- for (int i = 0; i < 256; i++) {
- int j = istream.read();
- if (i != j) {
- throw new RuntimeException("Error reading socket, expected " + i + ", got " + j);
- }
- }
-
- istream.close();
-
- OutputStream ostream = clientSocket.getOutputStream();
-
- for (int i = 0; i < 256; i++) {
- ostream.write(i);
- }
-
- ostream.flush();
- ostream.close();
-
- clientSocket.close();
- serverSocket.close();
-
- } catch (Exception ex) {
- exception = ex;
- }
- }
-
- public Exception getException() {
- return exception;
- }
-
- public X509Certificate[] getChain() {
- return trustManager.getChain();
- }
-
- }
-
- /**
- * Implements a test SSL socket client. It open a connection to localhost on
- * a given port, writes 256 bytes to the socket, and reads 256 bytes from the
- * socket.
- */
- class TestClient implements Runnable {
-
- private TestTrustManager trustManager;
-
- private Exception exception;
-
- private String keys;
-
- private boolean provideKeys;
-
- public TestClient(boolean provideKeys, String keys) {
- this.keys = keys;
- this.provideKeys = provideKeys;
-
- trustManager = new TestTrustManager();
- }
-
- public void run() {
- try {
- KeyManager[] keyManagers = provideKeys ? getKeyManagers(keys) : null;
- TrustManager[] trustManagers = new TrustManager[] { trustManager };
-
- SSLContext sslContext = SSLContext.getInstance("TLS");
- sslContext.init(keyManagers, trustManagers, null);
-
- SSLSocket socket = (SSLSocket)sslContext.getSocketFactory().createSocket();
-
- socket.connect(new InetSocketAddress(port));
- socket.addHandshakeCompletedListener(listener);
- socket.startHandshake();
-
- OutputStream ostream = socket.getOutputStream();
-
- for (int i = 0; i < 256; i++) {
- ostream.write(i);
- }
-
- ostream.flush();
- ostream.close();
-
- InputStream istream = socket.getInputStream();
-
- for (int i = 0; i < 256; i++) {
- int j = istream.read();
- if (i != j) {
- throw new RuntimeException("Error reading socket, expected " + i + ", got " + j);
- }
- }
-
- istream.close();
-
- socket.close();
-
- } catch (Exception ex) {
- exception = ex;
- }
- }
-
- public Exception getException() {
- return exception;
- }
-
- public X509Certificate[] getChain() {
- return trustManager.getChain();
- }
- }
-
- /**
- * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
- * for the result.
- */
- private KeyManager[] getKeyManagers(String keys) throws Exception {
- byte[] bytes = new Base64().decode(keys.getBytes());
- InputStream inputStream = new ByteArrayInputStream(bytes);
-
- KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
- keyStore.load(inputStream, PASSWORD.toCharArray());
- inputStream.close();
-
- String algorithm = KeyManagerFactory.getDefaultAlgorithm();
- KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
- keyManagerFactory.init(keyStore, PASSWORD.toCharArray());
-
- return keyManagerFactory.getKeyManagers();
- }
-
-
- /**
- * Implements basically a dummy TrustManager. It stores the certificate
- * chain it sees, so it can later be queried.
- */
- public static class TestTrustManager implements X509TrustManager {
-
- private X509Certificate[] chain;
-
- private String authType;
-
- public void checkClientTrusted(X509Certificate[] chain, String authType) {
- this.chain = chain;
- this.authType = authType;
- }
-
- public void checkServerTrusted(X509Certificate[] chain, String authType) {
- this.chain = chain;
- this.authType = authType;
- }
-
- public java.security.cert.X509Certificate[] getAcceptedIssuers() {
- return new java.security.cert.X509Certificate[0];
- }
-
- public X509Certificate[] getChain() {
- return chain;
- }
-
- public String getAuthType() {
- return authType;
- }
-
- public void checkClientTrusted(
- java.security.cert.X509Certificate[] chain, String authType)
- throws CertificateException {
-
- }
-
- public void checkServerTrusted(
- java.security.cert.X509Certificate[] chain, String authType)
- throws CertificateException {
-
- }
-
- }
-
- class MyHandshakeListener implements HandshakeCompletedListener {
-
- public boolean completeDone;
-
- MyHandshakeListener() {
- completeDone = false;
- }
-
- public void handshakeCompleted(HandshakeCompletedEvent event) {
- if (event != null) completeDone = true;
- }
- }
-}
-
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/HostnameVerifierTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/HostnameVerifierTest.java
deleted file mode 100644
index 15eb1cc..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/HostnameVerifierTest.java
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership. The ASF
- * licenses this file to You under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.BrokenTest;
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.SideEffect;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.xnet.tests.support.mySSLSession;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.security.cert.CertificateFactory;
-import java.security.cert.X509Certificate;
-
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.HttpsURLConnection;
-import javax.net.ssl.SSLSession;
-
-
-/**
- * Tests for <code>HostnameVerifier</code> class constructors and methods.
- *
- */
-@TestTargetClass(HostnameVerifier.class)
-public class HostnameVerifierTest extends TestCase implements
- CertificatesToPlayWith {
-
- /**
- * @tests javax.net.ssl.HostnameVerifier#verify(String hostname, SSLSession
- * session)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "verify",
- args = {String.class, SSLSession.class}
- )
- @SideEffect("the DefaultHostnameVerifier is set in some other tests, therefore we need isolation")
- public final void test_verify() {
- mySSLSession session = new mySSLSession("localhost", 1080, null);
- HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
- try {
- assertFalse(hv.verify("localhost", session));
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- // copied and modified from apache http client test suite.
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "verify",
- args = {String.class, SSLSession.class}
- )
- @AndroidOnly("DefaultHostnameVerifier on RI is weird and cannot be tested this way.")
- @SideEffect("the DefaultHostnameVerifier is set in some other tests, therefore we need isolation")
- public void testVerify() throws Exception {
- CertificateFactory cf = CertificateFactory.getInstance("X.509");
- InputStream in;
- X509Certificate x509;
- in = new ByteArrayInputStream(X509_FOO);
- x509 = (X509Certificate) cf.generateCertificate(in);
- mySSLSession session = new mySSLSession(new X509Certificate[] {x509});
-
- HostnameVerifier verifier = HttpsURLConnection
- .getDefaultHostnameVerifier();
-
- assertTrue(verifier.verify("foo.com", session));
- assertFalse(verifier.verify("a.foo.com", session));
- assertFalse(verifier.verify("bar.com", session));
-
- in = new ByteArrayInputStream(X509_HANAKO);
- x509 = (X509Certificate) cf.generateCertificate(in);
- session = new mySSLSession(new X509Certificate[] {x509});
- assertTrue(verifier.verify("\u82b1\u5b50.co.jp", session));
- assertFalse(verifier.verify("a.\u82b1\u5b50.co.jp", session));
-
- in = new ByteArrayInputStream(X509_FOO_BAR);
- x509 = (X509Certificate) cf.generateCertificate(in);
- session = new mySSLSession(new X509Certificate[] {x509});
- assertTrue(verifier.verify("foo.com", session));
- assertFalse(verifier.verify("a.foo.com", session));
- assertTrue(verifier.verify("bar.com", session));
- assertFalse(verifier.verify("a.bar.com", session));
-
- in = new ByteArrayInputStream(X509_FOO_BAR_HANAKO);
- x509 = (X509Certificate) cf.generateCertificate(in);
- session = new mySSLSession(new X509Certificate[] {x509});
- assertTrue(verifier.verify("foo.com", session));
- assertFalse(verifier.verify("a.foo.com", session));
- // these checks test alternative subjects. The test data contains an
- // alternative subject starting with a japanese kanji character. This is
- // not supported by Android because the underlying implementation from
- // harmony follows the definition from rfc 1034 page 10 for alternative
- // subject names. This causes the code to drop all alternative subjects.
- // assertTrue(verifier.verify("bar.com", session));
- // assertFalse(verifier.verify("a.bar.com", session));
- // assertFalse(verifier.verify("a.\u82b1\u5b50.co.jp", session));
-
- in = new ByteArrayInputStream(X509_NO_CNS_FOO);
- x509 = (X509Certificate) cf.generateCertificate(in);
- session = new mySSLSession(new X509Certificate[] {x509});
- assertTrue(verifier.verify("foo.com", session));
- assertFalse(verifier.verify("a.foo.com", session));
-
- in = new ByteArrayInputStream(X509_NO_CNS_FOO);
- x509 = (X509Certificate) cf.generateCertificate(in);
- session = new mySSLSession(new X509Certificate[] {x509});
- assertTrue(verifier.verify("foo.com", session));
- assertFalse(verifier.verify("a.foo.com", session));
-
- in = new ByteArrayInputStream(X509_THREE_CNS_FOO_BAR_HANAKO);
- x509 = (X509Certificate) cf.generateCertificate(in);
- session = new mySSLSession(new X509Certificate[] {x509});
- assertFalse(verifier.verify("foo.com", session));
- assertFalse(verifier.verify("a.foo.com", session));
- assertFalse(verifier.verify("bar.com", session));
- assertFalse(verifier.verify("a.bar.com", session));
- assertTrue(verifier.verify("\u82b1\u5b50.co.jp", session));
- assertFalse(verifier.verify("a.\u82b1\u5b50.co.jp", session));
-
- in = new ByteArrayInputStream(X509_WILD_FOO);
- x509 = (X509Certificate) cf.generateCertificate(in);
- session = new mySSLSession(new X509Certificate[] {x509});
- assertFalse(verifier.verify("foo.com", session));
- assertTrue(verifier.verify("www.foo.com", session));
- assertTrue(verifier.verify("\u82b1\u5b50.foo.com", session));
- assertTrue(verifier.verify("a.b.foo.com", session));
-
- in = new ByteArrayInputStream(X509_WILD_CO_JP);
- x509 = (X509Certificate) cf.generateCertificate(in);
- session = new mySSLSession(new X509Certificate[] {x509});
- // Silly test because no-one would ever be able to lookup an IP address
- // using "*.co.jp".
- assertTrue(verifier.verify("*.co.jp", session));
- assertFalse(verifier.verify("foo.co.jp", session));
- assertFalse(verifier.verify("\u82b1\u5b50.co.jp", session));
-
- in = new ByteArrayInputStream(X509_WILD_FOO_BAR_HANAKO);
- x509 = (X509Certificate) cf.generateCertificate(in);
- session = new mySSLSession(new X509Certificate[] {x509});
- // try the foo.com variations
- assertFalse(verifier.verify("foo.com", session));
- assertTrue(verifier.verify("www.foo.com", session));
- assertTrue(verifier.verify("\u82b1\u5b50.foo.com", session));
- assertTrue(verifier.verify("a.b.foo.com", session));
- // these checks test alternative subjects. The test data contains an
- // alternative subject starting with a japanese kanji character. This is
- // not supported by Android because the underlying implementation from
- // harmony follows the definition from rfc 1034 page 10 for alternative
- // subject names. This causes the code to drop all alternative subjects.
- // assertFalse(verifier.verify("bar.com", session));
- // assertTrue(verifier.verify("www.bar.com", session));
- // assertTrue(verifier.verify("\u82b1\u5b50.bar.com", session));
- // assertTrue(verifier.verify("a.b.bar.com", session));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "verify",
- args = {String.class, SSLSession.class}
- )
- @AndroidOnly("DefaultHostnameVerifier on RI is weird and cannot be tested this way.")
- @KnownFailure("DefaultHostnameVerifier is broken on Android, fixed in donutburger")
- @SideEffect("the DefaultHostnameVerifier is set in some other tests, therefore we need isolation")
- public void testSubjectAlt() throws Exception {
- CertificateFactory cf = CertificateFactory.getInstance("X.509");
- InputStream in = new ByteArrayInputStream(X509_MULTIPLE_SUBJECT_ALT);
- X509Certificate x509 = (X509Certificate) cf.generateCertificate(in);
- mySSLSession session = new mySSLSession(new X509Certificate[] {x509});
-
- HostnameVerifier verifier = HttpsURLConnection
- .getDefaultHostnameVerifier();
-
- // Whitespace differences between RI and Android are ignored by
- // replacing ", " with ","
- assertEquals(
- "CN=localhost,OU=Unknown,O=Unknown,L=Unknown,ST=Unknown,C=CH",
- x509.getSubjectDN().getName().replace(", ", ","));
-
- assertTrue(verifier.verify("localhost", session));
- assertTrue(verifier.verify("localhost.localdomain", session));
- assertTrue(verifier.verify("127.0.0.1", session));
-
- assertFalse(verifier.verify("local.host", session));
- assertFalse(verifier.verify("127.0.0.2", session));
-
- }
-}
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/HttpsURLConnectionTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/HttpsURLConnectionTest.java
deleted file mode 100644
index 067b2a9..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/HttpsURLConnectionTest.java
+++ /dev/null
@@ -1,498 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.ByteArrayInputStream;
-import java.net.URL;
-import java.security.Principal;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateException;
-import java.security.cert.CertificateFactory;
-
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.HttpsURLConnection;
-import javax.net.ssl.SSLPeerUnverifiedException;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSocketFactory;
-
-import org.apache.harmony.security.tests.support.cert.TestUtils;
-
-import junit.framework.TestCase;
-
-
-
-/**
- * Tests for <code>HttpsURLConnection</code> class constructors and methods.
- *
- */
-@TestTargetClass(HttpsURLConnection.class)
-public class HttpsURLConnectionTest extends TestCase {
-
- /**
- * @tests javax.net.ssl.HttpsURLConnection#HttpsURLConnection(java_net_URL)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "HttpsURLConnection",
- args = {java.net.URL.class}
- )
- public final void test_Constructor() {
- try {
- MyHttpsURLConnection huc = new MyHttpsURLConnection(new URL("https://www.fortify.net/"));
- } catch (Exception e) {
- fail("Unexpected exception: " + e.toString());
- }
- try {
- MyHttpsURLConnection huc = new MyHttpsURLConnection(null);
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- /**
- * @tests javax.net.ssl.HttpsURLConnection#getCipherSuite()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCipherSuite",
- args = {}
- )
- public final void test_getCipherSuite() {
- try {
- URL url = new URL("https://localhost:55555");
- HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
- try {
- connection.getCipherSuite();
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException ise) {
- //expected
- }
- } catch (Exception e) {
- fail("Unexpected exception " + e + " for exception case");
- }
-
- try {
- HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"));
- assertEquals("CipherSuite", con.getCipherSuite());
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
- }
-
- /**
- * @tests javax.net.ssl.HttpsURLConnection#getLocalCertificates()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocalCertificates",
- args = {}
- )
- public final void test_getLocalCertificates() {
- try {
- URL url = new URL("https://localhost:55555");
- HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
- try {
- connection.getLocalCertificates();
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException ise) {
- //expected
- }
- } catch (Exception e) {
- fail("Unexpected exception " + e + " for exception case");
- }
-
- try {
- HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508");
- assertNull(con.getLocalCertificates());
- con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509");
- Certificate[] cert = con.getLocalCertificates();
- assertNotNull(cert);
- assertEquals(1, cert.length);
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
- }
-
- /**
- * @tests javax.net.ssl.HttpsURLConnection#getDefaultHostnameVerifier()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDefaultHostnameVerifier",
- args = {}
- )
- public final void test_getDefaultHostnameVerifier() {
- HostnameVerifier verifyer =
- HttpsURLConnection.getDefaultHostnameVerifier();
- assertNotNull("Default hostname verifyer is null", verifyer);
- }
-
- /**
- * @tests javax.net.ssl.HttpsURLConnection#getDefaultSSLSocketFactory()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDefaultSSLSocketFactory",
- args = {}
- )
- public final void test_getDefaultSSLSocketFactory() {
- SSLSocketFactory sf = HttpsURLConnection.getDefaultSSLSocketFactory();
- if (!sf.equals(SSLSocketFactory.getDefault())) {
- fail("incorrect DefaultSSLSocketFactory");
- }
- }
-
- /**
- * @tests javax.net.ssl.HttpsURLConnection#getHostnameVerifier()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getHostnameVerifier",
- args = {}
- )
- public final void test_getHostnameVerifier()
- throws Exception {
- HttpsURLConnection con = new MyHttpsURLConnection(
- new URL("https://www.fortify.net/"));
- HostnameVerifier verifyer = con.getHostnameVerifier();
- assertNotNull("Hostname verifyer is null", verifyer);
- assertEquals("Incorrect value of hostname verirfyer",
- HttpsURLConnection.getDefaultHostnameVerifier(), verifyer);
- }
-
- /**
- * @tests javax.net.ssl.HttpsURLConnection#getLocalPrincipal()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocalPrincipal",
- args = {}
- )
- public final void test_getLocalPrincipal() {
- try {
- URL url = new URL("https://localhost:55555");
- HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
- try {
- connection.getLocalPrincipal();
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException ise) {
- //expected
- }
- } catch (Exception e) {
- fail("Unexpected exception " + e + " for exception case");
- }
-
- try {
- HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508");
- assertNull(con.getLocalPrincipal());
- con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509");
- assertNotNull("Local principal is null", con.getLocalPrincipal());
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
- }
-
- /**
- * @tests javax.net.ssl.HttpsURLConnection#getPeerPrincipal()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPeerPrincipal",
- args = {}
- )
- public final void test_getPeerPrincipal() throws Exception {
- try {
- URL url = new URL("https://localhost:55555");
- HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
- try {
- connection.getPeerPrincipal();
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException ise) {
- //expected
- }
- } catch (Exception e) {
- fail("Unexpected exception " + e + " for exception case");
- }
- HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508");
- try {
- Principal p = con.getPeerPrincipal();
- fail("SSLPeerUnverifiedException wasn't thrown");
- } catch (SSLPeerUnverifiedException e) {
- //expected
- }
-
- con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509");
- try {
- Principal p = con.getPeerPrincipal();
- assertNotNull(p);
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
- }
-
- /**
- * @tests javax.net.ssl.HttpsURLConnection#getServerCertificates()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getServerCertificates",
- args = {}
- )
- public final void test_getServerCertificates() throws Exception {
- try {
- URL url = new URL("https://localhost:55555");
- HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
- try {
- connection.getServerCertificates();
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException ise) {
- //expected
- }
- } catch (Exception e) {
- fail("Unexpected exception " + e + " for exception case");
- }
-
- HttpsURLConnection con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.508");
- try {
- Certificate[] cert = con.getServerCertificates();
- fail("SSLPeerUnverifiedException wasn't thrown");
- } catch (SSLPeerUnverifiedException e) {
- //expected
- }
-
- con = new MyHttpsURLConnection(new URL("https://www.fortify.net/"), "X.509");
- try {
- Certificate[] cert = con.getServerCertificates();
- assertNotNull(cert);
- assertEquals(1, cert.length);
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
- }
-
- /**
- * @tests javax.net.ssl.HttpsURLConnection#getSSLSocketFactory()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSSLSocketFactory",
- args = {}
- )
- public final void test_getSSLSocketFactory() {
- HttpsURLConnection con = new MyHttpsURLConnection(null);
- SSLSocketFactory sf = con.getSSLSocketFactory();
- if (!sf.equals(SSLSocketFactory.getDefault())) {
- fail("incorrect DefaultSSLSocketFactory");
- }
- }
-
- /**
- * @tests javax.net.ssl.HttpsURLConnection#setDefaultHostnameVerifier()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setDefaultHostnameVerifier",
- args = {javax.net.ssl.HostnameVerifier.class}
- )
- public final void test_setDefaultHostnameVerifier() {
- try {
- HttpsURLConnection.setDefaultHostnameVerifier(null);
- fail("No expected IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- myHostnameVerifier hnv = new myHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
- }
-
- /**
- * @tests javax.net.ssl.HttpsURLConnection#setHostnameVerifier()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setHostnameVerifier",
- args = {javax.net.ssl.HostnameVerifier.class}
- )
- public final void test_setHostnameVerifier() {
- HttpsURLConnection con = new MyHttpsURLConnection(null);
- try {
- con.setHostnameVerifier(null);
- fail("No expected IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- }
- try {
- myHostnameVerifier hnv = new myHostnameVerifier();
- con.setHostnameVerifier(hnv);
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
- }
-
- /**
- * @tests javax.net.ssl.HttpsURLConnection#setDefaultSSLSocketFactory()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setDefaultSSLSocketFactory",
- args = {javax.net.ssl.SSLSocketFactory.class}
- )
- public final void test_setDefaultSSLSocketFactory() {
- try {
- HttpsURLConnection.setDefaultSSLSocketFactory(null);
- fail("No expected IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- }
- try {
- SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory
- .getDefault();
- HttpsURLConnection.setDefaultSSLSocketFactory(ssf);
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
- }
-
- /**
- * @tests javax.net.ssl.HttpsURLConnection#setSSLSocketFactory()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setSSLSocketFactory",
- args = {javax.net.ssl.SSLSocketFactory.class}
- )
- public final void test_setSSLSocketFactory() {
- HttpsURLConnection con = new MyHttpsURLConnection(null);
- try {
- con.setSSLSocketFactory(null);
- fail("No expected IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- }
- try {
- SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory
- .getDefault();
- con.setSSLSocketFactory(ssf);
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
- }
-}
-
-class MyHttpsURLConnection extends javax.net.ssl.HttpsURLConnection {
-
- private String typeDone;
-
- public MyHttpsURLConnection(URL url) {
- super(url);
- }
-
- public MyHttpsURLConnection(URL url, String type) {
- super(url);
- typeDone = type;
- }
-
- /*
- * @see javax.net.ssl.HttpsURLConnection#getCipherSuite()
- */
- public String getCipherSuite() {
- return "CipherSuite";
- }
-
- /*
- * @see javax.net.ssl.HttpsURLConnection#getLocalCertificates()
- */
- public Certificate[] getLocalCertificates() {
- Certificate cert = null;
- try {
- CertificateFactory cf = CertificateFactory.getInstance(typeDone);
- byte[] barr = TestUtils.getX509Certificate_v1();
- ByteArrayInputStream bis = new ByteArrayInputStream(barr);
- cert = cf.generateCertificate(bis);
- } catch (CertificateException se) {
- cert = null;
- }
- return cert == null ? null : new Certificate[]{cert};
- }
-
- /*
- * @see javax.net.ssl.HttpsURLConnection#getServerCertificates()
- */
- public Certificate[] getServerCertificates() throws SSLPeerUnverifiedException {
- Certificate cert = null;
- try {
- CertificateFactory cf = CertificateFactory.getInstance(typeDone);
- byte[] barr = TestUtils.getX509Certificate_v3();
- ByteArrayInputStream bis = new ByteArrayInputStream(barr);
- cert = cf.generateCertificate(bis);
- } catch (CertificateException se) {
- throw new SSLPeerUnverifiedException("No server's end-entity certificate");
- }
- return cert == null ? null : new Certificate[]{cert};
- }
-
- /*
- * @see java.net.HttpURLConnection#disconnect()
- */
- public void disconnect() {
- }
-
- /*
- * @see java.net.HttpURLConnection#usingProxy()
- */
- public boolean usingProxy() {
- return false;
- }
-
- public void connect() {
- }
-
-}
-
-class myHostnameVerifier implements HostnameVerifier {
-
- myHostnameVerifier() {
- }
-
- public boolean verify(String hostname, SSLSession session) {
- if (hostname == session.getPeerHost()) {
- return true;
- } else return false;
- }
-}
-
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/KeyManagerFactory1Test.java b/x-net/src/test/java/tests/api/javax/net/ssl/KeyManagerFactory1Test.java
deleted file mode 100644
index f2a4d1c..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/KeyManagerFactory1Test.java
+++ /dev/null
@@ -1,634 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.KnownFailure;
-
-import java.io.IOException;
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.Provider;
-import java.security.Security;
-import java.security.UnrecoverableKeyException;
-import java.security.cert.CertificateException;
-
-import javax.net.ssl.KeyStoreBuilderParameters;
-import javax.net.ssl.ManagerFactoryParameters;
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.KeyManagerFactorySpi;
-
-import org.apache.harmony.security.tests.support.SpiEngUtils;
-import org.apache.harmony.xnet.tests.support.MyKeyManagerFactorySpi;
-
-import junit.framework.TestCase;
-
-/**
- * Tests for <code>KeyManagerFactory</code> class constructors and methods.
- *
- */
-@TestTargetClass(KeyManagerFactory.class)
-public class KeyManagerFactory1Test extends TestCase {
-
- private static final String srvKeyManagerFactory = "KeyManagerFactory";
-
- private static String defaultAlgorithm = null;
-
- private static String defaultProviderName = null;
-
- private static Provider defaultProvider = null;
-
- private static boolean DEFSupported = false;
-
- private static final String NotSupportedMsg = "There is no suitable provider for KeyManagerFactory";
-
- private static final String[] invalidValues = SpiEngUtils.invalidValues;
-
- private static String[] validValues = new String[3];
- static {
- defaultAlgorithm = Security
- .getProperty("ssl.KeyManagerFactory.algorithm");
- if (defaultAlgorithm != null) {
- defaultProvider = SpiEngUtils.isSupport(defaultAlgorithm,
- srvKeyManagerFactory);
- DEFSupported = (defaultProvider != null);
- defaultProviderName = (DEFSupported ? defaultProvider.getName()
- : null);
- validValues[0] = defaultAlgorithm;
- validValues[1] = defaultAlgorithm.toUpperCase();
- validValues[2] = defaultAlgorithm.toLowerCase();
- }
- }
-
- protected KeyManagerFactory[] createKMFac() {
- if (!DEFSupported) {
- fail(defaultAlgorithm + " algorithm is not supported");
- return null;
- }
- KeyManagerFactory[] kMF = new KeyManagerFactory[3];
- try {
- kMF[0] = KeyManagerFactory.getInstance(defaultAlgorithm);
- kMF[1] = KeyManagerFactory.getInstance(defaultAlgorithm,
- defaultProvider);
- kMF[2] = KeyManagerFactory.getInstance(defaultAlgorithm,
- defaultProviderName);
- return kMF;
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
-
- /**
- * @tests avax.net.ssl.KeyManagerFactory#getAlgorithm()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAlgorithm",
- args = {}
- )
- public void test_getAlgorithm()
- throws NoSuchAlgorithmException, NoSuchProviderException {
- if (!DEFSupported) fail(NotSupportedMsg);
- assertEquals("Incorrect algorithm",
- defaultAlgorithm,
- KeyManagerFactory
- .getInstance(defaultAlgorithm).getAlgorithm());
- assertEquals("Incorrect algorithm",
- defaultAlgorithm,
- KeyManagerFactory
- .getInstance(defaultAlgorithm, defaultProviderName)
- .getAlgorithm());
- assertEquals("Incorrect algorithm",
- defaultAlgorithm,
- KeyManagerFactory.getInstance(defaultAlgorithm, defaultProvider)
- .getAlgorithm());
- }
-
- /**
- * Test for <code>getDefaultAlgorithm()</code> method
- * Assertion: returns value which is specifoed in security property
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDefaultAlgorithm",
- args = {}
- )
- public void test_getDefaultAlgorithm() {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- String def = KeyManagerFactory.getDefaultAlgorithm();
- if (defaultAlgorithm == null) {
- assertNull("DefaultAlgorithm must be null", def);
- } else {
- assertEquals("Invalid default algorithm", def, defaultAlgorithm);
- }
- String defA = "Proba.keymanagerfactory.defaul.type";
- Security.setProperty("ssl.KeyManagerFactory.algorithm", defA);
- assertEquals("Incorrect defaultAlgorithm",
- KeyManagerFactory.getDefaultAlgorithm(), defA);
- if (def == null) {
- def = "";
- }
- Security.setProperty("ssl.KeyManagerFactory.algorithm", def);
- assertEquals("Incorrect defaultAlgorithm",
- KeyManagerFactory.getDefaultAlgorithm(), def);
- }
-
- /**
- * Test for <code>getInstance(String algorithm)</code> method
- * Assertions:
- * returns security property "ssl.KeyManagerFactory.algorithm";
- * returns instance of KeyManagerFactory
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class}
- )
- public void test_getInstanceLjava_lang_String01() throws NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- KeyManagerFactory keyMF;
- for (int i = 0; i < validValues.length; i++) {
- keyMF = KeyManagerFactory.getInstance(validValues[i]);
- assertNotNull("No KeyManagerFactory created", keyMF);
- assertEquals("Invalid algorithm", keyMF.getAlgorithm(),
- validValues[i]);
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm)</code> method
- * Assertion:
- * throws NullPointerException when algorithm is null;
- * throws NoSuchAlgorithmException when algorithm is not correct;
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class}
- )
- public void test_getInstanceLjava_lang_String02() {
- try {
- KeyManagerFactory.getInstance(null);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- KeyManagerFactory.getInstance(invalidValues[i]);
- fail("NoSuchAlgorithmException was not thrown as expected for algorithm: "
- .concat(invalidValues[i]));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, String provider)</code>
- * method
- * Assertion: throws IllegalArgumentException when provider is null or empty
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_lang_String01() throws NoSuchProviderException,
- NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- String provider = null;
- for (int i = 0; i < validValues.length; i++) {
- try {
- KeyManagerFactory.getInstance(validValues[i], provider);
- fail("Expected IllegalArgumentException was not thrown for null provider");
- } catch (IllegalArgumentException e) {
- }
- try {
- KeyManagerFactory.getInstance(validValues[i], "");
- fail("Expected IllegalArgumentException was not thrown for empty provider");
- } catch (IllegalArgumentException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, String provider)</code>
- * method
- * Assertion:
- * throws NullPointerException when algorithm is null;
- * throws NoSuchAlgorithmException when algorithm is not correct;
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_lang_String02() throws NoSuchProviderException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- try {
- KeyManagerFactory.getInstance(null, defaultProviderName);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- KeyManagerFactory.getInstance(invalidValues[i],
- defaultProviderName);
- fail("NoSuchAlgorithmException must be thrown (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, String provider)</code>
- * method
- * Assertion: throws NoSuchProviderException when provider has
- * invalid value
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_lang_String03()
- throws NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- for (int i = 0; i < validValues.length; i++) {
- for (int j = 1; j < invalidValues.length; j++) {
- try {
- KeyManagerFactory.getInstance(validValues[i],
- invalidValues[j]);
- fail("NuSuchProviderException must be thrown (algorithm: "
- + validValues[i] + " provider: " + invalidValues[j]
- + ")");
- } catch (NoSuchProviderException e) {
- }
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, String provider)</code>
- * method Assertion: returns instance of KeyManagerFactory
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_lang_String04()
- throws NoSuchProviderException,
- NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- KeyManagerFactory kMF;
- for (int i = 0; i < validValues.length; i++) {
- kMF = KeyManagerFactory.getInstance(validValues[i],
- defaultProviderName);
- assertNotNull("No KeyManagerFactory created", kMF);
- assertEquals("Incorrect algorithm", kMF.getAlgorithm(),
- validValues[i]);
- assertEquals("Incorrect provider", kMF.getProvider().getName(),
- defaultProviderName);
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, Provider provider)</code>
- * method
- * Assertion: throws IllegalArgumentException when provider is null
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.security.Provider.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_security_Provider01()
- throws NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- Provider provider = null;
- for (int i = 0; i < validValues.length; i++) {
- try {
- KeyManagerFactory.getInstance(validValues[i], provider);
- fail("Expected IllegalArgumentException was not thrown when provider is null");
- } catch (IllegalArgumentException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, Provider provider)</code>
- * method
- * Assertion:
- * throws NullPointerException when algorithm is null;
- * throws NoSuchAlgorithmException when algorithm is not correct;
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.security.Provider.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_security_Provider02() {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- try {
- KeyManagerFactory.getInstance(null, defaultProvider);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- KeyManagerFactory
- .getInstance(invalidValues[i], defaultProvider);
- fail("Expected NuSuchAlgorithmException was not thrown");
- } catch (NoSuchAlgorithmException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, Provider provider)</code>
- * method
- * Assertion: returns instance of KeyManagerFactory
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.security.Provider.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_security_Provider03()
- throws NoSuchAlgorithmException,
- IllegalArgumentException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- KeyManagerFactory kMF;
- for (int i = 0; i < validValues.length; i++) {
- kMF = KeyManagerFactory
- .getInstance(validValues[i], defaultProvider);
- assertNotNull("No KeyManagerFactory created", kMF);
- assertEquals(kMF.getAlgorithm(), validValues[i]);
- assertEquals(kMF.getProvider(), defaultProvider);
- }
- }
-
- /**
- * Test for <code>KeyManagerFactory</code> constructor
- * Assertion: returns KeyManagerFactory object
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "KeyManagerFactory",
- args = {javax.net.ssl.KeyManagerFactorySpi.class, java.security.Provider.class, java.lang.String.class}
- )
- public void test_Constructor() throws NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- KeyManagerFactorySpi spi = new MyKeyManagerFactorySpi();
- KeyManagerFactory keyMF = new myKeyManagerFactory(spi, defaultProvider,
- defaultAlgorithm);
- assertEquals("Incorrect algorithm", keyMF.getAlgorithm(),
- defaultAlgorithm);
- assertEquals("Incorrect provider", keyMF.getProvider(), defaultProvider);
- try {
- keyMF.init(null, new char[1]);
- fail("UnrecoverableKeyException must be thrown");
- } catch (UnrecoverableKeyException e) {
- } catch (Exception e) {
- fail("Unexpected: "+e.toString()+" was thrown");
- }
- keyMF = new myKeyManagerFactory(null, null, null);
- assertNull("Aalgorithm must be null", keyMF.getAlgorithm());
- assertNull("Provider must be null", keyMF.getProvider());
- try {
- keyMF.getKeyManagers();
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * @tests avax.net.ssl.KeyManagerFactory#getKeyManagers()
- * @throws NoSuchAlgorithmException
- * @throws KeyStoreException
- * @throws IOException
- * @throws CertificateException
- * @throws UnrecoverableKeyException
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getKeyManagers",
- args = {}
- )
- public void test_getKeyManagers()
- throws Exception {
- if (!DEFSupported) fail(NotSupportedMsg);
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm);
- char[] pass = "password".toCharArray();
- kmf.init(null, pass);
- assertNotNull("Key manager array is null", kmf.getKeyManagers());
- assertEquals("Incorrect size of array",
- 1, kmf.getKeyManagers().length);
- }
-
- /**
- * @tests avax.net.ssl.KeyManagerFactory#getProvider()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getProvider",
- args = {}
- )
- public void test_getProvider()
- throws Exception {
- if (!DEFSupported) fail(NotSupportedMsg);
- assertEquals("Incorrect provider",
- defaultProvider,
- KeyManagerFactory
- .getInstance(defaultAlgorithm).getProvider());
- assertEquals("Incorrect provider",
- defaultProvider,
- KeyManagerFactory
- .getInstance(defaultAlgorithm, defaultProviderName)
- .getProvider());
- assertEquals("Incorrect provider",
- defaultProvider,
- KeyManagerFactory.getInstance(defaultAlgorithm, defaultProvider)
- .getProvider());
- }
-
- /**
- * Test for <code>init(KeyStore keyStore, char[] password)</code> and
- * <code>getKeyManagers()</code>
- * Assertion: returns not empty KeyManager array
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException checking missed",
- method = "init",
- args = {java.security.KeyStore.class, char[].class}
- )
- public void test_initLjava_security_KeyStore$C()
- throws NoSuchAlgorithmException,
- KeyStoreException, UnrecoverableKeyException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- KeyManagerFactory[] keyMF = createKMFac();
- assertNotNull("KeyManagerFactory object were not created", keyMF);
- KeyStore ksNull = null;
- KeyManager[] km;
- for (int i = 0; i < keyMF.length; i++) {
- keyMF[i].init(ksNull, new char[10]);
- km = keyMF[i].getKeyManagers();
- assertNotNull("Result should not be null", km);
- assertTrue("Length of result KeyManager array should not be 0",
- (km.length > 0));
- }
- KeyStore ks;
- try {
- ks = KeyStore.getInstance(KeyStore.getDefaultType());
- ks.load(null, null);
- } catch (KeyStoreException e) {
- fail(e.toString() + "default KeyStore type is not supported");
- return;
- } catch (Exception e) {
- fail("Unexpected: " + e.toString());
- return;
- }
- for (int i = 0; i < keyMF.length; i++) {
- try {
- keyMF[i].init(ks, new char[10]);
- } catch (KeyStoreException e) {
- }
- km = keyMF[i].getKeyManagers();
- assertNotNull("Result has not be null", km);
- assertTrue("Length of result KeyManager array should not be 0",
- (km.length > 0));
- }
-
- }
-
- /**
- * Test for <code>init(ManagerFactoryParameters params)</code>
- * Assertion:
- * throws InvalidAlgorithmParameterException when params is null
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "functionality is not implemented in org.apache.harmony.xnet.provider.jsse.engineInit(ManagerFactoryParameters)",
- method = "init",
- args = {javax.net.ssl.ManagerFactoryParameters.class}
- )
- public void test_initLjavax_net_ssl_ManagerFactoryParameters()
- throws NoSuchAlgorithmException {
-
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- ManagerFactoryParameters par = null;
- KeyManagerFactory[] keyMF = createKMFac();
- assertNotNull("KeyManagerFactory object were not created", keyMF);
- for (int i = 0; i < keyMF.length; i++) {
- try {
- keyMF[i].init(par);
- fail("InvalidAlgorithmParameterException must be thrown");
- } catch (InvalidAlgorithmParameterException e) {
- }
- }
-
- KeyStore.ProtectionParameter pp = new ProtectionParameterImpl();
- KeyStore.Builder bld = KeyStore.Builder.newInstance("testType", null, pp);
- assertNotNull("Null object KeyStore.Builder", bld);
-
- try {
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm);
- KeyStoreBuilderParameters ksp = new KeyStoreBuilderParameters(bld);
- assertNotNull(ksp.getParameters());
- kmf.init(ksp);
- fail("InvalidAlgorithmParameterException must be thrown");
- } catch (InvalidAlgorithmParameterException e) {
- }
- }
-
-}
-
-/**
- * Additional class for KeyManagerFactory constructor verification
- */
-class myKeyManagerFactory extends KeyManagerFactory {
- public myKeyManagerFactory(KeyManagerFactorySpi spi, Provider prov,
- String alg) {
- super(spi, prov, alg);
- }
-}
-
-class ProtectionParameterImpl implements KeyStore.ProtectionParameter {
- ProtectionParameterImpl(){}
-} \ No newline at end of file
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/KeyManagerFactory2Test.java b/x-net/src/test/java/tests/api/javax/net/ssl/KeyManagerFactory2Test.java
deleted file mode 100644
index f25b3ab..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/KeyManagerFactory2Test.java
+++ /dev/null
@@ -1,287 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.Provider;
-import java.security.Security;
-import java.security.UnrecoverableKeyException;
-
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.ManagerFactoryParameters;
-
-import org.apache.harmony.security.tests.support.SpiEngUtils;
-import org.apache.harmony.xnet.tests.support.MyKeyManagerFactorySpi;
-import junit.framework.TestCase;
-
-/**
- * Tests for KeyManagerFactory class constructors and methods
- *
- */
-@TestTargetClass(KeyManagerFactory.class)
-public class KeyManagerFactory2Test extends TestCase {
- private static final String srvKeyManagerFactory = "KeyManagerFactory";
-
- private static final String defaultAlg = "KeyMF";
-
- private static final String KeyManagerFactoryProviderClass = "org.apache.harmony.xnet.tests.support.MyKeyManagerFactorySpi";
-
- private static final String[] invalidValues = SpiEngUtils.invalidValues;
-
- private static final String[] validValues;
-
- static {
- validValues = new String[4];
- validValues[0] = defaultAlg;
- validValues[1] = defaultAlg.toLowerCase();
- validValues[2] = "Keymf";
- validValues[3] = "kEYMF";
- }
-
- Provider mProv;
-
- protected void setUp() throws Exception {
- super.setUp();
- mProv = (new SpiEngUtils()).new MyProvider("MyKMFProvider",
- "Provider for testing", srvKeyManagerFactory.concat(".")
- .concat(defaultAlg), KeyManagerFactoryProviderClass);
- Security.insertProviderAt(mProv, 2);
- }
-
- /*
- * @see TestCase#tearDown()
- */
- protected void tearDown() throws Exception {
- super.tearDown();
- Security.removeProvider(mProv.getName());
- }
-
- private void checkResult(KeyManagerFactory keyMF)
- throws Exception {
- KeyStore kStore = null;
- ManagerFactoryParameters mfp = null;
-
- char[] pass = { 'a', 'b', 'c' };
-
- try {
- keyMF.init(kStore, null);
- fail("KeyStoreException must be thrown");
- } catch (KeyStoreException e) {
- }
- try {
- keyMF.init(kStore, pass);
- fail("UnrecoverableKeyException must be thrown");
- } catch (UnrecoverableKeyException e) {
- }
- try {
- keyMF.init(mfp);
- fail("InvalidAlgorithmParameterException must be thrown");
- } catch (InvalidAlgorithmParameterException e) {
- }
- assertNull("getKeyManagers() should return null object", keyMF
- .getKeyManagers());
-
- try {
- kStore = KeyStore.getInstance(KeyStore.getDefaultType());
- kStore.load(null, null);
- } catch (KeyStoreException e) {
- fail("default keystore is not supported");
- return;
- }
- keyMF.init(kStore, pass);
-
- mfp = new MyKeyManagerFactorySpi.Parameters(kStore, null);
- try {
- keyMF.init(mfp);
- fail("InvalidAlgorithmParameterException must be thrown");
- } catch (InvalidAlgorithmParameterException e) {
- }
- mfp = new MyKeyManagerFactorySpi.Parameters(kStore, pass);
- keyMF.init(mfp);
- }
- /**
- * Test for <code>getInstance(String algorithm)</code> method
- * Assertions:
- * throws NullPointerException when algorithm is null;
- * throws NoSuchAlgorithmException when algorithm is not correct;
- * returns KeyManagerFactory object
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class}
- )
- public void test_getInstanceLjava_lang_String() throws Exception {
- try {
- KeyManagerFactory.getInstance(null);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- KeyManagerFactory.getInstance(invalidValues[i]);
- fail("NoSuchAlgorithmException must be thrown (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- KeyManagerFactory keyMF;
- for (int i = 0; i < validValues.length; i++) {
- keyMF = KeyManagerFactory.getInstance(validValues[i]);
- assertEquals("Incorrect algorithm", keyMF.getAlgorithm(),
- validValues[i]);
- assertEquals("Incorrect provider", keyMF.getProvider(), mProv);
- checkResult(keyMF);
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, String provider)</code>
- * method
- * Assertions:
- * throws NullPointerException when algorithm is null;
- * throws NoSuchAlgorithmException when algorithm is not correct;
- * throws IllegalArgumentException when provider is null or empty;
- * throws NoSuchProviderException when provider is available;
- * returns KeyManagerFactory object
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_lang_String()
- throws Exception
- {
- try {
- KeyManagerFactory.getInstance(null, mProv.getName());
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- KeyManagerFactory
- .getInstance(invalidValues[i], mProv.getName());
- fail("NoSuchAlgorithmException must be thrown (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- String prov = null;
- for (int i = 0; i < validValues.length; i++) {
- try {
- KeyManagerFactory.getInstance(validValues[i], prov);
- fail("IllegalArgumentException must be thrown when provider is null (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (IllegalArgumentException e) {
- }
- try {
- KeyManagerFactory.getInstance(validValues[i], "");
- fail("IllegalArgumentException must be thrown when provider is empty (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (IllegalArgumentException e) {
- }
- }
- for (int i = 0; i < validValues.length; i++) {
- for (int j = 1; j < invalidValues.length; j++) {
- try {
- KeyManagerFactory.getInstance(validValues[i],
- invalidValues[j]);
- fail("NoSuchProviderException must be thrown (algorithm: "
- .concat(invalidValues[i]).concat(" provider: ")
- .concat(invalidValues[j]).concat(")"));
- } catch (NoSuchProviderException e) {
- }
- }
- }
- KeyManagerFactory keyMF;
- for (int i = 0; i < validValues.length; i++) {
- keyMF = KeyManagerFactory.getInstance(validValues[i], mProv
- .getName());
- assertEquals("Incorrect algorithm", keyMF.getAlgorithm(),
- validValues[i]);
- assertEquals("Incorrect provider", keyMF.getProvider().getName(),
- mProv.getName());
- checkResult(keyMF);
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, Provider provider)</code>
- * method
- * Assertions:
- * throws NullPointerException when algorithm is null;
- * throws NoSuchAlgorithmException when algorithm is not correct;
- * throws IllegalArgumentException when provider is null;
- * returns KeyManagerFactory object
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.security.Provider.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_security_Provider()
- throws Exception
- {
- try {
- KeyManagerFactory.getInstance(null, mProv);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- KeyManagerFactory.getInstance(invalidValues[i], mProv);
- fail("NoSuchAlgorithmException must be thrown (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- Provider prov = null;
- for (int i = 0; i < validValues.length; i++) {
- try {
- KeyManagerFactory.getInstance(validValues[i], prov);
- fail("IllegalArgumentException must be thrown when provider is null (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (IllegalArgumentException e) {
- }
- }
- KeyManagerFactory keyMF;
- for (int i = 0; i < validValues.length; i++) {
- keyMF = KeyManagerFactory.getInstance(validValues[i], mProv);
- assertEquals("Incorrect algorithm", keyMF.getAlgorithm(),
- validValues[i]);
- assertEquals("Incorrect provider", keyMF.getProvider(), mProv);
- checkResult(keyMF);
- }
- }
-} \ No newline at end of file
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/KeyManagerFactorySpiTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/KeyManagerFactorySpiTest.java
deleted file mode 100644
index 2319769..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/KeyManagerFactorySpiTest.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.UnrecoverableKeyException;
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactorySpi;
-import javax.net.ssl.ManagerFactoryParameters;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.xnet.tests.support.KeyManagerFactorySpiImpl;
-
-@TestTargetClass(KeyManagerFactorySpi.class)
-public class KeyManagerFactorySpiTest extends TestCase {
-
- /**
- * @tests javax.net.ssl.KeyManagerFactorySpi#KeyManagerFactorySpi()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "KeyManagerFactorySpi",
- args = {}
- )
- public void test_Constructor() {
- try {
- KeyManagerFactorySpiImpl kmf = new KeyManagerFactorySpiImpl();
- assertTrue(kmf instanceof KeyManagerFactorySpi);
- } catch (Exception e) {
- fail("Unexpected Exception " + e.toString());
- }
- }
-
- /**
- * @tests javax.net.ssl.KeyManagerFactorySpi#KengineInit(KeyStore ks, char[] password)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "engineInit",
- args = {java.security.KeyStore.class, char[].class}
- )
- public void test_engineInit_01() {
- KeyManagerFactorySpiImpl kmf = new KeyManagerFactorySpiImpl();
- KeyStore ks;
- char[] psw = "password".toCharArray();
-
- try {
- kmf.engineInit(null, null);
- fail("NoSuchAlgorithmException wasn't thrown");
- } catch (NoSuchAlgorithmException kse) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of NoSuchAlgorithmException");
- }
-
- try {
- kmf.engineInit(null, psw);
- fail("KeyStoreException wasn't thrown");
- } catch (KeyStoreException uke) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of KeyStoreException");
- }
-
- try {
- ks = KeyStore.getInstance(KeyStore.getDefaultType());
- kmf.engineInit(ks, null);
- fail("UnrecoverableKeyException wasn't thrown");
- } catch (UnrecoverableKeyException uke) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of UnrecoverableKeyException");
- }
-
- try {
- KeyStore kst = KeyStore.getInstance(KeyStore.getDefaultType());
- kst.load(null, null);
- kmf.engineInit(kst, psw);
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
- }
-
- /**
- * @tests javax.net.ssl.KeyManagerFactorySpi#KengineInit(ManagerFactoryParameters spec)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "engineInit",
- args = {javax.net.ssl.ManagerFactoryParameters.class}
- )
- public void test_engineInit_02() {
- KeyManagerFactorySpiImpl kmf = new KeyManagerFactorySpiImpl();
-
- try {
- kmf.engineInit(null);
- fail("InvalidAlgorithmParameterException wasn't thrown");
- } catch (InvalidAlgorithmParameterException iape) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of InvalidAlgorithmParameterException");
- }
-
- try {
- char[] psw = "password".toCharArray();
- Parameters pr = new Parameters(psw);
- kmf.engineInit(pr);
- } catch (Exception e) {
- fail(e + " unexpected exception was thrown");
- }
- }
-
- /**
- * @tests javax.net.ssl.KeyManagerFactorySpi#engineGetKeyManagers()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "engineGetKeyManagers",
- args = {}
- )
- public void test_engineGetKeyManagers() {
- KeyManagerFactorySpiImpl kmf = new KeyManagerFactorySpiImpl();
-
- try {
- KeyManager[] km = kmf.engineGetKeyManagers();
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException ise) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalStateException");
- }
-
- try {
- char[] psw = "password".toCharArray();
- Parameters pr = new Parameters(psw);
- kmf.engineInit(pr);
- KeyManager[] km = kmf.engineGetKeyManagers();
- assertNull("Object is not NULL", km);
- } catch (Exception e) {
- fail(e + " unexpected exception was thrown");
- }
- }
-
- public class Parameters implements ManagerFactoryParameters {
- private char[] passWD;
-
- public Parameters (char[] pass) {
- this.passWD = pass;
- }
- public char[] getPassword() {
- return passWD;
- }
- }
-
-}
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/KeyStoreBuilderParametersTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/KeyStoreBuilderParametersTest.java
deleted file mode 100644
index 613e701..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/KeyStoreBuilderParametersTest.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import javax.net.ssl.KeyManagerFactorySpi;
-import javax.net.ssl.KeyStoreBuilderParameters;
-import java.security.KeyStore;
-import java.util.ArrayList;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(KeyStoreBuilderParameters.class)
-public class KeyStoreBuilderParametersTest extends TestCase {
-
- /**
- * @tests javax.net.ssl.KeyStoreBuilderParameters#KeyStoreBuilderParameters(KeyStore.Builder builder)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "KeyStoreBuilderParameters",
- args = {java.security.KeyStore.Builder.class}
- )
- public void test_Constructor01() {
- KeyStore.Builder bld = null;
-
- //Null parameter
- try {
- KeyStoreBuilderParameters ksp = new KeyStoreBuilderParameters(bld);
- assertNotNull(ksp.getParameters());
- } catch (NullPointerException npe) {
- fail("NullPointerException should not be thrown");
- }
-
- //Not null parameter
- KeyStore.ProtectionParameter pp = new ProtectionParameterImpl();
- bld = KeyStore.Builder.newInstance("testType", null, pp);
- assertNotNull("Null object KeyStore.Builder", bld);
- try {
- KeyStoreBuilderParameters ksp = new KeyStoreBuilderParameters(bld);
- assertNotNull(ksp.getParameters());
- } catch (Exception e) {
- fail("Unexpected exception was thrown");
- }
- }
-
- /**
- * @tests javax.net.ssl.KeyStoreBuilderParameters#KeyStoreBuilderParameters(List parameters)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "KeyStoreBuilderParameters",
- args = {java.util.List.class}
- )
- public void test_Constructor02() {
-
- //Null parameter
- List<String> ls = null;
- try {
- KeyStoreBuilderParameters ksp = new KeyStoreBuilderParameters(ls);
- fail("NullPointerException should be thrown");
- } catch (NullPointerException npe) {
- //expected
- }
-
- //Empty parameter
- List<String> lsEmpty = new ArrayList<String>();
- try {
- KeyStoreBuilderParameters ksp = new KeyStoreBuilderParameters(lsEmpty);
- fail("IllegalArgumentException should be thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- }
-
- //Not null parameter
- List<String> lsFiled = new ArrayList<String>();;
- lsFiled.add("Parameter1");
- lsFiled.add("Parameter2");
- try {
- KeyStoreBuilderParameters ksp = new KeyStoreBuilderParameters(lsFiled);
- assertTrue("Not instanceof KeyStoreBuilderParameters object",
- ksp instanceof KeyStoreBuilderParameters);
- } catch (Exception e) {
- fail("Unexpected exception was thrown");
- }
- }
-
- /**
- * @tests javax.net.ssl.KeyStoreBuilderParameters#getParameters()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getParameters",
- args = {}
- )
- public void test_getParameters() {
- String[] param = {"Parameter1", "Parameter2", "Parameter3"};
- List<String> ls = new ArrayList<String>();
- for (int i = 0; i < param.length; i++) {
- ls.add(param[i]);
- }
- KeyStoreBuilderParameters ksp = new KeyStoreBuilderParameters(ls);
- try {
- List<String> res_list = ksp.getParameters();
- try {
- res_list.add("test");
- } catch (UnsupportedOperationException e) {
- // expected
- }
- Object[] res = res_list.toArray();
- if (res.length == param.length) {
- for (int i = 0; i < res.length; i++) {
- if (!param[i].equals(res[i])) {
- fail("Parameters not equal");
- }
- }
- } else {
- fail("Incorrect number of parameters");
- }
- } catch (Exception e) {
- fail("Unexpected exception was thrown");
- }
- }
-
- class ProtectionParameterImpl implements KeyStore.ProtectionParameter {
- ProtectionParameterImpl(){}
- }
-}
-
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/SSLContext1Test.java b/x-net/src/test/java/tests/api/javax/net/ssl/SSLContext1Test.java
deleted file mode 100644
index 3929003..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/SSLContext1Test.java
+++ /dev/null
@@ -1,718 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package tests.api.javax.net.ssl;
-
-import java.io.FileNotFoundException;
-import java.security.KeyManagementException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.Provider;
-import java.security.SecureRandom;
-import java.security.UnrecoverableKeyException;
-
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLContextSpi;
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.SSLServerSocketFactory;
-import javax.net.ssl.SSLSessionContext;
-import javax.net.ssl.SSLSocketFactory;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.security.tests.support.SpiEngUtils;
-import org.apache.harmony.xnet.tests.support.MySSLContextSpi;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-/**
- * Tests for <code>SSLContext</code> class constructors and methods.
- *
- */
-@TestTargetClass(SSLContext.class)
-public class SSLContext1Test extends TestCase {
-
- private static String srvSSLContext = "SSLContext";
- public static String defaultProtocol = "TLS";
- private static final String NotSupportMsg = "Default protocol is not supported";
- private static String defaultProviderName = null;
- private static Provider defaultProvider = null;
- private static final String[] invalidValues = SpiEngUtils.invalidValues;
- private static boolean DEFSupported = false;
- private static String[] validValues = new String[3];
- static {
- defaultProvider = SpiEngUtils.isSupport(defaultProtocol, srvSSLContext);
- DEFSupported = (defaultProvider != null);
- if (DEFSupported) {
- defaultProviderName = (DEFSupported ? defaultProvider.getName()
- : null);
- validValues[0] = defaultProtocol;
- validValues[1] = defaultProtocol.toUpperCase();
- validValues[2] = defaultProtocol.toLowerCase();
- } else {
- defaultProtocol = null;
- }
- }
-
- protected SSLContext[] createSSLCon() {
- if (!DEFSupported) {
- fail(defaultProtocol + " protocol is not supported");
- return null;
- }
- SSLContext[] sslC = new SSLContext[3];
- try {
- sslC[0] = SSLContext.getInstance(defaultProtocol);
- sslC[1] = SSLContext.getInstance(defaultProtocol, defaultProvider);
- sslC[2] = SSLContext.getInstance(defaultProtocol,
- defaultProviderName);
- return sslC;
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
-
- /**
- * Test for <code>SSLContext</code> constructor Assertion: returns
- * SSLContext object
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SSLContext",
- args = {javax.net.ssl.SSLContextSpi.class, java.security.Provider.class, java.lang.String.class}
- )
- public void test_ConstructorLjavax_net_ssl_SSLContextSpiLjava_security_ProviderLjava_lang_String()
- throws NoSuchAlgorithmException,
- KeyManagementException {
- if (!DEFSupported) {
- fail(NotSupportMsg);
- return;
- }
- SSLContextSpi spi = new MySSLContextSpi();
- SSLContext sslContext = new MySslContext(spi, defaultProvider,
- defaultProtocol);
- assertEquals("Incorrect protocol", defaultProtocol,
- sslContext.getProtocol());
- assertEquals("Incorrect provider", defaultProvider,
- sslContext.getProvider());
- TrustManager[] tm = null;
- KeyManager[] km = null;
- sslContext.init(km, tm, new SecureRandom());
- assertNotNull("No SSLEngine created",
- sslContext.createSSLEngine());
- assertNotNull("No SSLEngine created",
- sslContext.createSSLEngine("host", 8888));
- try {
- sslContext.init(km, tm, null);
- fail("KeyManagementException should be thrown for null "
- + "SecureRandom");
- } catch (KeyManagementException e) {
- }
-
- sslContext = new MySslContext(null, null, null);
- assertNull("Incorrect protocol", sslContext.getProtocol());
- assertNull("Incorrect provider", sslContext.getProvider());
- try {
- sslContext.createSSLEngine();
- fail("NullPointerException should be thrown");
- } catch (NullPointerException e) {
- }
- try {
- sslContext.getSocketFactory();
- fail("NullPointerException should be thrown");
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * @throws KeyManagementException
- * @tests javax.net.ssl.SSLContext#createSSLEngine()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "UnsupportedOperationException checking missed",
- method = "createSSLEngine",
- args = {}
- )
- public void test_createSSLEngine() throws KeyManagementException {
- if (!DEFSupported) fail(NotSupportMsg);
- SSLContextSpi spi = new MySSLContextSpi();
- SSLContext sslContext = new MySslContext(spi, defaultProvider,
- defaultProtocol);
- sslContext.init(null, null, new SecureRandom());
- SSLEngine sslEngine = sslContext.createSSLEngine();
- assertNotNull("SSL engine is null", sslEngine);
- }
-
- /**
- * @throws KeyManagementException
- * @tests javax.net.ssl.SSLContext#createSSLEngine(java.lang.String, int)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "UnsupportedOperationException checking missed",
- method = "createSSLEngine",
- args = {java.lang.String.class, int.class}
- )
- public void test_createSSLEngineLjava_lang_StringI()
- throws KeyManagementException {
- if (!DEFSupported) fail(NotSupportMsg);
- SSLContextSpi spi = new MySSLContextSpi();
- SSLContext sslContext = new MySslContext(spi, defaultProvider,
- defaultProtocol);
- sslContext.init(null, null, new SecureRandom());
- SSLEngine sslEngine = sslContext.createSSLEngine("www.fortify.net", 80);
- assertNotNull("SSL engine is null", sslEngine);
- }
-
- /**
- * Test for <code>getClientSessionContext()</code>
- * <code>getServiceSessionContext()</code>
- * methods Assertion: returns correspondent object
- * @throws KeyManagementException
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getClientSessionContext",
- args = {}
- )
- public void test_getClientSessionContext() throws NoSuchAlgorithmException, KeyManagementException {
- if (!DEFSupported) {
- fail(NotSupportMsg);
- return;
- }
- SSLContext[] sslC = createSSLCon();
- assertNotNull("SSLContext objects were not created", sslC);
- for (int i = 0; i < sslC.length; i++) {
- sslC[i].init(null, null, null);
- assertNotNull("Client session is incorrectly instantiated: " + i,
- sslC[i].getClientSessionContext());
- assertNotNull("Server session is incorrectly instantiated: " + i,
- sslC[i].getServerSessionContext());
- }
- }
-
- /**
- * Test for <code>getInstance(String protocol)</code> method Assertion:
- * returns SSLContext object
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class}
- )
- public void test_getInstanceLjava_lang_String01()
- throws NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportMsg);
- return;
- }
- SSLContext sslContext;
- for (int i = 0; i < validValues.length; i++) {
- sslContext = SSLContext.getInstance(validValues[i]);
- assertNotNull("No SSLContext created", sslContext);
- assertEquals("Invalid protocol", validValues[i],
- sslContext.getProtocol());
- }
- }
-
- /**
- * Test for <code>getInstance(String protocol)</code> method Assertion:
- * throws NullPointerException when protocol is null; throws
- * NoSuchAlgorithmException when protocol is not correct;
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class}
- )
- public void test_getInstanceLjava_lang_String02() {
- try {
- SSLContext.getInstance(null);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (protocol is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- SSLContext.getInstance(invalidValues[i]);
- fail("NoSuchAlgorithmException was not thrown as expected for provider: "
- .concat(invalidValues[i]));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String protocol, String provider)</code>
- * method Assertion: throws IllegalArgumentException when provider is null
- * or empty
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_lang_String01() throws NoSuchProviderException,
- NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportMsg);
- return;
- }
- String provider = null;
- for (int i = 0; i < validValues.length; i++) {
- try {
- SSLContext.getInstance(defaultProtocol, provider);
- fail("IllegalArgumentException must be thrown when provider is null");
- } catch (IllegalArgumentException e) {
- }
- try {
- SSLContext.getInstance(defaultProtocol, "");
- fail("IllegalArgumentException must be thrown when provider is empty");
- } catch (IllegalArgumentException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String protocol, String provider)</code>
- * method Assertion: throws NullPointerException when protocol is null;
- * throws NoSuchAlgorithmException when protocol is not correct;
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_lang_String02() throws NoSuchProviderException {
- if (!DEFSupported) {
- fail(NotSupportMsg);
- return;
- }
- try {
- SSLContext.getInstance(null, defaultProviderName);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (protocol is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- SSLContext.getInstance(invalidValues[i], defaultProviderName);
- fail("NoSuchAlgorithmException was not thrown as expected (protocol: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String protocol, String provider)</code>
- * method Assertion: throws NoSuchProviderException when provider has
- * invalid value
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_lang_String03() throws NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportMsg);
- return;
- }
- for (int i = 1; i < invalidValues.length; i++) {
- for (int j = 0; j < validValues.length; j++) {
- try {
- SSLContext.getInstance(validValues[j], invalidValues[i]);
- fail("NuSuchProviderException must be thrown (protocol: "
- .concat(validValues[j]).concat(" provider: ")
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchProviderException e) {
- }
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String protocol, String provider)</code>
- * method Assertion: returns instance of SSLContext
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_lang_String04() throws NoSuchAlgorithmException,
- NoSuchProviderException {
- if (!DEFSupported) {
- fail(NotSupportMsg);
- return;
- }
- SSLContext sslContext;
- for (int i = 0; i < validValues.length; i++) {
- sslContext = SSLContext.getInstance(validValues[i],
- defaultProviderName);
- assertNotNull("Not SSLContext created", sslContext);
- assertEquals("Invalid protocol",
- validValues[i], sslContext.getProtocol());
- assertEquals("Invalid provider",
- defaultProvider, sslContext.getProvider());
- }
- }
-
- /**
- * Test for <code>getInstance(String protocol, Provider provider)</code>
- * method Assertion: throws IllegalArgumentException when provider is null
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.security.Provider.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_security_Provider01() throws NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportMsg);
- return;
- }
- Provider provider = null;
- for (int i = 0; i < validValues.length; i++) {
- try {
- SSLContext.getInstance(validValues[i], provider);
- fail("IllegalArgumentException must be thrown when provider is null");
- } catch (IllegalArgumentException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String protocol, Provider provider)</code>
- * method Assertion: throws NullPointerException when protocol is null;
- * throws NoSuchAlgorithmException when protocol is not correct;
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.security.Provider.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_security_Provider02() {
- if (!DEFSupported) {
- fail(NotSupportMsg);
- return;
- }
- try {
- SSLContext.getInstance(null, defaultProvider);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (protocol is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- SSLContext.getInstance(invalidValues[i], defaultProvider);
- fail("Expected NoSuchAlgorithmException was not thrown as expected");
- } catch (NoSuchAlgorithmException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String protocol, Provider provider)</code>
- * method Assertion: returns instance of SSLContext
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.security.Provider.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_security_Provider03() throws NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportMsg);
- return;
- }
- SSLContext sslContext;
- for (int i = 0; i < validValues.length; i++) {
- sslContext = SSLContext
- .getInstance(validValues[i], defaultProvider);
- assertNotNull("Not SSLContext created", sslContext);
- assertEquals("Invalid protocol", validValues[i], sslContext.getProtocol());
- assertEquals("Invalid provider", defaultProvider, sslContext.getProvider());
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @throws NoSuchProviderException
- * @tests javax.net.ssl.SSLContext#getProtocol()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getProtocol",
- args = {}
- )
- public void test_getProtocol()
- throws NoSuchAlgorithmException, NoSuchProviderException {
- if (!DEFSupported) fail(NotSupportMsg);
- SSLContextSpi spi = new MySSLContextSpi();
- SSLContext sslContext = new MySslContext(spi, defaultProvider,
- defaultProtocol);
- assertEquals("Incorrect protocol",
- defaultProtocol, sslContext.getProtocol());
- sslContext = new MySslContext(spi, defaultProvider,
- null);
- assertNull("Incorrect protocol", sslContext.getProtocol());
- sslContext = SSLContext.getInstance(defaultProtocol);
- assertEquals("Incorrect protocol",
- defaultProtocol, sslContext.getProtocol());
- sslContext = SSLContext.getInstance(defaultProtocol, defaultProvider);
- assertEquals("Incorrect protocol",
- defaultProtocol, sslContext.getProtocol());
- sslContext = SSLContext.getInstance(defaultProtocol, defaultProviderName);
- assertEquals("Incorrect protocol",
- defaultProtocol, sslContext.getProtocol());
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @throws NoSuchProviderException
- * @tests javax.net.ssl.SSLContext#getProvider()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getProvider",
- args = {}
- )
- public void test_getProvider()
- throws NoSuchAlgorithmException, NoSuchProviderException {
- if (!DEFSupported) fail(NotSupportMsg);
- SSLContextSpi spi = new MySSLContextSpi();
- SSLContext sslContext = new MySslContext(spi, defaultProvider,
- defaultProtocol);
- assertEquals("Incorrect provider",
- defaultProvider, sslContext.getProvider());
- sslContext = SSLContext.getInstance(defaultProtocol, defaultProvider);
- assertEquals("Incorrect provider",
- defaultProvider, sslContext.getProvider());
- sslContext = SSLContext.getInstance(defaultProtocol, defaultProviderName);
- assertEquals("Incorrect provider",
- defaultProvider, sslContext.getProvider());
- }
-
- /**
- * @tests javax.net.ssl.SSLContext#getServletSessionContext()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getServerSessionContext",
- args = {}
- )
- public void test_getServerSessionContext() throws NoSuchAlgorithmException,
- KeyManagementException, KeyStoreException,
- UnrecoverableKeyException {
- if (!DEFSupported) fail(NotSupportMsg);
- SSLContext[] sslC = createSSLCon();
- assertNotNull("SSLContext objects were not created", sslC);
- String tAlg = TrustManagerFactory.getDefaultAlgorithm();
- String kAlg = KeyManagerFactory.getDefaultAlgorithm();
- if (tAlg == null)
- fail("TrustManagerFactory default algorithm is not defined");
- if (kAlg == null)
- fail("KeyManagerFactory default algorithm is not defined");
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(kAlg);
- kmf.init(null, new char[11]);
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(tAlg);
- KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
- tmf.init(ks);
- TrustManager[] tms = tmf.getTrustManagers();
- for (SSLContext sslCi : sslC) {
- sslCi.init(kmf.getKeyManagers(), tms, new SecureRandom());
- assertNotNull("Server context is incorrectly instantiated", sslCi
- .getServerSessionContext());
- }
- }
-
- /**
- * Test for <code>getServerSocketFactory()</code>
- * <code>getSocketFactory()</code>
- * <code>init(KeyManager[] km, TrustManager[] tm, SecureRandom random)</code>
- * methods Assertion: returns correspondent object
- *
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getServerSocketFactory",
- args = {}
- )
- public void test_getServerSocketFactory() throws NoSuchAlgorithmException,
- KeyManagementException, KeyStoreException,
- UnrecoverableKeyException {
- if (!DEFSupported) {
- fail(NotSupportMsg);
- return;
- }
- SSLContext[] sslC = createSSLCon();
- assertNotNull("SSLContext objects were not created", sslC);
- String tAlg = TrustManagerFactory.getDefaultAlgorithm();
- String kAlg = KeyManagerFactory.getDefaultAlgorithm();
- if (tAlg == null) {
- fail("TrustManagerFactory default algorithm is not defined");
- return;
- }
- if (kAlg == null) {
- fail("KeyManagerFactory default algorithm is not defined");
- return;
- }
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(kAlg);
- KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
- try {
- ks.load(null, null);
- } catch (Exception e) {
- fail(e + " was thrown for method load(null, null)");
- }
- kmf.init(ks, new char[10]);
- KeyManager[] kms = kmf.getKeyManagers();
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(tAlg);
- tmf.init(ks);
- TrustManager[] tms = tmf.getTrustManagers();
- for (int i = 0; i < sslC.length; i++) {
- sslC[i].init(kms, tms, new SecureRandom());
- assertNotNull("No SSLServerSocketFactory available",
- sslC[i].getServerSocketFactory());
- assertNotNull("No SSLSocketFactory available",
- sslC[i].getSocketFactory());
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLContext#getSocketFactory()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSocketFactory",
- args = {}
- )
- public void test_getSocketFactory() throws NoSuchAlgorithmException,
- KeyManagementException, KeyStoreException,
- UnrecoverableKeyException {
- if (!DEFSupported) fail(NotSupportMsg);
- SSLContext[] sslC = createSSLCon();
- assertNotNull("SSLContext objects were not created", sslC);
- String tAlg = TrustManagerFactory.getDefaultAlgorithm();
- String kAlg = KeyManagerFactory.getDefaultAlgorithm();
- if (tAlg == null)
- fail("TrustManagerFactory default algorithm is not defined");
- if (kAlg == null)
- fail("KeyManagerFactory default algorithm is not defined");
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(kAlg);
- kmf.init(null, new char[11]);
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(tAlg);
- KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
- tmf.init(ks);
- TrustManager[] tms = tmf.getTrustManagers();
- for (SSLContext sslCi : sslC) {
- sslCi.init(kmf.getKeyManagers(), tms, new SecureRandom());
- assertNotNull("Socket factory is incorrectly instantiated",
- sslCi.getSocketFactory());
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @throws KeyStoreException
- * @throws FileNotFoundException
- * @throws KeyManagementException
- * @tests javax.net.ssl.SSLContext#
- * init(javax.net.ssl.KeyManager[], javax.net.ssl.TrustManager[],
- * java.security.SecureRandom)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "init",
- args = {javax.net.ssl.KeyManager[].class, javax.net.ssl.TrustManager[].class, java.security.SecureRandom.class}
- )
- public void test_init$Ljavax_net_ssl_KeyManager$Ljavax_net_ssl_TrustManagerLjava_security_SecureRandom()
- throws Exception {
- if (!DEFSupported) fail(NotSupportMsg);
- SSLContextSpi spi = new MySSLContextSpi();
- SSLContext sslContext = new MySslContext(spi, defaultProvider,
- defaultProtocol);
- try {
- sslContext.createSSLEngine();
- fail("Expected RuntimeException was not thrown");
- } catch (RuntimeException rte) {
- // expected
- }
-
- try {
- sslContext.init(null, null, null);
- fail("KeyManagementException wasn't thrown");
- } catch (KeyManagementException kme) {
- //expected
- }
-
- try {
- String tAlg = TrustManagerFactory.getDefaultAlgorithm();
- String kAlg = KeyManagerFactory.getDefaultAlgorithm();
- if (tAlg == null)
- fail("TrustManagerFactory default algorithm is not defined");
- if (kAlg == null)
- fail("KeyManagerFactory default algorithm is not defined");
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(kAlg);
- kmf.init(null, new char[11]);
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(tAlg);
- KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
- tmf.init(ks);
- TrustManager[] tms = tmf.getTrustManagers();
- sslContext.init(kmf.getKeyManagers(), tms, new SecureRandom());
- } catch (Exception e) {
- System.out.println("EE = " + e);
- }
- }
-}
-
-/**
- * Addifional class to verify SSLContext constructor
- */
-
-class MySslContext extends SSLContext {
- public MySslContext(SSLContextSpi spi, Provider prov, String alg) {
- super(spi, prov, alg);
- }
-}
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/SSLContext2Test.java b/x-net/src/test/java/tests/api/javax/net/ssl/SSLContext2Test.java
deleted file mode 100644
index 2ddb1ed..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/SSLContext2Test.java
+++ /dev/null
@@ -1,323 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.security.KeyManagementException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.Provider;
-import java.security.SecureRandom;
-import java.security.Security;
-
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.TrustManager;
-
-import org.apache.harmony.security.tests.support.SpiEngUtils;
-
-import junit.framework.TestCase;
-
-/**
- * Tests for SSLContext class constructors and methods
- *
- */
-@TestTargetClass(SSLContext.class)
-public class SSLContext2Test extends TestCase {
-
- private static String srvSSLContext = "SSLContext";
-
- private static final String defaultProtocol = "S+S+L";
-
- public static final String SSLContextProviderClass = "org.apache.harmony.xnet.tests.support.MySSLContextSpi";
-
- private static final String[] invalidValues = SpiEngUtils.invalidValues;
-
- private static final String[] validValues;
- static {
- validValues = new String[4];
- validValues[0] = defaultProtocol;
- validValues[1] = defaultProtocol.toLowerCase();
- validValues[2] = "s+S+L";
- validValues[3] = "S+s+L";
- }
-
- Provider mProv;
-
- protected void setUp() throws Exception {
- super.setUp();
- mProv = (new SpiEngUtils()).new MyProvider("MySSLContextProvider", "Provider for testing",
- srvSSLContext.concat(".").concat(defaultProtocol),
- SSLContextProviderClass);
- Security.insertProviderAt(mProv, 1);
- }
-
- /*
- * @see TestCase#tearDown()
- */
- protected void tearDown() throws Exception {
- super.tearDown();
- Security.removeProvider(mProv.getName());
- }
-
- private void checkSSLContext(SSLContext sslC)
- throws KeyManagementException {
-
- try {
- sslC.getSocketFactory();
- fail("RuntimeException must be thrown");
- } catch (RuntimeException e) {
- assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
- }
- try {
- sslC.getServerSocketFactory();
- fail("RuntimeException must be thrown");
- } catch (RuntimeException e) {
- assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
- }
- try {
- sslC.getServerSessionContext();
- fail("RuntimeException must be thrown");
- } catch (RuntimeException e) {
- assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
- }
- try {
- sslC.getClientSessionContext();
- fail("RuntimeException must be thrown");
- } catch (RuntimeException e) {
- assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
- }
- try {
- sslC.createSSLEngine();
- fail("RuntimeException must be thrown");
- } catch (RuntimeException e) {
- assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
- }
- try {
- sslC.createSSLEngine("host",1);
- fail("RuntimeException must be thrown");
- } catch (RuntimeException e) {
- assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
- }
- TrustManager [] tm = new TManager[10];
- KeyManager [] km = new KManager[5];
- try {
- sslC.init(km, tm, null);
- fail("KeyManagementException must be thrown");
- } catch (KeyManagementException e) {
- }
- sslC.init(km, tm, new SecureRandom());
-
- SSLEngine sslE = sslC.createSSLEngine();
- assertTrue("Not null result",sslE instanceof SSLEngine);
- assertNull("Incorrect host", sslE.getPeerHost());
- assertEquals("Incorrect port", 0, sslE.getPeerPort());
- String host = "ZZZ";
- int port = 8080;
- sslE = sslC.createSSLEngine(host, port);
- assertTrue("Not null result",sslE instanceof SSLEngine);
- assertEquals("Incorrect host", sslE.getPeerHost(), host);
- assertEquals("Incorrect port", sslE.getPeerPort(), port);
- try {
- assertNull("Not null result", sslC.getServerSessionContext());
- } catch (NullPointerException e) {
- }
- try {
- assertNull("Not null result", sslC.getClientSessionContext());
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * Test for <code>getInstance(String protocol)</code> method
- * Assertions:
- * throws NullPointerException when protocol is null;
- * throws NoSuchAlgorithmException when protocol is not correct;
- * returns SSLContext object
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class}
- )
- public void test_getInstanceLjava_lang_String() throws NoSuchAlgorithmException,
- KeyManagementException {
- try {
- SSLContext.getInstance(null);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (protocol is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- SSLContext.getInstance(invalidValues[i]);
- fail("NoSuchAlgorithmException must be thrown (protocol: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- SSLContext sslC;
- for (int i = 0; i < validValues.length; i++) {
- sslC = SSLContext.getInstance(validValues[i]);
- assertTrue("Not instanceof SSLContext object",
- sslC instanceof SSLContext);
- assertEquals("Incorrect protocol", sslC.getProtocol(),
- validValues[i]);
- assertEquals("Incorrect provider", sslC.getProvider(), mProv);
- checkSSLContext(sslC);
- }
- }
-
- /**
- * Test for <code>getInstance(String protocol, String provider)</code>
- * method
- * Assertions:
- * throws NullPointerException when protocol is null;
- * throws NoSuchAlgorithmException when protocol is not correct;
- * throws IllegalArgumentException when provider is null or empty;
- * throws NoSuchProviderException when provider is available;
- * returns SSLContext object
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_lang_String() throws NoSuchAlgorithmException,
- NoSuchProviderException, IllegalArgumentException,
- KeyManagementException {
- try {
- SSLContext.getInstance(null, mProv.getName());
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (protocol is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- SSLContext.getInstance(invalidValues[i], mProv.getName());
- fail("NoSuchAlgorithmException must be thrown (protocol: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- String prov = null;
- for (int i = 0; i < validValues.length; i++) {
- try {
- SSLContext.getInstance(validValues[i], prov);
- fail("IllegalArgumentException must be thrown when provider is null (protocol: "
- .concat(invalidValues[i]).concat(")"));
- } catch (IllegalArgumentException e) {
- }
- try {
- SSLContext.getInstance(validValues[i], "");
- fail("IllegalArgumentException must be thrown when provider is empty (protocol: "
- .concat(invalidValues[i]).concat(")"));
- } catch (IllegalArgumentException e) {
- }
- }
- for (int i = 0; i < validValues.length; i++) {
- for (int j = 1; j < invalidValues.length; j++) {
- try {
- SSLContext.getInstance(validValues[i], invalidValues[j]);
- fail("NoSuchProviderException must be thrown (protocol: "
- .concat(invalidValues[i]).concat(" provider: ")
- .concat(invalidValues[j]).concat(")"));
- } catch (NoSuchProviderException e) {
- }
- }
- }
- SSLContext sslC;
- for (int i = 0; i < validValues.length; i++) {
- sslC = SSLContext.getInstance(validValues[i], mProv.getName());
- assertTrue("Not instanceof SSLContext object",
- sslC instanceof SSLContext);
- assertEquals("Incorrect protocol", sslC.getProtocol(),
- validValues[i]);
- assertEquals("Incorrect provider", sslC.getProvider().getName(),
- mProv.getName());
- checkSSLContext(sslC);
- }
- }
-
- /**
- * Test for <code>getInstance(String protocol, Provider provider)</code>
- * method
- * Assertions:
- * throws NullPointerException when protocol is null;
- * throws NoSuchAlgorithmException when protocol is not correct;
- * throws IllegalArgumentException when provider is null;
- * returns SSLContext object
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.security.Provider.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_security_Provider()
- throws NoSuchAlgorithmException,
- IllegalArgumentException, KeyManagementException {
- try {
- SSLContext.getInstance(null, mProv);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (protocol is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- SSLContext.getInstance(invalidValues[i], mProv);
- fail("NoSuchAlgorithmException must be thrown (protocol: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- Provider prov = null;
- for (int i = 0; i < validValues.length; i++) {
- try {
- SSLContext.getInstance(validValues[i], prov);
- fail("IllegalArgumentException must be thrown when provider is null (protocol: "
- .concat(invalidValues[i]).concat(")"));
- } catch (IllegalArgumentException e) {
- }
- }
- SSLContext sslC;
- for (int i = 0; i < validValues.length; i++) {
- sslC = SSLContext.getInstance(validValues[i], mProv);
- assertTrue("Not instanceof SSLContext object",
- sslC instanceof SSLContext);
- assertEquals("Incorrect protocol", sslC.getProtocol(),
- validValues[i]);
- assertEquals("Incorrect provider", sslC.getProvider(), mProv);
- checkSSLContext(sslC);
- }
- }
-
- class TManager implements TrustManager {
-
- }
- class KManager implements KeyManager {
-
- }
-} \ No newline at end of file
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/SSLContextSpiTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/SSLContextSpiTest.java
deleted file mode 100644
index cf3123a..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/SSLContextSpiTest.java
+++ /dev/null
@@ -1,323 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContextSpi;
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.SSLServerSocketFactory;
-import javax.net.ssl.SSLSessionContext;
-import javax.net.ssl.SSLSocketFactory;
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
-import java.security.KeyManagementException;
-
-import java.security.KeyStore;
-import java.security.SecureRandom;
-import java.security.Security;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.xnet.tests.support.SSLContextSpiImpl;
-
-@TestTargetClass(SSLContextSpi.class)
-public class SSLContextSpiTest extends TestCase {
-
- /**
- * @tests javax.net.ssl.SSLContextSpi#SSLContextSpi()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SSLContextSpi",
- args = {}
- )
- public void test_Constructor() {
- try {
- SSLContextSpiImpl ssl = new SSLContextSpiImpl();
- assertTrue(ssl instanceof SSLContextSpi);
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLContextSpi#engineCreateSSLEngine()
- * Verify exception when SSLContextSpi object wasn't initialiazed.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "engineCreateSSLEngine",
- args = {}
- )
- public void test_engineCreateSSLEngine_01() {
- SSLContextSpiImpl ssl = new SSLContextSpiImpl();
- try {
- SSLEngine sleng = ssl.engineCreateSSLEngine();
- fail("RuntimeException wasn't thrown");
- } catch (RuntimeException re) {
- String str = re.getMessage();
- if (!str.equals("Not initialiazed"))
- fail("Incorrect exception message: " + str);
- } catch (Exception e) {
- fail("Incorrect exception " + e + " was thrown");
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLContextSpi#engineCreateSSLEngine(String host, int port)
- * Verify exception when SSLContextSpi object wasn't initialiazed.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "engineCreateSSLEngine",
- args = {java.lang.String.class, int.class}
- )
- public void test_engineCreateSSLEngine_02() {
- int[] invalid_port = {Integer.MIN_VALUE, -65535, -1, 65536, Integer.MAX_VALUE};
- SSLContextSpiImpl ssl = new SSLContextSpiImpl();
- try {
- SSLEngine sleng = ssl.engineCreateSSLEngine("localhost", 1080);
- fail("RuntimeException wasn't thrown");
- } catch (RuntimeException re) {
- String str = re.getMessage();
- if (!str.equals("Not initialiazed"))
- fail("Incorrect exception message: " + str);
- } catch (Exception e) {
- fail("Incorrect exception " + e + " was thrown");
- }
-
- for (int i = 0; i < invalid_port.length; i++) {
- try {
- SSLEngine sleng = ssl.engineCreateSSLEngine("localhost", invalid_port[i]);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- }
- }
- }
-
- /**
- * @tests SSLContextSpi#engineGetClientSessionContext()
- * @tests SSLContextSpi#engineGetServerSessionContext()
- * @tests SSLContextSpi#engineGetServerSocketFactory()
- * @tests SSLContextSpi#engineGetSocketFactory()
- * Verify exception when SSLContextSpi object wasn't initialiazed.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "engineGetClientSessionContext",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "engineGetServerSessionContext",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "engineGetServerSocketFactory",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "engineGetSocketFactory",
- args = {}
- )
- })
- public void test_commonTest_01() {
- SSLContextSpiImpl ssl = new SSLContextSpiImpl();
-
- try {
- SSLSessionContext slsc = ssl.engineGetClientSessionContext();
- fail("RuntimeException wasn't thrown");
- } catch (RuntimeException re) {
- String str = re.getMessage();
- if (!str.equals("Not initialiazed"))
- fail("Incorrect exception message: " + str);
- } catch (Exception e) {
- fail("Incorrect exception " + e + " was thrown");
- }
-
- try {
- SSLSessionContext slsc = ssl.engineGetServerSessionContext();
- fail("RuntimeException wasn't thrown");
- } catch (RuntimeException re) {
- String str = re.getMessage();
- if (!str.equals("Not initialiazed"))
- fail("Incorrect exception message: " + str);
- } catch (Exception e) {
- fail("Incorrect exception " + e + " was thrown");
- }
-
- try {
- SSLServerSocketFactory sssf = ssl.engineGetServerSocketFactory();
- fail("RuntimeException wasn't thrown");
- } catch (RuntimeException re) {
- String str = re.getMessage();
- if (!str.equals("Not initialiazed"))
- fail("Incorrect exception message: " + str);
- } catch (Exception e) {
- fail("Incorrect exception " + e + " was thrown");
- }
-
- try {
- SSLSocketFactory ssf = ssl.engineGetSocketFactory();
- fail("RuntimeException wasn't thrown");
- } catch (RuntimeException re) {
- String str = re.getMessage();
- if (!str.equals("Not initialiazed"))
- fail("Incorrect exception message: " + str);
- } catch (Exception e) {
- fail("Incorrect exception " + e + " was thrown");
- }
- }
-
- /**
- * @tests SSLContextSpi#engineInit(KeyManager[] km, TrustManager[] tm, SecureRandom sr)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "engineInit",
- args = {javax.net.ssl.KeyManager[].class, javax.net.ssl.TrustManager[].class, java.security.SecureRandom.class}
- )
- public void test_engineInit() {
- SSLContextSpiImpl ssl = new SSLContextSpiImpl();
- String defaultAlgorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
- try {
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm);
- char[] pass = "password".toCharArray();
- kmf.init(null, pass);
- KeyManager[] km = kmf.getKeyManagers();
- defaultAlgorithm = Security.getProperty("ssl.TrustManagerFactory.algorithm");
- TrustManagerFactory trustMF = TrustManagerFactory.getInstance(defaultAlgorithm);
- KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
- ks.load(null, null);
- trustMF.init(ks);
- TrustManager[] tm = trustMF.getTrustManagers();
- SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
- try {
- ssl.engineInit(km, tm, sr);
- } catch (KeyManagementException kme) {
- fail(kme + " was throw for engineInit method");
- }
- try {
- ssl.engineInit(km, tm, null);
- fail("KeyManagementException wasn't thrown");
- } catch (KeyManagementException kme) {
- //expected
- }
- } catch (Exception ex) {
- fail(ex + " unexpected exception");
- }
- }
-
- /**
- * @tests SSLContextSpi#engineCreateSSLEngine()
- * @tests SSLContextSpi#engineCreateSSLEngine(String host, int port)
- * @tests SSLContextSpi#engineGetClientSessionContext()
- * @tests SSLContextSpi#engineGetServerSessionContext()
- * @tests SSLContextSpi#engineGetServerSocketFactory()
- * @tests SSLContextSpi#engineGetSocketFactory()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "engineCreateSSLEngine",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "engineCreateSSLEngine",
- args = {java.lang.String.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "engineGetClientSessionContext",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "engineGetServerSessionContext",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "engineGetServerSocketFactory",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "engineGetSocketFactory",
- args = {}
- )
- })
- public void test_commonTest_02() {
- SSLContextSpiImpl ssl = new SSLContextSpiImpl();
- String defaultAlgorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
- try {
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm);
- char[] pass = "password".toCharArray();
- kmf.init(null, pass);
- KeyManager[] km = kmf.getKeyManagers();
- defaultAlgorithm = Security.getProperty("ssl.TrustManagerFactory.algorithm");
- TrustManagerFactory trustMF = TrustManagerFactory.getInstance(defaultAlgorithm);
- KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
- ks.load(null, null);
- trustMF.init(ks);
- TrustManager[] tm = trustMF.getTrustManagers();
- SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
- ssl.engineInit(km, tm, sr);
- } catch (Exception ex) {
- fail(ex + " unexpected exception");
- }
-
- try {
- assertNotNull("Subtest_01: Object is NULL", ssl.engineCreateSSLEngine());
- SSLEngine sleng = ssl.engineCreateSSLEngine("localhost", 1080);
- assertNotNull("Subtest_02: Object is NULL", sleng);
- assertEquals(sleng.getPeerPort(), 1080);
- assertEquals(sleng.getPeerHost(), "localhost");
- assertNull("Subtest_03: Object not NULL", ssl.engineGetClientSessionContext());
- assertNull("Subtest_04: Object not NULL", ssl.engineGetServerSessionContext());
- assertNull("Subtest_05: Object not NULL", ssl.engineGetServerSocketFactory());
- assertNull("Subtest_06: Object not NULL", ssl.engineGetSocketFactory());
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
- }
-
-}
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/SSLEngineResultHandshakeStatusTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/SSLEngineResultHandshakeStatusTest.java
deleted file mode 100644
index 22af271..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/SSLEngineResultHandshakeStatusTest.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import javax.net.ssl.SSLEngineResult;
-
-import junit.framework.TestCase;
-
-/**
- * Tests for SSLEngineResult.Status class
- *
- */
-@TestTargetClass(SSLEngineResult.HandshakeStatus.class)
-public class SSLEngineResultHandshakeStatusTest extends TestCase {
-
- /**
- * Test for <code> SSLEngineResult.HandshakeStatus.values() </code>
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "values",
- args = {}
- )
- public void test_SSLEngineResultHandshakeStatus_values() {
- String[] str = {"NOT_HANDSHAKING", "FINISHED", "NEED_TASK", "NEED_WRAP", "NEED_UNWRAP"};
- SSLEngineResult.HandshakeStatus[] enS = SSLEngineResult.HandshakeStatus.values();
- if (enS.length == str.length) {
- for (int i = 0; i < enS.length; i++) {
- //System.out.println("enS[" + i + "] = " + enS[i]);
- assertEquals("Incorrect Status", enS[i].toString(), str[i]);
- }
- } else {
- fail("Incorrect number of enum constant was returned");
- }
- }
-
- /**
- * Test for <code> SSLEngineResult.HandshakeStatus.valueOf(String name) </code>
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {String.class}
- )
- public void test_SSLEngineResultStatus_valueOf() {
- String[] str = {"FINISHED", "NEED_TASK", "NEED_UNWRAP", "NEED_WRAP", "NOT_HANDSHAKING"};
- String[] str_invalid = {"", "FINISHED1", "NEED_task", "NEED_UN",
- "NEED_WRAP_WRAP", "not_HANDSHAKING", "Bad string for verification valueOf method"};
- SSLEngineResult.HandshakeStatus enS;
-
- //Correct parameter
- for (int i = 0; i < str.length; i++) {
- try {
- enS = SSLEngineResult.HandshakeStatus.valueOf(str[i]);
- assertEquals("Incorrect Status", enS.toString(), str[i]);
- } catch (Exception e) {
- fail("Unexpected exception " + e + " was thrown for " + str[i]);
- }
- }
-
- //Incorrect parameter
- for (int i = 0; i < str_invalid.length; i++) {
- try {
- enS = SSLEngineResult.HandshakeStatus.valueOf(str_invalid[i]);
- fail("IllegalArgumentException should be thrown for " + str_invalid[i]);
- } catch (IllegalArgumentException iae) {
- //expected
- }
- }
-
- //Null parameter
- try {
- enS = SSLEngineResult.HandshakeStatus.valueOf(null);
- fail("NullPointerException/IllegalArgumentException should be thrown for NULL parameter");
- } catch (NullPointerException npe) {
- //expected
- } catch (IllegalArgumentException iae) {
- }
- }
-} \ No newline at end of file
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/SSLEngineResultStatusTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/SSLEngineResultStatusTest.java
deleted file mode 100644
index 652b384..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/SSLEngineResultStatusTest.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import javax.net.ssl.SSLEngineResult;
-
-import junit.framework.TestCase;
-
-/**
- * Tests for SSLEngineResult.Status class
- *
- */
-@TestTargetClass(SSLEngineResult.Status.class)
-public class SSLEngineResultStatusTest extends TestCase {
-
- /**
- * Test for <code> SSLEngineResult.Status.values() </code>
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "values",
- args = {}
- )
- public void test_SSLEngineResultStatus_values() {
- boolean flag = false;
- String[] str = {"BUFFER_OVERFLOW", "BUFFER_UNDERFLOW", "CLOSED", "OK"};
- SSLEngineResult.Status[] enS = SSLEngineResult.Status.values();
- if (enS.length == str.length) {
- for (int i = 0; i < enS.length; i++) {
- flag = false;
- for (int j = 0; j < str.length; j++) {
- if (enS[i].toString() == str[j]) {
- flag = true;
- break;
- }
- }
- }
- assertTrue("Incorrect Status", flag);
- } else {
- fail("Incorrect number of enum constant was returned");
- }
- }
-
- /**
- * Test for <code> SSLEngineResult.Status.valueOf(String name) </code>
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {String.class}
- )
- public void test_SSLEngineResultStatus_valueOf() {
- String[] str = {"BUFFER_OVERFLOW", "BUFFER_UNDERFLOW", "CLOSED", "OK"};
- String[] str_invalid = {"", "OK1", "BUFFER_overflow", "BUFFER_UND",
- "CLOSED_CLOSED", "Bad string for verification valueOf method"};
- SSLEngineResult.Status enS;
-
- //Correct parameter
- for (int i = 0; i < str.length; i++) {
- try {
- enS = SSLEngineResult.Status.valueOf(str[i]);
- assertEquals("Incorrect Status", enS.toString(), str[i]);
- } catch (Exception e) {
- fail("Unexpected exception " + e + " was thrown for " + str[i]);
- }
- }
-
- //Incorrect parameter
- for (int i = 0; i < str_invalid.length; i++) {
- try {
- enS = SSLEngineResult.Status.valueOf(str_invalid[i]);
- fail("IllegalArgumentException should be thrown for " + str_invalid[i]);
- } catch (IllegalArgumentException iae) {
- //expected
- }
- }
-
- //Null parameter
- try {
- enS = SSLEngineResult.Status.valueOf(null);
- fail("NullPointerException/IllegalArgumentException should be thrown for NULL parameter");
- } catch (NullPointerException npe) {
- //expected
- } catch (IllegalArgumentException iae) {
- }
- }
-} \ No newline at end of file
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/SSLEngineResultTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/SSLEngineResultTest.java
deleted file mode 100644
index 4878df8..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/SSLEngineResultTest.java
+++ /dev/null
@@ -1,259 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import javax.net.ssl.SSLEngineResult;
-import junit.framework.TestCase;
-
-
-/**
- * Tests for SSLEngineResult class
- *
- */
-@TestTargetClass(SSLEngineResult.class)
-public class SSLEngineResultTest extends TestCase {
-
- /**
- * Test for <code>SSLEngineResult(SSLEngineResult.Status status,
- * SSLEngineResult.HandshakeStatus handshakeStatus,
- * int bytesConsumed,
- * int bytesProduced) </code> constructor and
- * <code>getHandshakeStatus()</code>
- * <code>getStatus()</code>
- * <code>bytesConsumed()</code>
- * <code>bytesProduced()</code>
- * <code>toString()</code>
- * methods
- * Assertions:
- * constructor throws IllegalArgumentException when bytesConsumed
- * or bytesProduced is negative or when status or handshakeStatus
- * is null
- *
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SSLEngineResult",
- args = {javax.net.ssl.SSLEngineResult.Status.class, javax.net.ssl.SSLEngineResult.HandshakeStatus.class, int.class, int.class}
- )
- public void test_ConstructorLjavax_net_ssl_SSLEngineResult_StatusLjavax_net_ssl_SSLEngineResult_HandshakeStatusII() {
-
- int[] neg = { -1, -10, -1000, Integer.MIN_VALUE,
- (Integer.MIN_VALUE + 1) };
- try {
- new SSLEngineResult(null, SSLEngineResult.HandshakeStatus.FINISHED,
- 1, 1);
- fail("IllegalArgumentException must be thrown");
- } catch (IllegalArgumentException e) {
- }
- try {
- new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW, null,
- 1, 1);
- fail("IllegalArgumentException must be thrown");
- } catch (IllegalArgumentException e) {
- }
- for (int i = 0; i < neg.length; i++) {
- try {
- new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW,
- SSLEngineResult.HandshakeStatus.FINISHED, neg[i], 1);
- fail("IllegalArgumentException must be thrown");
- } catch (IllegalArgumentException e) {
- }
- }
- for (int i = 0; i < neg.length; i++) {
- try {
- new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW,
- SSLEngineResult.HandshakeStatus.FINISHED, 1, neg[i]);
- fail("IllegalArgumentException must be thrown");
- } catch (IllegalArgumentException e) {
- }
- }
-
- try {
- SSLEngineResult res = new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW,
- SSLEngineResult.HandshakeStatus.FINISHED, 1, 2);
- assertNotNull("Null object", res);
- assertEquals(1, res.bytesConsumed());
- assertEquals(2, res.bytesProduced());
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- /**
- * Test for <code>bytesConsumed()</code> method
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "bytesConsumed",
- args = {}
- )
- public void test_bytesConsumed() {
- int[] pos = { 0, 1, 1000, Integer.MAX_VALUE, (Integer.MAX_VALUE - 1) };
- SSLEngineResult.Status [] enS =
- SSLEngineResult.Status.values();
- SSLEngineResult.HandshakeStatus [] enHS =
- SSLEngineResult.HandshakeStatus.values();
- for (int i = 0; i < enS.length; i++) {
- for (int j = 0; j < enHS.length; j++) {
- for (int n = 0; n < pos.length; n++) {
- for (int l = 0; l < pos.length; l++) {
- SSLEngineResult res = new SSLEngineResult(enS[i],
- enHS[j], pos[n], pos[l]);
- assertEquals("Incorrect bytesConsumed", pos[n],
- res.bytesConsumed());
- }
- }
- }
- }
- }
-
- /**
- * Test for <code>bytesProduced()</code> method
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "bytesProduced",
- args = {}
- )
- public void test_bytesProduced() {
- int[] pos = { 0, 1, 1000, Integer.MAX_VALUE, (Integer.MAX_VALUE - 1) };
- SSLEngineResult.Status [] enS =
- SSLEngineResult.Status.values();
- SSLEngineResult.HandshakeStatus [] enHS =
- SSLEngineResult.HandshakeStatus.values();
- for (int i = 0; i < enS.length; i++) {
- for (int j = 0; j < enHS.length; j++) {
- for (int n = 0; n < pos.length; n++) {
- for (int l = 0; l < pos.length; ++l) {
- SSLEngineResult res = new SSLEngineResult(enS[i],
- enHS[j], pos[n], pos[l]);
- assertEquals("Incorrect bytesProduced", pos[l],
- res.bytesProduced());
- }
- }
- }
- }
- }
-
- /**
- * Test for <code>getHandshakeStatus()</code> method
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getHandshakeStatus",
- args = {}
- )
- public void test_getHandshakeStatus() {
- int[] pos = { 0, 1, 1000, Integer.MAX_VALUE, (Integer.MAX_VALUE - 1) };
- SSLEngineResult.Status [] enS =
- SSLEngineResult.Status.values();
- SSLEngineResult.HandshakeStatus [] enHS =
- SSLEngineResult.HandshakeStatus.values();
- for (int i = 0; i < enS.length; i++) {
- for (int j = 0; j < enHS.length; j++) {
- for (int n = 0; n < pos.length; n++) {
- for (int l = 0; l < pos.length; ++l) {
- SSLEngineResult res = new SSLEngineResult(enS[i],
- enHS[j], pos[n], pos[l]);
- assertEquals("Incorrect HandshakeStatus", enHS[j],
- res.getHandshakeStatus());
- }
- }
- }
- }
- }
-
- /**
- * Test for <code>getStatus()</code> method
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getStatus",
- args = {}
- )
- public void test_getStatus() {
- int[] pos = { 0, 1, 1000, Integer.MAX_VALUE, (Integer.MAX_VALUE - 1) };
- SSLEngineResult.Status [] enS =
- SSLEngineResult.Status.values();
- SSLEngineResult.HandshakeStatus [] enHS =
- SSLEngineResult.HandshakeStatus.values();
- for (int i = 0; i < enS.length; i++) {
- for (int j = 0; j < enHS.length; j++) {
- for (int n = 0; n < pos.length; n++) {
- for (int l = 0; l < pos.length; ++l) {
- SSLEngineResult res = new SSLEngineResult(enS[i],
- enHS[j], pos[n], pos[l]);
- assertEquals("Incorrect Status", enS[i],
- res.getStatus());
- }
- }
- }
- }
- }
-
- /**
- * Test for <code>toString()</code> method
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- int[] pos = { 0, 1, 1000, Integer.MAX_VALUE, (Integer.MAX_VALUE - 1) };
- SSLEngineResult.Status [] enS =
- SSLEngineResult.Status.values();
- SSLEngineResult.HandshakeStatus [] enHS =
- SSLEngineResult.HandshakeStatus.values();
- for (int i = 0; i < enS.length; i++) {
- for (int j = 0; j < enHS.length; j++) {
- for (int n = 0; n < pos.length; n++) {
- for (int l = 0; l < pos.length; ++l) {
- SSLEngineResult res = new SSLEngineResult(enS[i],
- enHS[j], pos[n], pos[l]);
- assertNotNull("Result of toSring() method is null",
- res.toString());
- }
- }
- }
- }
- }
-
- private boolean findEl(Object[] arr, Object el) {
- boolean ok = false;
- for (int i = 0; i < arr.length; i++) {
- if (arr[i].equals(el)) {
- ok = true;
- break;
- }
- }
- return ok;
- }
-
-}
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/SSLEngineTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/SSLEngineTest.java
deleted file mode 100644
index 8205059..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/SSLEngineTest.java
+++ /dev/null
@@ -1,1929 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package tests.api.javax.net.ssl;
-
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.nio.ReadOnlyBufferException;
-import java.nio.channels.Pipe;
-import java.nio.channels.Pipe.SinkChannel;
-import java.nio.channels.Pipe.SourceChannel;
-import java.security.KeyManagementException;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.UnrecoverableKeyException;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
-import java.util.Vector;
-
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.SSLEngineResult;
-import javax.net.ssl.SSLException;
-import javax.net.ssl.X509TrustManager;
-import javax.net.ssl.SSLEngineResult.HandshakeStatus;
-
-import junit.framework.TestCase;
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import tests.util.TestEnvironment;
-
-
-/**
- * Tests for SSLEngine class
- *
- */
-@TestTargetClass(SSLEngine.class)
-public class SSLEngineTest extends TestCase {
-
- private HandshakeHandler clientEngine;
- private HandshakeHandler serverEngine;
-
- @Override protected void setUp() throws Exception {
- super.setUp();
- TestEnvironment.reset();
- }
-
- /**
- * Test for <code>SSLEngine()</code> constructor Assertion: creates
- * SSLEngine object with null host and -1 port
- * @throws NoSuchAlgorithmException
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SSLEngine",
- args = {}
- )
- public void test_Constructor() throws NoSuchAlgorithmException {
- SSLEngine e = getEngine();
- assertNull(e.getPeerHost());
- assertEquals(-1, e.getPeerPort());
- String[] suites = e.getSupportedCipherSuites();
- e.setEnabledCipherSuites(suites);
- assertEquals(e.getEnabledCipherSuites().length, suites.length);
- }
-
- /**
- * Test for <code>SSLEngine(String host, int port)</code> constructor
- * @throws NoSuchAlgorithmException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verification with incorrect parameters missed",
- method = "SSLEngine",
- args = {java.lang.String.class, int.class}
- )
- public void test_ConstructorLjava_lang_StringI01() throws NoSuchAlgorithmException {
- int port = 1010;
- SSLEngine e = getEngine(null, port);
- assertNull(e.getPeerHost());
- assertEquals(e.getPeerPort(), port);
- try {
- e.beginHandshake();
- } catch (IllegalStateException ex) {
- // expected
- } catch (SSLException ex) {
- fail("unexpected SSLException was thrown.");
- }
- e = getEngine(null, port);
- e.setUseClientMode(true);
- try {
- e.beginHandshake();
- } catch (SSLException ex) {
- // expected
- }
- e = getEngine(null, port);
- e.setUseClientMode(false);
- try {
- e.beginHandshake();
- } catch (SSLException ex) {
- // expected
- }
- }
-
- /**
- * Test for <code>SSLEngine(String host, int port)</code> constructor
- * @throws NoSuchAlgorithmException
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verification with incorrect parameters missed",
- method = "SSLEngine",
- args = {java.lang.String.class, int.class}
- )
- public void test_ConstructorLjava_lang_StringI02() throws NoSuchAlgorithmException {
- String host = "new host";
- int port = 8080;
- SSLEngine e = getEngine(host, port);
- assertEquals(e.getPeerHost(), host);
- assertEquals(e.getPeerPort(), port);
- String[] suites = e.getSupportedCipherSuites();
- e.setEnabledCipherSuites(suites);
- assertEquals(e.getEnabledCipherSuites().length, suites.length);
- e.setUseClientMode(true);
- assertTrue(e.getUseClientMode());
- }
-
- /**
- * Test for <code>getPeerHost()</code> method
- * @throws NoSuchAlgorithmException
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPeerHost",
- args = {}
- )
- public void test_getPeerHost() throws NoSuchAlgorithmException {
- SSLEngine e = getEngine();
- assertNull(e.getPeerHost());
- e = getEngine("www.fortify.net", 80);
- assertEquals("Incorrect host name", "www.fortify.net", e.getPeerHost());
- }
-
- /**
- * Test for <code>getPeerPort()</code> method
- * @throws NoSuchAlgorithmException
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPeerPort",
- args = {}
- )
- public void test_getPeerPort() throws NoSuchAlgorithmException {
- SSLEngine e = getEngine();
- assertEquals("Incorrect default value of peer port",
- -1 ,e.getPeerPort());
- e = getEngine("www.fortify.net", 80);
- assertEquals("Incorrect peer port", 80, e.getPeerPort());
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @tests javax.net.ssl.SSLEngine#getSupportedProtocols()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSupportedProtocols",
- args = {}
- )
- public void test_getSupportedProtocols() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
- try {
- String[] res = sse.getSupportedProtocols();
- assertNotNull(res);
- assertTrue(res.length > 0);
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @tests javax.net.ssl.SSLEngine#setEnabledProtocols(String[] protocols)
- * @tests javax.net.ssl.SSLEngine#getEnabledProtocols()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getEnabledProtocols",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setEnabledProtocols",
- args = {String[].class}
- )
- })
- public void test_EnabledProtocols() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
- String[] pr = sse.getSupportedProtocols();
- try {
- sse.setEnabledProtocols(pr);
- String[] res = sse.getEnabledProtocols();
- assertNotNull("Null array was returned", res);
- assertEquals("Incorrect array length", res.length, pr.length);
- assertTrue("Incorrect array was returned", Arrays.equals(res, pr));
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- try {
- sse.setEnabledProtocols(null);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @tests javax.net.ssl.SSLEngine#getSupportedCipherSuites()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSupportedCipherSuites",
- args = {}
- )
- public void test_getSupportedCipherSuites() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
- try {
- String[] res = sse.getSupportedCipherSuites();
- assertNotNull(res);
- assertTrue(res.length > 0);
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @tests javax.net.ssl.SSLEngine#setEnabledCipherSuites(String[] suites)
- * @tests javax.net.ssl.SSLEngine#getEnabledCipherSuites()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setEnabledCipherSuites",
- args = {String[].class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getEnabledCipherSuites",
- args = {}
- )
- })
- public void test_EnabledCipherSuites() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
- String[] st = sse.getSupportedCipherSuites();
- try {
- sse.setEnabledCipherSuites(st);
- String[] res = sse.getEnabledCipherSuites();
- assertNotNull("Null array was returned", res);
- assertEquals("Incorrect array length", res.length, st.length);
- assertTrue("Incorrect array was returned", Arrays.equals(res, st));
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- try {
- sse.setEnabledCipherSuites(null);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @tests javax.net.ssl.SSLEngine#setEnableSessionCreation(boolean flag)
- * @tests javax.net.ssl.SSLEngine#getEnableSessionCreation()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setEnableSessionCreation",
- args = {boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getEnableSessionCreation",
- args = {}
- )
- })
- public void test_EnableSessionCreation() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
- try {
- assertTrue(sse.getEnableSessionCreation());
- sse.setEnableSessionCreation(false);
- assertFalse(sse.getEnableSessionCreation());
- sse.setEnableSessionCreation(true);
- assertTrue(sse.getEnableSessionCreation());
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @tests javax.net.ssl.SSLEngine#setNeedClientAuth(boolean need)
- * @tests javax.net.ssl.SSLEngine#getNeedClientAuth()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setNeedClientAuth",
- args = {boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getNeedClientAuth",
- args = {}
- )
- })
- public void test_NeedClientAuth() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
- try {
- sse.setNeedClientAuth(false);
- assertFalse(sse.getNeedClientAuth());
- sse.setNeedClientAuth(true);
- assertTrue(sse.getNeedClientAuth());
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @tests javax.net.ssl.SSLEngine#setWantClientAuth(boolean want)
- * @tests javax.net.ssl.SSLEngine#getWantClientAuth()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setWantClientAuth",
- args = {boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getWantClientAuth",
- args = {}
- )
- })
- public void test_WantClientAuth() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
- try {
- sse.setWantClientAuth(false);
- assertFalse(sse.getWantClientAuth());
- sse.setWantClientAuth(true);
- assertTrue(sse.getWantClientAuth());
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @tests javax.net.ssl.SSLEngine#beginHandshake()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "beginHandshake",
- args = {}
- )
- public void test_beginHandshake() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
- try {
- sse.beginHandshake();
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException se) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalStateException");
- }
- sse = getEngine("new host", 1080);
- try {
- sse.beginHandshake();
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException ise) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalStateException");
- }
- sse = getEngine();
- try {
- sse.setUseClientMode(true);
- sse.beginHandshake();
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @tests javax.net.ssl.SSLEngine#setUseClientMode(boolean mode)
- * @tests javax.net.ssl.SSLEngine#getUseClientMode()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setUseClientMode",
- args = {boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getUseClientMode",
- args = {}
- )
- })
- @AndroidOnly("The RI doesn't throw the expected IllegalStateException.")
- public void test_UseClientMode() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
- try {
- sse.setUseClientMode(false);
- assertFalse(sse.getUseClientMode());
- sse.setUseClientMode(true);
- assertTrue(sse.getUseClientMode());
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
-
- try {
- sse = getEngine(null, 1080);
- sse.setUseClientMode(true);
- sse.beginHandshake();
- try {
- sse.setUseClientMode(false);
- fail("IllegalArgumentException was not thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- }
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @tests javax.net.ssl.SSLEngine#getSession()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSession",
- args = {}
- )
- public void test_getSession() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
- try {
- assertNotNull(sse.getSession());
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @tests javax.net.ssl.SSLEngine#getHandshakeStatus()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getHandshakeStatus",
- args = {}
- )
- public void test_getHandshakeStatus() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
- try {
- assertEquals(sse.getHandshakeStatus().toString(), "NOT_HANDSHAKING");
- sse.setUseClientMode(true);
- sse.beginHandshake();
- assertEquals(sse.getHandshakeStatus().toString(), "NEED_WRAP");
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @tests javax.net.ssl.SSLEngine#getDelegatedTask()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDelegatedTask",
- args = {}
- )
- @KnownFailure("org.apache.harmony.xnet.provider.jsse.SSLEngineImpl#getDelegatedTask() throws NPE instead of returning null")
- public void test_getDelegatedTask() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
- try {
- assertNull(sse.getDelegatedTask());
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @throws IOException
- * @throws InterruptedException
- * @tests javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts,
- * int offset, int length)
- * Exception case: SSLException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "unwrap",
- args = {ByteBuffer.class, ByteBuffer[].class, int.class, int.class}
- )
- public void test_unwrap_01() throws IOException, InterruptedException {
- prepareEngines();
- doHandshake();
-
- ByteBuffer bbs = ByteBuffer.wrap(new byte[] {1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,31,2,3,1,2,3,1,2,3,1,2,3});
- ByteBuffer bbd = ByteBuffer.allocate(100);
- try {
- clientEngine.engine.unwrap(bbs, new ByteBuffer[] { bbd }, 0, 1);
- fail("SSLException wasn't thrown");
- } catch (SSLException ex) {
- //expected
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts,
- * int offset, int length)
- * Exception case: IndexOutOfBoundsException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "unwrap",
- args = {ByteBuffer.class, ByteBuffer[].class, int.class, int.class}
- )
- @KnownFailure("Fixed in DonutBurger, boundary checks missing")
- public void test_unwrap_02() throws SSLException {
- String host = "new host";
- int port = 8080;
- ByteBuffer[] bbA = { ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
-
- ByteBuffer bb = ByteBuffer.allocate(10);
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.unwrap(bb, bbA, -1, 3);
- fail("IndexOutOfBoundsException wasn't thrown");
- } catch (IndexOutOfBoundsException iobe) {
- //expected
- }
- try {
- sse.unwrap(bb, bbA, 0, -3);
- fail("IndexOutOfBoundsException wasn't thrown");
- } catch (IndexOutOfBoundsException iobe) {
- //expected
- }
- try {
- sse.unwrap(bb, bbA, bbA.length + 1, bbA.length);
- fail("IndexOutOfBoundsException wasn't thrown");
- } catch (IndexOutOfBoundsException iobe) {
- //expected
- }
- try {
- sse.unwrap(bb, bbA, 0, bbA.length + 1);
- fail("IndexOutOfBoundsException wasn't thrown");
- } catch (IndexOutOfBoundsException iobe) {
- //expected
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts,
- * int offset, int length)
- * Exception case: ReadOnlyBufferException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "unwrap",
- args = {ByteBuffer.class, ByteBuffer[].class, int.class, int.class}
- )
- @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown")
- public void test_unwrap_03() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bbR = ByteBuffer.allocate(100).asReadOnlyBuffer();
- ByteBuffer[] bbA = { bbR, ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
-
- ByteBuffer bb = ByteBuffer.allocate(10);
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.unwrap(bb, bbA, 0, bbA.length);
- fail("ReadOnlyBufferException wasn't thrown");
- } catch (ReadOnlyBufferException iobe) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of ReadOnlyBufferException");
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts,
- * int offset, int length)
- * Exception case: IllegalArgumentException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IllegalArgumentException should be thrown",
- method = "unwrap",
- args = {ByteBuffer.class, ByteBuffer[].class, int.class, int.class}
- )
- @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown")
- public void test_unwrap_04() {
- String host = "new host";
- int port = 8080;
- ByteBuffer[] bbA = {ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100)};
- ByteBuffer[] bbAN = {ByteBuffer.allocate(100), null, ByteBuffer.allocate(100)};
- ByteBuffer[] bbN = null;
- ByteBuffer bb = ByteBuffer.allocate(10);
- ByteBuffer bN = null;
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.unwrap(bN, bbA, 0, 3);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iobe) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
- try {
- sse.unwrap(bb, bbAN, 0, 3);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iobe) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
- try {
- sse.unwrap(bb, bbN, 0, 0);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iobe) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
- try {
- sse.unwrap(bN, bbN, 0, 0);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iobe) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts,
- * int offset, int length)
- * Exception case: IllegalStateException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "unwrap",
- args = {ByteBuffer.class, ByteBuffer[].class, int.class, int.class}
- )
- @AndroidOnly("The RI doesn't throw the IllegalStateException.")
- public void test_unwrap_05() {
- String host = "new host";
- int port = 8080;
- ByteBuffer[] bbA = { ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
-
- ByteBuffer bb = ByteBuffer.allocate(10);
- SSLEngine sse = getEngine(host, port);
-
- try {
- sse.unwrap(bb, bbA, 0, bbA.length);
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException iobe) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalStateException");
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts,
- * int offset, int length)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "unwrap",
- args = {ByteBuffer.class, ByteBuffer[].class, int.class, int.class}
- )
- public void test_unwrap_06() {
- String host = "new host";
- int port = 8080;
- ByteBuffer[] bbA = { ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
-
- ByteBuffer bb = ByteBuffer.allocate(10);
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- SSLEngineResult res = sse.unwrap(bb, bbA, 0, bbA.length);
- assertEquals(0, res.bytesConsumed());
- assertEquals(0, res.bytesProduced());
- } catch (Exception ex) {
- fail("Unexpected exception: " + ex);
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, int offset,
- * int length, ByteBuffer dst)
- * Exception case: SSLException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "wrap cannot be forced to fail",
- method = "wrap",
- args = {ByteBuffer[].class, int.class, int.class, ByteBuffer.class}
- )
- public void test_wrap_01() throws IOException, InterruptedException {
- prepareEngines();
- doHandshake();
-
- ByteBuffer bbs = ByteBuffer.allocate(100);
- ByteBuffer bbd = ByteBuffer.allocate(20000);
-
- try {
- @SuppressWarnings("unused")
- SSLEngineResult result = clientEngine.engine.wrap(new ByteBuffer[] { bbs }, 0, 1, bbd);
- //fail("SSLException wasn't thrown");
- } catch (SSLException ex) {
- //expected
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, int offset,
- * int length, ByteBuffer dst)
- * Exception case: IndexOutOfBoundsException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {ByteBuffer[].class, int.class, int.class, ByteBuffer.class}
- )
- @KnownFailure("Fixed in DonutBurger, boundary checks missing")
- public void test_wrap_02() throws SSLException {
- String host = "new host";
- int port = 8080;
- ByteBuffer bb = ByteBuffer.allocate(10);
- ByteBuffer[] bbA = {ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5)};
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.wrap(bbA, -1, 3, bb);
- fail("IndexOutOfBoundsException wasn't thrown");
- } catch (IndexOutOfBoundsException iobe) {
- //expected
- }
- try {
- sse.wrap(bbA, 0, -3, bb);
- fail("IndexOutOfBoundsException wasn't thrown");
- } catch (IndexOutOfBoundsException iobe) {
- //expected
- }
- try {
- sse.wrap(bbA, bbA.length + 1, bbA.length, bb);
- fail("IndexOutOfBoundsException wasn't thrown");
- } catch (IndexOutOfBoundsException iobe) {
- //expected
- }
- try {
- sse.wrap(bbA, 0, bbA.length + 1, bb);
- fail("IndexOutOfBoundsException wasn't thrown");
- } catch (IndexOutOfBoundsException iobe) {
- //expected
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, int offset,
- * int length, ByteBuffer dst)
- * Exception case: ReadOnlyBufferException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {ByteBuffer[].class, int.class, int.class, ByteBuffer.class}
- )
- public void test_wrap_03() throws SSLException {
- String host = "new host";
- int port = 8080;
- ByteBuffer bb = ByteBuffer.allocate(10).asReadOnlyBuffer();
- ByteBuffer[] bbA = {ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5)};
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.wrap(bbA, 0, bbA.length, bb);
- fail("ReadOnlyBufferException wasn't thrown");
- } catch (ReadOnlyBufferException iobe) {
- //expected
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, int offset,
- * int length, ByteBuffer dst)
- * Exception case: IllegalArgumentException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IllegalArgumentException must be thrown",
- method = "wrap",
- args = {ByteBuffer[].class, int.class, int.class, ByteBuffer.class}
- )
- @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown")
- public void test_wrap_04() {
- String host = "new host";
- int port = 8080;
- ByteBuffer[] bbA = {ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100)};
- ByteBuffer[] bbN = null;
- ByteBuffer bN = null;
- SSLEngine e = getEngine(host, port);
- e.setUseClientMode(true);
-
- try {
- e.wrap(bbA, 0, 3, bN);
- fail("IllegalArgumentException must be thrown for null srcs byte buffer array");
- } catch (NullPointerException npe) {
- } catch (IllegalArgumentException ex) {
- } catch (Exception ex) {
- fail(ex + " was thrown instead of IllegalArgumentException");
- }
-
- try {
- e.wrap(bbN, 0, 0, bN);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException ex) {
- } catch (NullPointerException npe) {
- } catch (Exception ex) {
- fail(ex + " was thrown instead of IllegalArgumentException");
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, int offset,
- * int length, ByteBuffer dst)
- * Exception case: IllegalStateException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {ByteBuffer[].class, int.class, int.class, ByteBuffer.class}
- )
- @AndroidOnly("The RI doesn't throw the IllegalStateException.")
- public void test_wrap_05() throws SSLException {
- String host = "new host";
- int port = 8080;
- ByteBuffer bb = ByteBuffer.allocate(10);
- ByteBuffer[] bbA = {ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5)};
- SSLEngine sse = getEngine(host, port);
-
- try {
- sse.wrap(bbA, 0, bbA.length, bb);
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException iobe) {
- //expected
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, int offset,
- * int length, ByteBuffer dst)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {ByteBuffer[].class, int.class, int.class, ByteBuffer.class}
- )
- public void test_wrap_06() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bb = ByteBuffer.allocate(10);
- ByteBuffer[] bbA = {ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5)};
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.wrap(bbA, 0, bbA.length, bb);
- } catch (Exception ex) {
- fail("Unexpected exception: " + ex);
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @tests javax.net.ssl.SSLEngine#closeOutbound()
- * @tests javax.net.ssl.SSLEngine#isOutboundDone()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "closeOutbound",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isOutboundDone",
- args = {}
- )
- })
- public void test_closeOutbound() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
-
- try {
- assertFalse(sse.isOutboundDone());
- sse.closeOutbound();
- assertTrue(sse.isOutboundDone());
- } catch (Exception ex) {
- fail("Unexpected exception: " + ex);
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @tests javax.net.ssl.SSLEngine#closeInbound()
- * @tests javax.net.ssl.SSLEngine#isInboundDone()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "",
- method = "closeInbound",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isInboundDone",
- args = {}
- )
- })
- public void test_closeInbound() throws NoSuchAlgorithmException {
- SSLEngine sse = getEngine();
-
- try {
- assertFalse(sse.isInboundDone());
- sse.closeInbound();
- assertTrue(sse.isInboundDone());
- } catch (Exception ex) {
- fail("Unexpected exception: " + ex);
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer dst)
- * SSLException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "unwrap",
- args = {ByteBuffer.class, ByteBuffer.class}
- )
- public void test_unwrap_ByteBuffer_ByteBuffer_01() throws InterruptedException, IOException {
- prepareEngines();
- doHandshake();
- ByteBuffer bbs = ByteBuffer.allocate(100);
- ByteBuffer bbd = ByteBuffer.allocate(100);
-
- try {
- SSLEngineResult unwrap = clientEngine.engine.unwrap(bbs, bbd);
- fail("SSLException wasn't thrown");
- } catch (SSLException ex) {
- //expected
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer dst)
- * ReadOnlyBufferException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "unwrap",
- args = {ByteBuffer.class, ByteBuffer.class}
- )
- @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown")
- public void test_unwrap_ByteBuffer_ByteBuffer_02() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bbs = ByteBuffer.allocate(10);
- ByteBuffer bbd = ByteBuffer.allocate(100).asReadOnlyBuffer();
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.unwrap(bbs, bbd);
- fail("ReadOnlyBufferException wasn't thrown");
- } catch (ReadOnlyBufferException iobe) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of ReadOnlyBufferException");
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer dst)
- * IllegalArgumentException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "unwrap",
- args = {ByteBuffer.class, ByteBuffer.class}
- )
- @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown")
- public void test_unwrap_ByteBuffer_ByteBuffer_03() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bbsN = null;
- ByteBuffer bbdN = null;
- ByteBuffer bbs = ByteBuffer.allocate(10);
- ByteBuffer bbd = ByteBuffer.allocate(100);
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.unwrap(bbsN, bbd);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- try {
- sse.unwrap(bbs, bbdN);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- try {
- sse.unwrap(bbsN, bbdN);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer dst)
- * IllegalStateException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "unwrap",
- args = {ByteBuffer.class, ByteBuffer.class}
- )
- @AndroidOnly("The RI doesn't throw the IllegalStateException.")
- public void test_unwrap_ByteBuffer_ByteBuffer_04() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bbs = ByteBuffer.allocate(10);
- ByteBuffer bbd = ByteBuffer.allocate(100);
- SSLEngine sse = getEngine(host, port);
-
- try {
- sse.unwrap(bbs, bbd);
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException iobe) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalStateException");
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer dst)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "unwrap",
- args = {ByteBuffer.class, ByteBuffer.class}
- )
- public void test_unwrap_ByteBuffer_ByteBuffer_05() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bbs = ByteBuffer.allocate(10);
- ByteBuffer bbd = ByteBuffer.allocate(100);
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- SSLEngineResult res = sse.unwrap(bbs, bbd);
- assertEquals(0, res.bytesConsumed());
- assertEquals(0, res.bytesProduced());
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts)
- * SSLException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "unwrap",
- args = {ByteBuffer.class, ByteBuffer[].class}
- )
- public void test_unwrap_ByteBuffer$ByteBuffer_01() throws IOException, InterruptedException {
- prepareEngines();
- doHandshake();
-
- ByteBuffer bbs = ByteBuffer.allocate(100);
- ByteBuffer bbd = ByteBuffer.allocate(100);
-
- try {
- clientEngine.engine.unwrap(bbs, new ByteBuffer[] { bbd });
- fail("SSLException wasn't thrown");
- } catch (SSLException ex) {
- //expected
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts)
- * ReadOnlyBufferException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "unwrap",
- args = {ByteBuffer.class, ByteBuffer[].class}
- )
- @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown")
- public void test_unwrap_ByteBuffer$ByteBuffer_02() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bbs = ByteBuffer.allocate(10);
- ByteBuffer bbR = ByteBuffer.allocate(100).asReadOnlyBuffer();
- ByteBuffer[] bbA = { bbR, ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.unwrap(bbs, bbA);
- fail("ReadOnlyBufferException wasn't thrown");
- } catch (ReadOnlyBufferException iobe) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of ReadOnlyBufferException");
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts)
- * IllegalArgumentException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "unwrap",
- args = {ByteBuffer.class, ByteBuffer[].class}
- )
- @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown")
- public void test_unwrap_ByteBuffer$ByteBuffer_03() {
- String host = "new host";
- int port = 8080;
- ByteBuffer[] bbA = { ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
- ByteBuffer[] bbN = { ByteBuffer.allocate(100), null, ByteBuffer.allocate(100) };
- ByteBuffer[] bbAN = null;
- ByteBuffer bb = ByteBuffer.allocate(10);
- ByteBuffer bN = null;
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.unwrap(bN, bbA);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iobe) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- try {
- sse.unwrap(bb, bbAN);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iobe) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- try {
- sse.unwrap(bb, bbN);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iobe) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- try {
- sse.unwrap(bN, bbAN);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iobe) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts)
- * IllegalStateException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "unwrap",
- args = {ByteBuffer.class, ByteBuffer[].class}
- )
- @AndroidOnly("The RI doesn't throw the IllegalStateException.")
- public void test_unwrap_ByteBuffer$ByteBuffer_04() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bbs = ByteBuffer.allocate(10);
- ByteBuffer[] bbd = {ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
- SSLEngine sse = getEngine(host, port);
-
- try {
- sse.unwrap(bbs, bbd);
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException iobe) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalStateException");
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "unwrap",
- args = {ByteBuffer.class, ByteBuffer[].class}
- )
- public void test_unwrap_ByteBuffer$ByteBuffer_05() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bbs = ByteBuffer.allocate(10);
- ByteBuffer[] bbd = {ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- SSLEngineResult res = sse.unwrap(bbs, bbd);
- assertEquals(0, res.bytesConsumed());
- assertEquals(0, res.bytesProduced());
- } catch (Exception ex) {
- fail("Unexpected exception: " + ex);
- }
- }
-
- /**
- * @throws IOException
- * @throws InterruptedException
- * @tests javax.net.ssl.SSLEngine#wrap(ByteBuffer src, ByteBuffer dst)
- * SSLException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "wrap cannot be forced to produce SSLException",
- method = "wrap",
- args = {ByteBuffer.class, ByteBuffer.class}
- )
- public void test_wrap_ByteBuffer_ByteBuffer_01() throws IOException, InterruptedException {
- prepareEngines();
- doHandshake();
- ByteBuffer bbs = ByteBuffer.allocate(20);
- ByteBuffer bbd = ByteBuffer.allocate(20000);
-
- try {
- clientEngine.engine.wrap(bbs, bbd);
- //fail("SSLException wasn't thrown");
- } catch (SSLException ex) {
- //expected
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#wrap(ByteBuffer src, ByteBuffer dst)
- * ReadOnlyBufferException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {ByteBuffer.class, ByteBuffer.class}
- )
- public void test_wrap_ByteBuffer_ByteBuffer_02() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bbs = ByteBuffer.allocate(10);
- ByteBuffer bbd = ByteBuffer.allocate(100).asReadOnlyBuffer();
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.wrap(bbs, bbd);
- fail("ReadOnlyBufferException wasn't thrown");
- } catch (ReadOnlyBufferException iobe) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of ReadOnlyBufferException");
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#wrap(ByteBuffer src, ByteBuffer dst)
- * IllegalArgumentException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {ByteBuffer.class, ByteBuffer.class}
- )
- @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown")
- public void test_wrap_ByteBuffer_ByteBuffer_03() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bbsN = null;
- ByteBuffer bbdN = null;
- ByteBuffer bbs = ByteBuffer.allocate(10);
- ByteBuffer bbd = ByteBuffer.allocate(100);
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.wrap(bbsN, bbd);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- try {
- sse.wrap(bbs, bbdN);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- try {
- sse.wrap(bbsN, bbdN);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#wrap(ByteBuffer src, ByteBuffer dst)
- * IllegalStateException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {ByteBuffer.class, ByteBuffer.class}
- )
- @AndroidOnly("The RI doesn't throw the IllegalStateException.")
- public void test_wrap_ByteBuffer_ByteBuffer_04() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bbs = ByteBuffer.allocate(10);
- ByteBuffer bbd = ByteBuffer.allocate(10);
- SSLEngine sse = getEngine(host, port);
-
- try {
- sse.wrap(bbs, bbd);
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException iobe) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalStateException");
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#wrap(ByteBuffer src, ByteBuffer dst)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {ByteBuffer.class, ByteBuffer.class}
- )
- public void test_wrap_ByteBuffer_ByteBuffer_05() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bb = ByteBuffer.allocate(10);
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- SSLEngineResult res = sse.wrap(bb, ByteBuffer.allocate(10));
- assertEquals(0, res.bytesConsumed());
- assertEquals(0, res.bytesProduced());
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- /**
- * @throws IOException
- * @throws InterruptedException
- * @tests javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, ByteBuffer dst)
- * SSLException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "wrap cannot be forced to throw SSLException",
- method = "wrap",
- args = {ByteBuffer[].class, ByteBuffer.class}
- )
- public void test_wrap_ByteBuffer$ByteBuffer_01() throws IOException, InterruptedException {
- prepareEngines();
- doHandshake();
- ByteBuffer bbs = ByteBuffer.allocate(100);
- ByteBuffer bbd = ByteBuffer.allocate(20000);
-
- try {
- clientEngine.engine.wrap(new ByteBuffer[] { bbs }, bbd);
- serverEngine.engine.wrap(new ByteBuffer[] { bbs }, bbd);
- //fail("SSLException wasn't thrown");
- } catch (SSLException ex) {
- //expected
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, ByteBuffer dst)
- * ReadOnlyBufferException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {ByteBuffer[].class, ByteBuffer.class}
- )
- public void test_wrap_ByteBuffer$ByteBuffer_02() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bb = ByteBuffer.allocate(10).asReadOnlyBuffer();
- ByteBuffer[] bbA = {ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5)};
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.wrap(bbA, bb);
- fail("ReadOnlyBufferException wasn't thrown");
- } catch (ReadOnlyBufferException iobe) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of ReadOnlyBufferException");
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, ByteBuffer dst)
- * IllegalArgumentException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {ByteBuffer[].class, ByteBuffer.class}
- )
- @KnownFailure("Fixed on DonutBurger, Wrong Exception thrown")
- public void test_wrap_ByteBuffer$ByteBuffer_03() {
- String host = "new host";
- int port = 8080;
- ByteBuffer[] bbA = {ByteBuffer.allocate(100), ByteBuffer.allocate(10), ByteBuffer.allocate(100)};
- ByteBuffer[] bbAN = null;
- ByteBuffer bb = ByteBuffer.allocate(10);
- ByteBuffer bN = null;
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- sse.wrap(bbA, bN);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iobe) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- try {
- sse.wrap(bbAN, bb);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iobe) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- try {
- sse.wrap(bbAN, bN);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iobe) {
- //expected
- } catch (NullPointerException npe) {
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, ByteBuffer dst)
- * IllegalStateException should be thrown.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {ByteBuffer[].class, ByteBuffer.class}
- )
- @AndroidOnly("The RI doesn't throw the IllegalStateException.")
- public void test_wrap_ByteBuffer$ByteBuffer_04() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bb = ByteBuffer.allocate(10);
- ByteBuffer[] bbA = { ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5) };
- SSLEngine sse = getEngine(host, port);
-
- try {
- sse.wrap(bbA, bb);
- fail("IllegalStateException wasn't thrown");
- } catch (IllegalStateException iobe) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalStateException");
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLEngine#wrap(ByteBuffer[] srcs, ByteBuffer dst)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {ByteBuffer[].class, ByteBuffer.class}
- )
- public void test_wrap_ByteBuffer$ByteBuffer_05() {
- String host = "new host";
- int port = 8080;
- ByteBuffer bb = ByteBuffer.allocate(10);
- ByteBuffer[] bbA = { ByteBuffer.allocate(5), ByteBuffer.allocate(10), ByteBuffer.allocate(5) };
- SSLEngine sse = getEngine(host, port);
- sse.setUseClientMode(true);
-
- try {
- SSLEngineResult res = sse.wrap(bbA, bb);
- assertEquals(0, res.bytesConsumed());
- assertEquals(0, res.bytesProduced());
- } catch (Exception ex) {
- fail("Unexpected exception: " + ex);
- }
- }
-
- private SSLEngine getEngine() {
- SSLContext context = null;
- try {
- context = SSLContext.getInstance("TLS");
- context.init(null, null, null);
- } catch (KeyManagementException e) {
- fail("Could not get SSLEngine: key management exception "
- + e.getMessage());
- } catch (NoSuchAlgorithmException e) {
- fail("Could not get SSLEngine: no such algorithm " + e.getMessage());
- }
- return context.createSSLEngine();
- }
-
- private SSLEngine getEngine(String host, int port) {
- SSLContext context = null;
- try {
- context = SSLContext.getInstance("TLS");
- context.init(null, null, null);
- } catch (KeyManagementException e) {
- fail("Could not get SSLEngine: key management exception "
- + e.getMessage());
- } catch (NoSuchAlgorithmException e) {
- fail("Could not get SSLEngine: no such algorithm " + e.getMessage());
- }
- return context.createSSLEngine(host, port);
- }
-
- class HandshakeHandler implements Runnable {
-
- private final SSLEngine engine;
-
- private final SourceChannel in;
-
- private final SinkChannel out;
-
- private final ByteBuffer EMPTY = ByteBuffer.allocate(0);
-
- @SuppressWarnings("unused")
- private final String LOGTAG;
-
- private SSLEngineResult.HandshakeStatus status;
-
- private ByteBuffer readBuffer;
-
- private ByteBuffer writeBuffer;
-
- HandshakeHandler(boolean clientMode, SourceChannel in, SinkChannel out)
- throws SSLException {
- this.in = in;
- this.out = out;
- engine = getEngine();
- engine.setUseClientMode(clientMode);
- String[] cipherSuites = engine.getSupportedCipherSuites();
- Set<String> enabledSuites = new HashSet<String>();
- for (String cipherSuite : cipherSuites) {
- if (cipherSuite.contains("anon")) {
- enabledSuites.add(cipherSuite);
- }
- }
- engine.setEnabledCipherSuites((String[]) enabledSuites.toArray(
- new String[enabledSuites.size()]));
-
- engine.beginHandshake();
- status = engine.getHandshakeStatus();
-
- if (clientMode) {
- LOGTAG = "CLIENT: ";
- } else {
- LOGTAG = "SERVER: ";
- }
-
- log("CipherSuites: " + Arrays.toString(engine.getEnabledCipherSuites()));
- log(status);
-
- readBuffer = ByteBuffer.allocate(200000);
- writeBuffer = ByteBuffer.allocate(20000);
- }
-
- public SSLEngineResult.HandshakeStatus getStatus() {
- return status;
- }
-
- private void log(Object o) {
- //System.out.print(LOGTAG);
- //System.out.println(o);
- }
-
- private ByteBuffer read() throws IOException {
- if (readBuffer == null || readBuffer.remaining() == 0 || readBuffer.position() == 0) {
- readBuffer.clear();
- int read = in.read(readBuffer);
- log("read: " + read);
- readBuffer.rewind();
- readBuffer.limit(read);
- }
- return readBuffer;
- }
-
- public void run() {
- try {
- while (true) {
- switch (status) {
- case FINISHED: {
- log(status);
- return;
- }
- case NEED_TASK: {
- log(status);
- Runnable task;
- while ((task = engine.getDelegatedTask()) != null) {
- task.run();
- }
- status = engine.getHandshakeStatus();
- break;
- }
- case NEED_UNWRAP: {
- log(status);
- ByteBuffer source = read();
- writeBuffer.clear();
-
- while (status == HandshakeStatus.NEED_UNWRAP) {
- SSLEngineResult result = engine.unwrap(source, writeBuffer);
- status = result.getHandshakeStatus();
- log(result);
- }
- break;
- }
- case NEED_WRAP: {
- log(status);
- writeBuffer.clear();
-
- int produced = 0;
- SSLEngineResult result = null;
- while (status == HandshakeStatus.NEED_WRAP) {
- result = engine.wrap(EMPTY, writeBuffer);
- status = result.getHandshakeStatus();
- produced += result.bytesProduced();
- log(result);
- }
- writeBuffer.rewind();
- writeBuffer.limit(produced);
- log("write: " + produced);
- out.write(writeBuffer);
- break;
- }
- case NOT_HANDSHAKING: {
- log("Not Handshaking");
- return;
- }
- }
- }
- } catch (IOException e) {
- log(e);
- } catch (RuntimeException e) {
- // ignore;
- }
- }
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {ByteBuffer.class, ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "unwrap",
- args = {ByteBuffer.class, ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "beginHandshake",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getHandshakeStatus",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "wrap",
- args = {ByteBuffer[].class, ByteBuffer.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getDelegatedTask",
- args = {}
- )
- })
- @KnownFailure("Handshake Status is never finished. NPE in "
- + "ClientSessionContext$HostAndPort.hashCode() when host is null")
- public void testHandshake() throws IOException, InterruptedException {
-
- prepareEngines();
-
- assertTrue("handshake failed", doHandshake());
-
- System.out.println(clientEngine.engine.getSession().getCipherSuite());
-
- assertEquals("Handshake not finished",
- SSLEngineResult.HandshakeStatus.FINISHED,
- clientEngine.getStatus());
- assertEquals("Handshake not finished",
- SSLEngineResult.HandshakeStatus.FINISHED,
- serverEngine.getStatus());
- }
-
- void prepareEngines() throws IOException {
- Pipe clientSendPipe = Pipe.open();
- Pipe serverSendPipe = Pipe.open();
-
- SinkChannel clientSink = clientSendPipe.sink();
- SourceChannel serverSource = clientSendPipe.source();
- SinkChannel serverSink = serverSendPipe.sink();
- SourceChannel clientSource = serverSendPipe.source();
-
- clientEngine = new HandshakeHandler(true, clientSource, clientSink);
- serverEngine = new HandshakeHandler(false, serverSource, serverSink);
- }
-
- boolean doHandshake() throws InterruptedException {
- Thread clientThread = new Thread(clientEngine);
- clientThread.start();
-
- Thread serverThread = new Thread(serverEngine);
- serverThread.start();
-
- int i = 0;
- while (clientThread.isAlive() && serverThread.isAlive() && i < 20) {
- Thread.sleep(500);
- i++;
- }
-
- if (clientThread.isAlive()) {
- clientThread.interrupt();
- }
-
- if (serverThread.isAlive()) {
- serverThread.interrupt();
- }
-
- return clientEngine.getStatus() == HandshakeStatus.FINISHED && serverEngine.getStatus() == HandshakeStatus.FINISHED;
- }
-
-}
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/SSLExceptionTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/SSLExceptionTest.java
deleted file mode 100644
index 301f510..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/SSLExceptionTest.java
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import javax.net.ssl.SSLException;
-
-import junit.framework.TestCase;
-@TestTargetClass(SSLException.class)
-/**
- * Tests for <code>SSLException</code> class constructors and methods.
- *
- */
-public class SSLExceptionTest extends TestCase {
-
- private static String[] msgs = {
- "",
- "Check new message",
- "Check new message Check new message Check new message Check new message Check new message" };
-
- private static Throwable tCause = new Throwable("Throwable for exception");
-
- /**
- * Test for <code>SSLException(String)</code> constructor Assertion:
- * constructs SSLException with detail message msg. Parameter
- * <code>msg</code> is not null.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "SSLException",
- args = {java.lang.String.class}
- )
- public void testSSLException01() {
- SSLException sE;
- for (int i = 0; i < msgs.length; i++) {
- sE = new SSLException(msgs[i]);
- assertEquals("getMessage() must return: ".concat(msgs[i]), sE.getMessage(), msgs[i]);
- assertNull("getCause() must return null", sE.getCause());
- }
- }
-
- /**
- * Test for <code>SSLException(String)</code> constructor Assertion:
- * constructs SSLException when <code>msg</code> is null
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "SSLException",
- args = {java.lang.String.class}
- )
- public void testSSLException02() {
- String msg = null;
- SSLException sE = new SSLException(msg);
- assertNull("getMessage() must return null.", sE.getMessage());
- assertNull("getCause() must return null", sE.getCause());
- }
-
- /**
- * Test for <code>SSLException(Throwable)</code> constructor
- * Assertion: constructs SSLException when <code>cause</code> is null
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "SSLException",
- args = {java.lang.Throwable.class}
- )
- public void testSSLException03() {
- Throwable cause = null;
- SSLException sE = new SSLException(cause);
- assertNull("getMessage() must return null.", sE.getMessage());
- assertNull("getCause() must return null", sE.getCause());
- }
-
- /**
- * Test for <code>SSLException(Throwable)</code> constructor
- * Assertion: constructs SSLException when <code>cause</code> is not
- * null
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "SSLException",
- args = {java.lang.Throwable.class}
- )
- public void testSSLException04() {
- SSLException sE = new SSLException(tCause);
- if (sE.getMessage() != null) {
- String toS = tCause.toString();
- String getM = sE.getMessage();
- assertTrue("getMessage() should contain ".concat(toS), (getM
- .indexOf(toS) != -1));
- }
- assertNotNull("getCause() must not return null", sE.getCause());
- assertEquals("getCause() must return ".concat(tCause.toString()), sE.getCause(), tCause);
- }
-
- /**
- * Test for <code>SSLException(String, Throwable)</code> constructor
- * Assertion: constructs SSLException when <code>cause</code> is null
- * <code>msg</code> is null
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "SSLException",
- args = {java.lang.String.class, java.lang.Throwable.class}
- )
- public void testSSLException05() {
- SSLException sE = new SSLException(null, null);
- assertNull("getMessage() must return null", sE.getMessage());
- assertNull("getCause() must return null", sE.getCause());
- }
-
- /**
- * Test for <code>SSLException(String, Throwable)</code> constructor
- * Assertion: constructs SSLException when <code>cause</code> is null
- * <code>msg</code> is not null
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "SSLException",
- args = {java.lang.String.class, java.lang.Throwable.class}
- )
- public void testSSLException06() {
- SSLException sE;
- for (int i = 0; i < msgs.length; i++) {
- sE = new SSLException(msgs[i], null);
- assertEquals("getMessage() must return: ".concat(msgs[i]), sE
- .getMessage(), msgs[i]);
- assertNull("getCause() must return null", sE.getCause());
- }
- }
-
- /**
- * Test for <code>SSLException(String, Throwable)</code> constructor
- * Assertion: constructs SSLException when <code>cause</code> is not
- * null <code>msg</code> is null
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "SSLException",
- args = {java.lang.String.class, java.lang.Throwable.class}
- )
- public void testSSLException07() {
- SSLException sE = new SSLException(null, tCause);
- if (sE.getMessage() != null) {
- String toS = tCause.toString();
- String getM = sE.getMessage();
- assertTrue("getMessage() must should ".concat(toS), (getM
- .indexOf(toS) != -1));
- }
- assertNotNull("getCause() must not return null", sE.getCause());
- assertEquals("getCause() must return ".concat(tCause.toString()), sE
- .getCause(), tCause);
- }
-
- /**
- * Test for <code>SSLException(String, Throwable)</code> constructor
- * Assertion: constructs SSLException when <code>cause</code> is not
- * null <code>msg</code> is not null
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "SSLException",
- args = {java.lang.String.class, java.lang.Throwable.class}
- )
- public void testSSLException08() {
- SSLException sE;
- for (int i = 0; i < msgs.length; i++) {
- sE = new SSLException(msgs[i], tCause);
- String getM = sE.getMessage();
- String toS = tCause.toString();
- if (msgs[i].length() > 0) {
- assertTrue("getMessage() must contain ".concat(msgs[i]), getM
- .indexOf(msgs[i]) != -1);
- if (!getM.equals(msgs[i])) {
- assertTrue("getMessage() should contain ".concat(toS), getM
- .indexOf(toS) != -1);
- }
- }
- assertNotNull("getCause() must not return null", sE.getCause());
- assertEquals("getCause() must return ".concat(tCause.toString()),
- sE.getCause(), tCause);
- }
- }
-} \ No newline at end of file
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/SSLHandshakeExceptionTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/SSLHandshakeExceptionTest.java
deleted file mode 100644
index 45bf262..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/SSLHandshakeExceptionTest.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import javax.net.ssl.SSLHandshakeException;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(SSLHandshakeException.class)
-public class SSLHandshakeExceptionTest extends TestCase {
-
- private static String[] msgs = {
- "",
- "Check new message",
- "Check new message Check new message Check new message Check new message Check new message" };
-
-
- /**
- * Test for <code>SSLHandshakeException(String)</code> constructor Assertion:
- * constructs SSLHandshakeException with detail message msg. Parameter
- * <code>msg</code> is not null.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "SSLHandshakeException",
- args = {java.lang.String.class}
- )
- public void test_Constructor01() {
- SSLHandshakeException sslE;
- for (int i = 0; i < msgs.length; i++) {
- sslE = new SSLHandshakeException(msgs[i]);
- assertEquals("getMessage() must return: ".concat(msgs[i]), sslE.getMessage(), msgs[i]);
- assertNull("getCause() must return null", sslE.getCause());
- }
- }
-
- /**
- * Test for <code>SSLHandshakeException(String)</code> constructor Assertion:
- * constructs SSLHandshakeException with detail message msg. Parameter
- * <code>msg</code> is null.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "SSLHandshakeException",
- args = {java.lang.String.class}
- )
- public void test_Constructor02() {
- String msg = null;
- SSLHandshakeException sslE = new SSLHandshakeException(msg);
- assertNull("getMessage() must return null.", sslE.getMessage());
- assertNull("getCause() must return null", sslE.getCause());
- }
-} \ No newline at end of file
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/SSLKeyExceptionTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/SSLKeyExceptionTest.java
deleted file mode 100644
index 7d3b48a..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/SSLKeyExceptionTest.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import javax.net.ssl.SSLKeyException;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(SSLKeyException.class)
-public class SSLKeyExceptionTest extends TestCase {
-
- private static String[] msgs = {
- "",
- "Check new message",
- "Check new message Check new message Check new message Check new message Check new message" };
-
-
- /**
- * Test for <code>SSLKeyException(String)</code> constructor Assertion:
- * constructs SSLKeyException with detail message msg. Parameter
- * <code>msg</code> is not null.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "SSLKeyException",
- args = {java.lang.String.class}
- )
- public void test_Constructor01() {
- SSLKeyException skE;
- for (int i = 0; i < msgs.length; i++) {
- skE = new SSLKeyException(msgs[i]);
- assertEquals("getMessage() must return: ".concat(msgs[i]), skE.getMessage(), msgs[i]);
- assertNull("getCause() must return null", skE.getCause());
- }
- }
-
- /**
- * Test for <code>SSLPeerUnverifiedException(String)</code> constructor Assertion:
- * constructs SSLPeerUnverifiedException with detail message msg. Parameter
- * <code>msg</code> is null.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "SSLKeyException",
- args = {java.lang.String.class}
- )
- public void test_Constructor02() {
- String msg = null;
- SSLKeyException skE = new SSLKeyException(msg);
- assertNull("getMessage() must return null.", skE.getMessage());
- assertNull("getCause() must return null", skE.getCause());
- }
-} \ No newline at end of file
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/SSLPeerUnverifiedExceptionTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/SSLPeerUnverifiedExceptionTest.java
deleted file mode 100644
index 7e4c9be..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/SSLPeerUnverifiedExceptionTest.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import javax.net.ssl.SSLPeerUnverifiedException;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(SSLPeerUnverifiedException.class)
-public class SSLPeerUnverifiedExceptionTest extends TestCase {
-
- private static String[] msgs = {
- "",
- "Check new message",
- "Check new message Check new message Check new message Check new message Check new message" };
-
-
- /**
- * Test for <code>SSLPeerUnverifiedException(String)</code> constructor Assertion:
- * constructs SSLPeerUnverifiedException with detail message msg. Parameter
- * <code>msg</code> is not null.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "SSLPeerUnverifiedException",
- args = {java.lang.String.class}
- )
- public void test_Constructor01() {
- SSLPeerUnverifiedException sslE;
- for (int i = 0; i < msgs.length; i++) {
- sslE = new SSLPeerUnverifiedException(msgs[i]);
- assertEquals("getMessage() must return: ".concat(msgs[i]), sslE.getMessage(), msgs[i]);
- assertNull("getCause() must return null", sslE.getCause());
- }
- }
-
- /**
- * Test for <code>SSLPeerUnverifiedException(String)</code> constructor Assertion:
- * constructs SSLPeerUnverifiedException with detail message msg. Parameter
- * <code>msg</code> is null.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "SSLPeerUnverifiedException",
- args = {java.lang.String.class}
- )
- public void test_Constructor02() {
- String msg = null;
- SSLPeerUnverifiedException sslE = new SSLPeerUnverifiedException(msg);
- assertNull("getMessage() must return null.", sslE.getMessage());
- assertNull("getCause() must return null", sslE.getCause());
- }
-}
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/SSLPermissionTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/SSLPermissionTest.java
deleted file mode 100644
index 4da9553..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/SSLPermissionTest.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import javax.net.ssl.SSLPermission;
-import junit.framework.TestCase;
-
-
-/**
- * Tests for <code>SSLPermission</code> class constructors.
- *
- */
-@TestTargetClass(SSLPermission.class)
-public class SSLPermissionTest extends TestCase {
-
- /*
- * Class under test for void SSLPermission(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SSLPermission",
- args = {String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- try {
- SSLPermission p = new SSLPermission("name");
- assertEquals("Incorrect permission name", "name", p.getName());
- try {
- p = new SSLPermission(null);
- } catch (NullPointerException npe) {
- //expected
- }
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- /*
- * Class under test for void SSLPermission(String, String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SSLPermission",
- args = {String.class, String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_String() {
- try {
- SSLPermission p = new SSLPermission("name", "value");
- assertEquals("Incorrect permission name", "name", p.getName());
- assertEquals("Incorrect default permission actions",
- "", p.getActions());
- try {
- p = new SSLPermission(null, "value");
- } catch (NullPointerException npe) {
- //expected
- }
- try {
- p = new SSLPermission("name", null);
- } catch (NullPointerException npe) {
- //expected
- }
- try {
- p = new SSLPermission(null, null);
- } catch (NullPointerException npe) {
- //expected
- }
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-}
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/SSLProtocolExceptionTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/SSLProtocolExceptionTest.java
deleted file mode 100644
index 9b8b22c..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/SSLProtocolExceptionTest.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import javax.net.ssl.SSLProtocolException;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(SSLProtocolException.class)
-public class SSLProtocolExceptionTest extends TestCase {
-
- private static String[] msgs = {
- "",
- "Check new message",
- "Check new message Check new message Check new message Check new message Check new message" };
-
-
- /**
- * Test for <code>SSLProtocolException(String)</code> constructor Assertion:
- * constructs SSLProtocolException with detail message msg. Parameter
- * <code>msg</code> is not null.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "SSLProtocolException",
- args = {java.lang.String.class}
- )
- public void test_Constructor01() {
- SSLProtocolException sslE;
- for (int i = 0; i < msgs.length; i++) {
- sslE = new SSLProtocolException(msgs[i]);
- assertEquals("getMessage() must return: ".concat(msgs[i]), sslE.getMessage(), msgs[i]);
- assertNull("getCause() must return null", sslE.getCause());
- }
- }
-
- /**
- * Test for <code>SSLProtocolException(String)</code> constructor Assertion:
- * constructs SSLProtocolException with detail message msg. Parameter
- * <code>msg</code> is null.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "SSLProtocolException",
- args = {java.lang.String.class}
- )
- public void test_Constructor02() {
- String msg = null;
- SSLProtocolException sslE = new SSLProtocolException(msg);
- assertNull("getMessage() must return null.", sslE.getMessage());
- assertNull("getCause() must return null", sslE.getCause());
- }
-} \ No newline at end of file
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/SSLServerSocketFactoryTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/SSLServerSocketFactoryTest.java
deleted file mode 100644
index 979d574..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/SSLServerSocketFactoryTest.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.ServerSocket;
-
-import javax.net.ssl.SSLServerSocketFactory;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(SSLServerSocketFactory.class)
-public class SSLServerSocketFactoryTest extends TestCase {
-
- private class MockSSLServerSocketFactory extends SSLServerSocketFactory {
- public MockSSLServerSocketFactory() {
- super();
- }
-
- @Override
- public String[] getDefaultCipherSuites() {
- return null;
- }
-
- @Override
- public String[] getSupportedCipherSuites() {
- return null;
- }
-
- @Override
- public ServerSocket createServerSocket(int arg0) throws IOException {
- return null;
- }
-
- @Override
- public ServerSocket createServerSocket(int arg0, int arg1)
- throws IOException {
- return null;
- }
-
- @Override
- public ServerSocket createServerSocket(int arg0, int arg1,
- InetAddress arg2) throws IOException {
- return null;
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLServerSocketFactory#SSLServerSocketFactory()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SSLServerSocketFactory",
- args = {}
- )
- public void test_Constructor() {
- try {
- MockSSLServerSocketFactory ssf = new MockSSLServerSocketFactory();
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLServerSocketFactory#getDefault()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDefault",
- args = {}
- )
- public void test_getDefault() {
- assertNotNull("Incorrect default socket factory",
- SSLServerSocketFactory.getDefault());
- }
-
- /**
- * @tests javax.net.ssl.SSLServerSocketFactory#getDefaultCipherSuites()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDefaultCipherSuites",
- args = {}
- )
- public void test_getDefaultCipherSuites() {
- SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory
- .getDefault();
- try {
- assertTrue(ssf.getDefaultCipherSuites().length > 0);
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLServerSocketFactory#getSupportedCipherSuites()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSupportedCipherSuites",
- args = {}
- )
- public void test_getSupportedCipherSuites() {
- SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory
- .getDefault();
- try {
- assertTrue(ssf.getSupportedCipherSuites().length > 0);
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
- }
-}
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/SSLServerSocketTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/SSLServerSocketTest.java
deleted file mode 100644
index d12959b..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/SSLServerSocketTest.java
+++ /dev/null
@@ -1,614 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.luni.util.Base64;
-
-import tests.support.Support_PortManager;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.InetAddress;
-import java.security.KeyStore;
-import java.security.SecureRandom;
-import java.util.Arrays;
-
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLServerSocket;
-
-@TestTargetClass(SSLServerSocket.class)
-public class SSLServerSocketTest extends TestCase {
-
- // set to true if on Android, false if on RI
- boolean useBKS = true;
-
- /**
- * Additional class for SSLServerSocket constructor verification
- */
- class mySSLServerSocket extends SSLServerSocket {
-
- public mySSLServerSocket() throws IOException{
- super();
- }
-
- public mySSLServerSocket(int port) throws IOException{
- super(port);
- }
-
- public mySSLServerSocket(int port, int backlog) throws IOException{
- super(port, backlog);
- }
-
- public mySSLServerSocket(int port, int backlog, InetAddress address) throws IOException{
- super(port, backlog, address);
- }
-
- public String[] getSupportedCipherSuites() {
- return null;
- }
-
- public void setEnabledCipherSuites(String[] suites) {
-
- }
-
- public String[] getEnabledCipherSuites() {
- return null;
- }
-
- public String[] getSupportedProtocols() {
- return null;
- }
-
- public String[] getEnabledProtocols() {
- return null;
- }
-
- public void setEnabledProtocols(String[] protocols) {
-
- }
-
- public void setEnableSessionCreation(boolean flag) {
-
- }
-
- public boolean getEnableSessionCreation() {
- return false;
- }
-
- public void setNeedClientAuth(boolean need) {
-
- }
-
- public boolean getNeedClientAuth() {
- return false;
- }
-
- public boolean getUseClientMode() {
- return false;
- }
-
- public void setUseClientMode(boolean mode) {
-
- }
-
- public boolean getWantClientAuth() {
- return false;
- }
- public void setWantClientAuth(boolean mode) {
-
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLServerSocket#SSLServerSocket()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "IOException wasn't implemented",
- method = "SSLServerSocket",
- args = {}
- )
- public void testConstructor_01() {
- try {
- SSLServerSocket ssl = new mySSLServerSocket();
- } catch (Exception ex) {
- fail("Unexpected exception was thrown " + ex);
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLServerSocket#SSLServerSocket(int port)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SSLServerSocket",
- args = {int.class}
- )
- public void testConstructor_02() {
- SSLServerSocket ssl;
- int portNumber = Support_PortManager.getNextPort();
- int[] port_invalid = {-1, 65536, Integer.MIN_VALUE, Integer.MAX_VALUE};
-
- try {
- ssl = new mySSLServerSocket(portNumber);
- assertEquals(portNumber, ssl.getLocalPort());
- } catch (Exception ex) {
- fail("Unexpected exception was thrown " + ex);
- }
-
- for (int i = 0; i < port_invalid.length; i++) {
- try {
- ssl = new mySSLServerSocket(port_invalid[i]);
- fail("IllegalArgumentException should be thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
- }
-
- try {
- ssl = new mySSLServerSocket(portNumber);
- new mySSLServerSocket(portNumber);
- fail("IOException Expected when opening an already opened port");
- } catch (IOException ioe) {
- // expected
- } catch (Exception ex) {
- fail("Unexpected exception was thrown " + ex);
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLServerSocket#SSLServerSocket(int port, int backlog)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Invalid values for backlog weren't checked",
- method = "SSLServerSocket",
- args = {int.class, int.class}
- )
- public void testConstructor_03() {
- mySSLServerSocket ssl;
- int portNumber = Support_PortManager.getNextPort();
- int[] port_invalid = {-1, Integer.MIN_VALUE, Integer.MAX_VALUE};
-
- try {
- ssl = new mySSLServerSocket(portNumber, 1);
- assertEquals(portNumber, ssl.getLocalPort());
- } catch (Exception ex) {
- fail("Unexpected exception was thrown");
- }
-
- for (int i = 0; i < port_invalid.length; i++) {
- try {
- ssl = new mySSLServerSocket(port_invalid[i], 1);
- fail("IllegalArgumentException should be thrown");
- } catch (IllegalArgumentException iae) {
- // expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
- }
-
- portNumber = Support_PortManager.getNextPort();
- try {
- ssl = new mySSLServerSocket(portNumber, 1);
- new mySSLServerSocket(portNumber, 1);
- fail("IOException should be thrown");
- } catch (IOException ioe) {
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLServerSocket#SSLServerSocket(int port, int backlog, InetAddress address)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Invalid values for backlog weren\'t checked",
- method = "SSLServerSocket",
- args = {int.class, int.class, InetAddress.class}
- )
- public void testConstructor_04() {
- mySSLServerSocket ssl;
- InetAddress ia = null;
- int portNumber = Support_PortManager.getNextPort();
- int[] port_invalid = {-1, 65536, Integer.MIN_VALUE, Integer.MAX_VALUE};
-
- try {
- ssl = new mySSLServerSocket(portNumber, 0, ia);
- assertEquals(portNumber, ssl.getLocalPort());
- } catch (Exception ex) {
- fail("Unexpected exception was thrown");
- }
-
- portNumber = Support_PortManager.getNextPort();
- try {
- ssl = new mySSLServerSocket(portNumber, 0, InetAddress.getLocalHost());
- assertEquals(portNumber, ssl.getLocalPort());
- } catch (Exception ex) {
- fail("Unexpected exception was thrown");
- }
-
- for (int i = 0; i < port_invalid.length; i++) {
- try {
- ssl = new mySSLServerSocket(port_invalid[i], 1, InetAddress.getLocalHost());
- fail("IllegalArgumentException should be thrown");
- } catch (IllegalArgumentException iae) {
- // expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
- }
-
- portNumber = Support_PortManager.getNextPort();
- try {
- ssl = new mySSLServerSocket(portNumber, 0, InetAddress.getLocalHost());
- new mySSLServerSocket(portNumber, 0, InetAddress.getLocalHost());
- fail("IOException should be thrown for");
- } catch (IOException ioe) {
- }
- }
-
- /**
- * @throws Exception
- * @tests javax.net.ssl.SSLServerSocket#getSupportedCipherSuites()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSupportedCipherSuites",
- args = {}
- )
- public void test_getSupportedCipherSuites() throws Exception {
- SSLServerSocket sss = getSSLServerSocket();
- String[] res = sss.getSupportedCipherSuites();
- assertNotNull("NULL result", res);
- assertTrue("no supported cipher suites available.", res.length > 0);
- }
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.SSLServerSocket#getEnabledCipherSuites()
- * @tests javax.net.ssl.SSLServerSocket#setEnabledCipherSuites(String[] suites)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getEnabledCipherSuites",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setEnabledCipherSuites",
- args = {String[].class}
- )
- })
- public void test_EnabledCipherSuites() throws Exception {
- SSLServerSocket sss = getSSLServerSocket();
- try {
- sss.setEnabledCipherSuites(null);
- } catch (IllegalArgumentException iae) {
- //expected
- }
- String[] unsupportedCipherSuites = {"unsupported"};
- try {
- sss.setEnabledCipherSuites(unsupportedCipherSuites);
- } catch (IllegalArgumentException iae) {
- //expected
- }
- int count = sss.getSupportedCipherSuites().length;
- assertTrue("No supported cipher suites", count > 0);
- sss.setEnabledCipherSuites(sss.getSupportedCipherSuites());
- String[] res = sss.getEnabledCipherSuites();
- assertNotNull("NULL result", res);
- assertEquals("not all supported cipher suites were enabled",
- Arrays.asList(sss.getSupportedCipherSuites()),
- Arrays.asList(res));
- }
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.SSLServerSocket#getSupportedProtocols()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSupportedProtocols",
- args = {}
- )
- public void test_getSupportedProtocols() throws Exception {
- SSLServerSocket sss = getSSLServerSocket();
- String[] res = sss.getSupportedCipherSuites();
- assertNotNull("NULL result", res);
- assertTrue("no supported protocols available.", res.length > 0);
- }
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.SSLServerSocket#getEnabledProtocols()
- * @tests javax.net.ssl.SSLServerSocket#setEnabledProtocols(String[] protocols)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setEnabledProtocols",
- args = {String[].class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getEnabledProtocols",
- args = {}
- )
- })
- public void test_EnabledProtocols() throws Exception {
- SSLServerSocket sss = getSSLServerSocket();
- try {
- sss.setEnabledProtocols(null);
- } catch (IllegalArgumentException iae) {
- //expected
- }
- String[] unsupportedProtocols = {"unsupported"};
- try {
- sss.setEnabledProtocols(unsupportedProtocols);
- } catch (IllegalArgumentException iae) {
- //expected
- }
- int count = sss.getSupportedProtocols().length;
- assertTrue("No supported protocols", count > 0);
- sss.setEnabledProtocols(sss.getSupportedProtocols());
- String[] res = sss.getEnabledProtocols();
- assertNotNull("NULL result", res);
- assertTrue("no enabled protocols.", res.length == count);
- }
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.SSLServerSocket#setEnableSessionCreation(boolean flag)
- * @tests javax.net.ssl.SSLServerSocket#getEnableSessionCreation()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getEnableSessionCreation",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setEnableSessionCreation",
- args = {boolean.class}
- )
- })
- public void test_EnableSessionCreation() throws Exception {
- SSLServerSocket sss = getSSLServerSocket();
- assertTrue(sss.getEnableSessionCreation());
- sss.setEnableSessionCreation(false);
- assertFalse(sss.getEnableSessionCreation());
- sss.setEnableSessionCreation(true);
- assertTrue(sss.getEnableSessionCreation());
- }
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.SSLServerSocket#setNeedClientAuth(boolean need)
- * @tests javax.net.ssl.SSLServerSocket#getNeedClientAuthCreation()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setNeedClientAuth",
- args = {boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getNeedClientAuth",
- args = {}
- )
- })
- public void test_NeedClientAuth() throws Exception {
- SSLServerSocket sss = getSSLServerSocket();
- sss.setNeedClientAuth(true);
- assertTrue(sss.getNeedClientAuth());
- sss.setNeedClientAuth(false);
- assertFalse(sss.getNeedClientAuth());
- }
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.SSLServerSocket#getUseClientMode()
- * @tests javax.net.ssl.SSLServerSocket#setUseClientMode(boolean mode)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getUseClientMode",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setUseClientMode",
- args = {boolean.class}
- )
- })
- public void test_UseClientMode() throws Exception {
- SSLServerSocket sss = getSSLServerSocket();
- sss.setUseClientMode(false);
- assertFalse(sss.getUseClientMode());
- sss.setUseClientMode(true);
- assertTrue(sss.getUseClientMode());
- }
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.SSLServerSocket#setWantClientAuth(boolean want)
- * @tests javax.net.ssl.SSLServerSocket#getWantClientAuthCreation()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getWantClientAuth",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setWantClientAuth",
- args = {boolean.class}
- )
- })
- public void test_WantClientAuth() throws Exception {
- SSLServerSocket sss = getSSLServerSocket();
- sss.setWantClientAuth(true);
- assertTrue(sss.getWantClientAuth());
- sss.setWantClientAuth(false);
- assertFalse(sss.getWantClientAuth());
- }
-
-
- /**
- * Defines the keystore contents for the server, BKS version. Holds just a
- * single self-generated key. The subject name is "Test Server".
- */
- private static final String SERVER_KEYS_BKS =
- "AAAAAQAAABQDkebzoP1XwqyWKRCJEpn/t8dqIQAABDkEAAVteWtleQAAARpYl20nAAAAAQAFWC41" +
- "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU1jANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET" +
- "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV" +
- "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMB4XDTA4MDYwNTExNTgxNFoXDTA4MDkw" +
- "MzExNTgxNFowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U" +
- "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IFNlcnZl" +
- "cjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0LIdKaIr9/vsTq8BZlA3R+NFWRaH4lGsTAQy" +
- "DPMF9ZqEDOaL6DJuu0colSBBBQ85hQTPa9m9nyJoN3pEi1hgamqOvQIWcXBk+SOpUGRZZFXwniJV" +
- "zDKU5nE9MYgn2B9AoiH3CSuMz6HRqgVaqtppIe1jhukMc/kHVJvlKRNy9XMCAwEAATANBgkqhkiG" +
- "9w0BAQUFAAOBgQC7yBmJ9O/eWDGtSH9BH0R3dh2NdST3W9hNZ8hIa8U8klhNHbUCSSktZmZkvbPU" +
- "hse5LI3dh6RyNDuqDrbYwcqzKbFJaq/jX9kCoeb3vgbQElMRX8D2ID1vRjxwlALFISrtaN4VpWzV" +
- "yeoHPW4xldeZmoVtjn8zXNzQhLuBqX2MmAAAAqwAAAAUvkUScfw9yCSmALruURNmtBai7kQAAAZx" +
- "4Jmijxs/l8EBaleaUru6EOPioWkUAEVWCxjM/TxbGHOi2VMsQWqRr/DZ3wsDmtQgw3QTrUK666sR" +
- "MBnbqdnyCyvM1J2V1xxLXPUeRBmR2CXorYGF9Dye7NkgVdfA+9g9L/0Au6Ugn+2Cj5leoIgkgApN" +
- "vuEcZegFlNOUPVEs3SlBgUF1BY6OBM0UBHTPwGGxFBBcetcuMRbUnu65vyDG0pslT59qpaR0TMVs" +
- "P+tcheEzhyjbfM32/vwhnL9dBEgM8qMt0sqF6itNOQU/F4WGkK2Cm2v4CYEyKYw325fEhzTXosck" +
- "MhbqmcyLab8EPceWF3dweoUT76+jEZx8lV2dapR+CmczQI43tV9btsd1xiBbBHAKvymm9Ep9bPzM" +
- "J0MQi+OtURL9Lxke/70/MRueqbPeUlOaGvANTmXQD2OnW7PISwJ9lpeLfTG0LcqkoqkbtLKQLYHI" +
- "rQfV5j0j+wmvmpMxzjN3uvNajLa4zQ8l0Eok9SFaRr2RL0gN8Q2JegfOL4pUiHPsh64WWya2NB7f" +
- "V+1s65eA5ospXYsShRjo046QhGTmymwXXzdzuxu8IlnTEont6P4+J+GsWk6cldGbl20hctuUKzyx" +
- "OptjEPOKejV60iDCYGmHbCWAzQ8h5MILV82IclzNViZmzAapeeCnexhpXhWTs+xDEYSKEiG/camt" +
- "bhmZc3BcyVJrW23PktSfpBQ6D8ZxoMfF0L7V2GQMaUg+3r7ucrx82kpqotjv0xHghNIm95aBr1Qw" +
- "1gaEjsC/0wGmmBDg1dTDH+F1p9TInzr3EFuYD0YiQ7YlAHq3cPuyGoLXJ5dXYuSBfhDXJSeddUkl" +
- "k1ufZyOOcskeInQge7jzaRfmKg3U94r+spMEvb0AzDQVOKvjjo1ivxMSgFRZaDb/4qw=";
-
- /**
- * Defines the keystore contents for the server, JKS version. Holds just a
- * single self-generated key. The subject name is "Test Server".
- */
- private static final String SERVER_KEYS_JKS =
- "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFfBeAAAArowggK2MA4GCisGAQQBKgIRAQEFAASC" +
- "AqI2kp5XjnF8YZkhcF92YsJNQkvsmH7zqMM87j23zSoV4DwyE3XeC/gZWq1ToScIhoqZkzlbWcu4" +
- "T/Zfc/DrfGk/rKbBL1uWKGZ8fMtlZk8KoAhxZk1JSyJvdkyKxqmzUbxk1OFMlN2VJNu97FPVH+du" +
- "dvjTvmpdoM81INWBW/1fZJeQeDvn4mMbbe0IxgpiLnI9WSevlaDP/sm1X3iO9yEyzHLL+M5Erspo" +
- "Cwa558fOu5DdsICMXhvDQxjWFKFhPHnKtGe+VvwkG9/bAaDgx3kfhk0w5zvdnkKb+8Ed9ylNRzdk" +
- "ocAa/mxlMTOsTvDKXjjsBupNPIIj7OP4GNnZaxkJjSs98pEO67op1GX2qhy6FSOPNuq8k/65HzUc" +
- "PYn6voEeh6vm02U/sjEnzRevQ2+2wXoAdp0EwtQ/DlMe+NvcwPGWKuMgX4A4L93DZGb04N2VmAU3" +
- "YLOtZwTO0LbuWrcCM/q99G/7LcczkxIVrO2I/rh8RXVczlf9QzcrFObFv4ATuspWJ8xG7DhsMbnk" +
- "rT94Pq6TogYeoz8o8ZMykesAqN6mt/9+ToIemmXv+e+KU1hI5oLwWMnUG6dXM6hIvrULY6o+QCPH" +
- "172YQJMa+68HAeS+itBTAF4Clm/bLn6reHCGGU6vNdwU0lYldpiOj9cB3t+u2UuLo6tiFWjLf5Zs" +
- "EQJETd4g/EK9nHxJn0GAKrWnTw7pEHQJ08elzUuy04C/jEEG+4QXU1InzS4o/kR0Sqz2WTGDoSoq" +
- "ewuPRU5bzQs/b9daq3mXrnPtRBL6HfSDAdpTK76iHqLCGdqx3avHjVSBm4zFvEuYBCev+3iKOBmg" +
- "yh7eQRTjz4UOWfy85omMBr7lK8PtfVBDzOXpasxS0uBgdUyBDX4tO6k9jZ8a1kmQRQAAAAEABVgu" +
- "NTA5AAACSDCCAkQwggGtAgRIR8SKMA0GCSqGSIb3DQEBBAUAMGkxCzAJBgNVBAYTAlVTMRMwEQYD" +
- "VQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzANBgNVBAoTBkdvb2dsZTEQMA4GA1UECxMH" +
- "QW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBTZXJ2ZXIwHhcNMDgwNjA1MTA0ODQyWhcNMDgwOTAzMTA0" +
- "ODQyWjBpMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8w" +
- "DQYDVQQKEwZHb29nbGUxEDAOBgNVBAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMIGf" +
- "MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwoC6chqCI84rj1PrXuJgbiit4EV909zR6N0jNlYfg" +
- "itwB39bP39wH03rFm8T59b3mbSptnGmCIpLZn25KPPFsYD3JJ+wFlmiUdEP9H05flfwtFQJnw9uT" +
- "3rRIdYVMPcQ3RoZzwAMliGr882I2thIDbA6xjGU/1nRIdvk0LtxH3QIDAQABMA0GCSqGSIb3DQEB" +
- "BAUAA4GBAJn+6YgUlY18Ie+0+Vt8oEi81DNi/bfPrAUAh63fhhBikx/3R9dl3wh09Z6p7cIdNxjW" +
- "n2ll+cRW9eqF7z75F0Omm0C7/KAEPjukVbszmzeU5VqzkpSt0j84YWi+TfcHRrfvhLbrlmGITVpY" +
- "ol5pHLDyqGmDs53pgwipWqsn/nEXEBgj3EoqPeqHbDf7YaP8h/5BSt0=";
-
- private String PASSWORD = "android";
-
- /**
- * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
- * for the result.
- */
- private KeyManager[] getKeyManagers() throws Exception {
- String keys = (useBKS ? SERVER_KEYS_BKS : SERVER_KEYS_JKS);
- byte[] bytes = new Base64().decode(keys.getBytes());
- InputStream inputStream = new ByteArrayInputStream(bytes);
-
- KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
- keyStore.load(inputStream, PASSWORD.toCharArray());
- inputStream.close();
-
- String algorithm = KeyManagerFactory.getDefaultAlgorithm();
- KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
- keyManagerFactory.init(keyStore, PASSWORD.toCharArray());
-
- return keyManagerFactory.getKeyManagers();
- }
-
- private SSLServerSocket getSSLServerSocket() throws Exception {
- SSLContext context = SSLContext.getInstance("TLS");
- context.init(getKeyManagers(), null, null);
- SSLServerSocket sss = (SSLServerSocket) context.getServerSocketFactory()
- .createServerSocket();
- return sss;
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Guard against native resource leakage.",
- method = "SSLSocket",
- args = {}
- )
- public void test_creationStressTest() throws Exception {
- KeyManager[] keyManagers = getKeyManagers();
- // Test the default codepath, which uses /dev/urandom.
- SSLContext sslContext = SSLContext.getInstance("TLS");
- sslContext.init(keyManagers, null, null);
- for (int i = 0; i < 2048; ++i) {
- sslContext.getServerSocketFactory().createServerSocket();
- }
-
- // Test the other codepath, which copies a seed from a byte[].
- sslContext.init(keyManagers, null, new SecureRandom());
- for (int i = 0; i < 2048; ++i) {
- sslContext.getServerSocketFactory().createServerSocket();
- }
- }
-}
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/SSLSessionBindingEventTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/SSLSessionBindingEventTest.java
deleted file mode 100644
index f95c941..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/SSLSessionBindingEventTest.java
+++ /dev/null
@@ -1,260 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.security.Principal;
-import java.security.cert.Certificate;
-
-import javax.net.ssl.SSLPeerUnverifiedException;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSessionContext;
-import javax.net.ssl.SSLSessionBindingEvent;
-import javax.security.cert.X509Certificate;
-
-import junit.framework.TestCase;
-
-/**
- * Tests for <code>SSLSessionBindingEvent</code> class constructors and methods.
- *
- */
-@TestTargetClass(SSLSessionBindingEvent.class)
-public class SSLSessionBindingEventTest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SSLSessionBindingEvent",
- args = {javax.net.ssl.SSLSession.class, java.lang.String.class}
- )
- public final void test_ConstructorLjavax_net_ssl_SSLSessionLjava_lang_String() {
- SSLSession ses = new MySSLSession();
-
- try {
- SSLSessionBindingEvent event = new SSLSessionBindingEvent(ses, "test");
- if (!"test".equals(event.getName())) {
- fail("incorrect name");
- }
- if (!event.getSession().equals(ses)) {
- fail("incorrect session");
- }
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
-
- try {
- SSLSessionBindingEvent event = new SSLSessionBindingEvent(null, "test");
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- try {
- SSLSessionBindingEvent event = new SSLSessionBindingEvent(ses, null);
- } catch (IllegalArgumentException e) {
- fail("Unexpected IllegalArgumentException: " + e);
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLSessionBindingEvent#getName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getName",
- args = {}
- )
- public void test_getName() {
- SSLSession ses = new MySSLSession();
- SSLSessionBindingEvent event = new SSLSessionBindingEvent(ses, "test");
- assertEquals("Incorrect session name", "test", event.getName());
- event = new SSLSessionBindingEvent(ses, null);
- assertEquals("Incorrect session name", null, event.getName());
- }
-
- /**
- * @tests javax.net.ssl.SSLSessionBindingEvent#getSession()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSession",
- args = {}
- )
- public void test_getSession() {
- SSLSession ses = new MySSLSession();
- SSLSessionBindingEvent event = new SSLSessionBindingEvent(ses, "test");
- assertEquals("Incorrect session", ses, event.getSession());
- }
-}
-
-class MySSLSession implements SSLSession {
- /*
- * @see javax.net.ssl.SSLSession#getApplicationBufferSize()
- */
- public int getApplicationBufferSize() {
- return 0;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getCipherSuite()
- */
- public String getCipherSuite() {
- return "MyTestCipherSuite";
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getCreationTime()
- */
- public long getCreationTime() {
- return 0;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getId()
- */
- public byte[] getId() {
- return null;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getLastAccessedTime()
- */
- public long getLastAccessedTime() {
- return 0;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getLocalCertificates()
- */
- public Certificate[] getLocalCertificates() {
- return null;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getLocalPrincipal()
- */
- public Principal getLocalPrincipal() {
- return null;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getPacketBufferSize()
- */
- public int getPacketBufferSize() {
- return 0;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getPeerCertificateChain()
- */
- public X509Certificate[] getPeerCertificateChain()
- throws SSLPeerUnverifiedException {
- throw new SSLPeerUnverifiedException("test exception");
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getPeerCertificates()
- */
- public Certificate[] getPeerCertificates()
- throws SSLPeerUnverifiedException {
- throw new SSLPeerUnverifiedException("test exception");
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getPeerHost()
- */
- public String getPeerHost() {
- return null;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getPeerPort()
- */
- public int getPeerPort() {
- return 0;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getPeerPrincipal()
- */
- public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
- return null;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getProtocol()
- */
- public String getProtocol() {
- return null;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getSessionContext()
- */
- public SSLSessionContext getSessionContext() {
- return null;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getValue(java.lang.String)
- */
- public Object getValue(String name) {
- return null;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#getValueNames()
- */
- public String[] getValueNames() {
- return null;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#invalidate()
- */
- public void invalidate() {
- }
-
- /*
- * @see javax.net.ssl.SSLSession#isValid()
- */
- public boolean isValid() {
- return false;
- }
-
- /*
- * @see javax.net.ssl.SSLSession#putValue(java.lang.String,
- * java.lang.Object)
- */
- public void putValue(String name, Object value) {
- }
-
- /*
- * @see javax.net.ssl.SSLSession#removeValue(java.lang.String)
- */
- public void removeValue(String name) {
- }
-
-}
-
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/SSLSessionBindingListenerTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/SSLSessionBindingListenerTest.java
deleted file mode 100644
index 7b26485..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/SSLSessionBindingListenerTest.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import javax.net.ssl.SSLServerSocket;
-import javax.net.ssl.SSLServerSocketFactory;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSessionBindingEvent;
-import javax.net.ssl.SSLSessionBindingListener;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.SSLSocketFactory;
-
-import java.io.IOException;
-import java.net.UnknownHostException;
-
-import junit.framework.TestCase;
-
-/**
- * Tests for SSLSessionBindingListener class
- *
- */
-@TestTargetClass(SSLSessionBindingListener.class)
-public class SSLSessionBindingListenerTest extends TestCase {
-
- public class mySSLSessionBindingListener implements SSLSessionBindingListener {
-
- public boolean boundDone = false;
- public boolean unboundDone = false;
-
- mySSLSessionBindingListener() {
- }
-
- public void valueBound(SSLSessionBindingEvent event) {
- if (event != null) boundDone = true;
- }
- public void valueUnbound(SSLSessionBindingEvent event) {
- if (event != null) unboundDone = true;
- }
- }
-
- /**
- * @throws IOException
- * @throws UnknownHostException
- * @throws InterruptedException
- * @tests javax.net.ssl.SSLSessionBindingListener#valueBound(SSLSessionBindingEvent event)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueBound",
- args = {SSLSessionBindingEvent.class}
- )
- public void test_valueBound() throws UnknownHostException, IOException,
- InterruptedException {
- SSLSocket sock = (SSLSocket) SSLSocketFactory.getDefault()
- .createSocket();
- SSLSession ss = sock.getSession();
- mySSLSessionBindingListener sbl = new mySSLSessionBindingListener();
- ss.putValue("test", sbl);
- assertTrue("valueBound was not called.", sbl.boundDone);
- }
-
- /**
- * @throws IOException
- * @throws UnknownHostException
- * @tests javax.net.ssl.SSLSessionBindingListener#valueUnbound(SSLSessionBindingEvent event)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueUnbound",
- args = {SSLSessionBindingEvent.class}
- )
- public void test_valueUnbound() throws UnknownHostException, IOException {
- SSLSocket sock = (SSLSocket) SSLSocketFactory.getDefault()
- .createSocket();
- SSLSession ss = sock.getSession();
- mySSLSessionBindingListener sbl = new mySSLSessionBindingListener();
- ss.putValue("test", sbl);
- ss.removeValue("test");
- assertTrue("valueUnbound was not called.", sbl.unboundDone);
- }
-}
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/SSLSessionContextTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/SSLSessionContextTest.java
deleted file mode 100644
index 930b6da..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/SSLSessionContextTest.java
+++ /dev/null
@@ -1,141 +0,0 @@
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSessionContext;
-
-import java.security.KeyManagementException;
-import java.security.NoSuchAlgorithmException;
-
-/**
- * Tests for <code>SSLSessionContext</code> class constructors and methods.
- */
-@TestTargetClass(SSLSessionContext.class)
-public class SSLSessionContextTest extends TestCase {
-
- /**
- * @throws NoSuchAlgorithmException
- * @throws KeyManagementException
- * @tests javax.net.ssl.SSLSessionContex#getSessionCacheSize()
- * @tests javax.net.ssl.SSLSessionContex#setSessionCacheSize(int size)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSessionCacheSize",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setSessionCacheSize",
- args = {int.class}
- )
- })
- public final void test_sessionCacheSize() throws NoSuchAlgorithmException, KeyManagementException {
- SSLContext context = SSLContext.getInstance("TLS");
- context.init(null, null, null);
- SSLSessionContext sc = context
- .getClientSessionContext();
- sc.setSessionCacheSize(10);
- assertEquals("10 wasn't returned", 10, sc.getSessionCacheSize());
- sc.setSessionCacheSize(5);
- assertEquals("5 wasn't returned", 5, sc.getSessionCacheSize());
-
- try {
- sc.setSessionCacheSize(-1);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @throws KeyManagementException
- * @tests javax.net.ssl.SSLSessionContex#getSessionTimeout()
- * @tests javax.net.ssl.SSLSessionContex#setSessionTimeout(int seconds)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSessionTimeout",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setSessionTimeout",
- args = {int.class}
- )
- })
- public final void test_sessionTimeout() throws NoSuchAlgorithmException, KeyManagementException {
- SSLContext context = SSLContext.getInstance("TLS");
- context.init(null, null, null);
- SSLSessionContext sc = context
- .getClientSessionContext();
- sc.setSessionTimeout(100);
- assertEquals("100 wasn't returned", 100, sc.getSessionTimeout());
- sc.setSessionTimeout(5000);
- assertEquals("5000 wasn't returned", 5000, sc.getSessionTimeout());
-
- try {
- sc.setSessionTimeout(-1);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @throws KeyManagementException
- * @tests javax.net.ssl.SSLSessionContex#getSession(byte[] sessionId)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSession",
- args = {byte[].class}
- )
- public final void test_getSession() throws NoSuchAlgorithmException, KeyManagementException {
- SSLContext context = SSLContext.getInstance("TLS");
- context.init(null, null, null);
- SSLSessionContext sc = context
- .getClientSessionContext();
- try {
- sc.getSession(null);
- } catch (NullPointerException e) {
- // expected
- }
- assertNull(sc.getSession(new byte[5]));
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @throws KeyManagementException
- * @tests javax.net.ssl.SSLSessionContex#getIds()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getIds",
- args = {}
- )
- public final void test_getIds() throws NoSuchAlgorithmException, KeyManagementException {
- SSLContext context = SSLContext.getInstance("TLS");
- context.init(null, null, null);
- SSLSessionContext sc = context
- .getClientSessionContext();
- assertFalse(sc.getIds().hasMoreElements());
- }
-
-} \ No newline at end of file
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/SSLSessionTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/SSLSessionTest.java
deleted file mode 100644
index 6f3b61d..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/SSLSessionTest.java
+++ /dev/null
@@ -1,895 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.luni.util.Base64;
-
-import tests.api.javax.net.ssl.HandshakeCompletedEventTest.MyHandshakeListener;
-import tests.api.javax.net.ssl.HandshakeCompletedEventTest.TestTrustManager;
-import tests.support.Support_PortManager;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.security.KeyStore;
-import java.security.Principal;
-import java.security.cert.Certificate;
-import java.util.Date;
-
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLPeerUnverifiedException;
-import javax.net.ssl.SSLServerSocket;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.SSLSessionBindingEvent;
-import javax.net.ssl.SSLSessionBindingListener;
-import javax.net.ssl.TrustManager;
-import javax.security.cert.X509Certificate;
-
-/**
- * Tests for SSLSession class
- *
- */
-@TestTargetClass(SSLSession.class)
-public class SSLSessionTest extends TestCase {
-
- // set to true if on Android, false if on RI
- boolean useBKS = true;
-
- /**
- * @tests javax.net.ssl.SSLSession#getPeerHost()
- * @tests javax.net.ssl.SSLSession#getPeerPort()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPeerHost",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPeerPort",
- args = {}
- )
- })
- @AndroidOnly("Uses bks key store. Change useBKS to false to run on the RI")
- public void test_getPeerHost() {
- SSLSession s = clientSession;
- try {
- assertEquals(s.getPeerHost(), InetAddress.getLocalHost().getHostName());
- assertEquals(s.getPeerPort(), port);
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLSession#invalidate()
- * @tests javax.net.ssl.SSLSession#isValid()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "invalidate",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isValid",
- args = {}
- )
- })
- @AndroidOnly("Uses bks key store. Change useBKS to false to run on the RI")
- public void test_invalidate() {
- SSLSession s = clientSession;
- try {
- assertTrue(s.isValid());
- s.invalidate();
- assertFalse(s.isValid());
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLSession#getPeerPrincipal()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Exception wasn't implemented in the interface's class",
- method = "getPeerPrincipal",
- args = {}
- )
- @AndroidOnly("Uses bks key store. Change useBKS to false to run on the RI")
- public void test_getPeerPrincipal() {
- try {
- Principal p1 = clientSession.getPeerPrincipal();
- KeyStore store = server.getStore();
- Certificate cert = store.getCertificate("mykey");
- X509Certificate c = X509Certificate.getInstance(cert.getEncoded());
- Principal p2 = c.getSubjectDN();
- String name2 = p2.getName().replaceAll(" ", "");
- String name1 = p1.getName().replaceAll(" ", "");
- assertEquals(name2, name1);
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLSession#getApplicationBufferSize()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getApplicationBufferSize",
- args = {}
- )
- @AndroidOnly("Uses bks key store. Change useBKS to false to run on the RI")
- public void test_getApplicationBufferSize() {
- try {
- assertTrue(clientSession.getApplicationBufferSize() > 0);
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLSession#getCipherSuite()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCipherSuite",
- args = {}
- )
- @AndroidOnly("Uses bks key store. Change useBKS to false to run on the RI")
- public void test_getCipherSuite() {
- try {
- assertEquals(cipherSuite, clientSession.getCipherSuite());
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLSession#getCreationTime()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCreationTime",
- args = {}
- )
- @AndroidOnly("Uses bks key store. Change useBKS to false to run on the RI")
- public void test_getCreationTime() {
- try {
- // check if creation time was in the last 10 seconds
- long currentTime = System.currentTimeMillis();
- long sessionTime = clientSession.getCreationTime();
- long diff = currentTime - sessionTime;
- assertTrue("diff between " + currentTime + " and " + sessionTime + " should be < 10000", diff < 10000);
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLSession#getId()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getId",
- args = {}
- )
- @AndroidOnly("Uses bks key store. Change useBKS to false to run on the RI")
- public void test_getId() {
- byte[] id = clientSession.getId();
- try {
- SSLSession sess =
- clientSslContext.getClientSessionContext().getSession(id);
- assertNotNull("Could not find session for id " + id, sess);
- assertEquals(clientSession, sess);
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLSession#getLastAccessedTime()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLastAccessedTime",
- args = {}
- )
- @AndroidOnly("Uses bks key store. Change useBKS to false to run on the RI")
- public void test_getLastAccessedTime() {
- try {
- // check if last access time was in the last 10 seconds
- long currentTime = System.currentTimeMillis();
- long sessionTime = clientSession.getLastAccessedTime();
- long diff = currentTime - sessionTime;
- assertTrue("diff between " + currentTime + " and " + sessionTime + " should be < 10000", diff < 10000);
- assertTrue ("diff should be < 10000 but is " + diff, diff < 10000);
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLSession#getLocalCertificates()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocalCertificates",
- args = {}
- )
- @AndroidOnly("Uses bks key store. Change useBKS to false to run on the RI")
- public void test_getLocalCertificates() {
- try {
- KeyStore store = client.getStore();
- Certificate cert = store.getCertificate("mykey");
- Certificate[] certs = clientSession.getLocalCertificates();
- assertEquals(cert, certs[0]);
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLSession#getLocalPrincipal()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocalPrincipal",
- args = {}
- )
- @AndroidOnly("Uses bks key store. Change useBKS to false to run on the RI")
- public void test_getLocalPrincipal() {
- try {
- Principal p1 = clientSession.getLocalPrincipal();
- KeyStore store = client.getStore();
- Certificate cert = store.getCertificate("mykey");
- X509Certificate c = X509Certificate.getInstance(cert.getEncoded());
- Principal p2 = c.getSubjectDN();
- String name2 = p2.getName().replaceAll(" ", "");
- String name1 = p1.getName().replaceAll(" ", "");
- assertEquals(name2, name1);
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLSession#getPacketBufferSize()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPacketBufferSize",
- args = {}
- )
- @AndroidOnly("Uses bks key store. Change useBKS to false to run on the RI")
- public void test_getPacketBufferSize() {
- try {
- assertTrue(clientSession.getPacketBufferSize() > 0);
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLSession#getPeerCertificates()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "",
- method = "getPeerCertificates",
- args = {}
- )
- @AndroidOnly("Uses bks key store. Change useBKS to false to run on the RI")
- public void test_getPeerCertificates() {
-// try {
-// Certificate[] res = clientSession.getPeerCertificates();
-// fail("SSLPeerUnverifiedException wasn't thrown");
-// } catch (SSLPeerUnverifiedException pue) {
-// //expected
-// }
- try {
- Certificate[] res = clientSession.getPeerCertificates();
- assertTrue(res.length > 0);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLSession#getPeerCertificateChain()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "",
- method = "getPeerCertificateChain",
- args = {}
- )
- @AndroidOnly("Uses bks key store. Change useBKS to false to run on the RI")
- public void test_getPeerCertificateChain() {
-// try {
-// X509Certificate[] resN = clientSession.getPeerCertificateChain();
-// fail("SSLPeerUnverifiedException wasn't thrown");
-// } catch (SSLPeerUnverifiedException pue) {
-// //expected
-// }
- try {
- X509Certificate[] res = clientSession.getPeerCertificateChain();
- assertTrue(res.length > 0);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLSession#getProtocol()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getProtocol",
- args = {}
- )
- @AndroidOnly("Uses bks key store. Change useBKS to false to run on the RI")
- public void test_getProtocol() {
- try {
- assertEquals(clientSession.getProtocol(), "TLSv1");
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLSession#getSessionContext()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSessionContext",
- args = {}
- )
- @AndroidOnly("Uses bks key store. Change useBKS to false to run on the RI")
- public void test_getSessionContext() {
- try {
- assertEquals(clientSslContext.getClientSessionContext(),
- clientSession.getSessionContext());
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLSession#putValue(String name, Object value)
- * @tests javax.net.ssl.SSLSession#removeValue(String name)
- * @tests javax.net.ssl.SSLSession#getValueNames()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "putValue",
- args = {String.class, Object.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "removeValue",
- args = {String.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getValueNames",
- args = {}
- )
- })
- @AndroidOnly("Uses bks key store. Change useBKS to false to run on the RI")
- public void test_putValue() {
- SSLSession s = clientSession;
- mySSLSessionBindingListener sbl = new mySSLSessionBindingListener();
- try {
- assertNotNull(s.getValueNames());
- assertEquals(s.getValueNames().length, 0);
- s.putValue("Name_01", sbl);
- s.putValue("Name_02", sbl);
- s.putValue("Name_03", sbl);
- assertEquals(s.getValueNames().length, 3);
- s.removeValue("Name_01");
- assertEquals(s.getValueNames().length, 2);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
-
- try {
- s.putValue(null, null);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- }
- try {
- s.putValue("ABC", null);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- }
- try {
- s.putValue(null, sbl);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- }
-
- try {
- s.removeValue(null);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLSession#getValue(String name)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getValue",
- args = {String.class}
- )
- @AndroidOnly("Uses bks key store. Change useBKS to false to run on the RI")
- public void test_getValue() {
- SSLSession s = clientSession;
- mySSLSessionBindingListener sbl = new mySSLSessionBindingListener();
-
- try {
- s.getValue(null);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- }
-
- try {
- s.putValue("Name", sbl);
- Object obj = s.getValue("Name");
- assertTrue(obj instanceof SSLSessionBindingListener);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- Thread serverThread, clientThread;
- TestServer server;
- TestClient client;
-
- @Override
- protected void setUp() {
- port = Support_PortManager.getNextPort();
- String serverKeys = (useBKS ? SERVER_KEYS_BKS : SERVER_KEYS_JKS);
- String clientKeys = (useBKS ? CLIENT_KEYS_BKS : CLIENT_KEYS_JKS);
- server = new TestServer(true,
- TestServer.CLIENT_AUTH_WANTED, serverKeys);
- client = new TestClient(true, clientKeys);
-
- serverThread = new Thread(server);
- clientThread = new Thread(client);
-
- serverThread.start();
- try {
- Thread.currentThread().sleep(1000);
- clientThread.start();
- } catch (InterruptedException e) {
- fail("Could not create server or cient " + e.getMessage());
- }
- while (clientSession == null
- && server.exception == null
- && client.exception == null) {
- try {
- Thread.currentThread().sleep(500);
- } catch (InterruptedException e) {
- fail("couldn't create session");
- }
- }
- assertNull("server thread has a pending exception: " + server.exception,
- server.exception);
- assertNull("client thread has a pending exception: " + client.exception,
- client.exception);
- assertNotNull("Could not initialize session", clientSession);
- }
-
- @Override
- protected void tearDown() {
- notFinished = false;
- try {
- serverThread.join();
- } catch (InterruptedException e) {
- }
- try {
- clientThread.join();
- } catch (InterruptedException e) {
- }
-
- // The server must have completed without an exception.
- if (server.getException() != null) {
- throw new RuntimeException(server.getException());
- }
-
- // The client must have completed without an exception.
- if (client.getException() != null) {
- throw new RuntimeException(client.getException());
- }
- }
-
- public class mySSLSessionBindingListener implements
- SSLSessionBindingListener {
- mySSLSessionBindingListener() {
- }
- public void valueBound(SSLSessionBindingEvent event) {}
- public void valueUnbound(SSLSessionBindingEvent event) {}
- }
-
-
-
- String cipherSuiteBKS = "AES256-SHA";
- /**
- * Defines the keystore contents for the server, BKS version. Holds just a
- * single self-generated key. The subject name is "Test Server".
- */
- private static final String SERVER_KEYS_BKS =
- "AAAAAQAAABQDkebzoP1XwqyWKRCJEpn/t8dqIQAABDkEAAVteWtleQAAARpYl20nAAAAAQAFWC41" +
- "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU1jANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET" +
- "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV" +
- "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMB4XDTA4MDYwNTExNTgxNFoXDTA4MDkw" +
- "MzExNTgxNFowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U" +
- "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IFNlcnZl" +
- "cjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0LIdKaIr9/vsTq8BZlA3R+NFWRaH4lGsTAQy" +
- "DPMF9ZqEDOaL6DJuu0colSBBBQ85hQTPa9m9nyJoN3pEi1hgamqOvQIWcXBk+SOpUGRZZFXwniJV" +
- "zDKU5nE9MYgn2B9AoiH3CSuMz6HRqgVaqtppIe1jhukMc/kHVJvlKRNy9XMCAwEAATANBgkqhkiG" +
- "9w0BAQUFAAOBgQC7yBmJ9O/eWDGtSH9BH0R3dh2NdST3W9hNZ8hIa8U8klhNHbUCSSktZmZkvbPU" +
- "hse5LI3dh6RyNDuqDrbYwcqzKbFJaq/jX9kCoeb3vgbQElMRX8D2ID1vRjxwlALFISrtaN4VpWzV" +
- "yeoHPW4xldeZmoVtjn8zXNzQhLuBqX2MmAAAAqwAAAAUvkUScfw9yCSmALruURNmtBai7kQAAAZx" +
- "4Jmijxs/l8EBaleaUru6EOPioWkUAEVWCxjM/TxbGHOi2VMsQWqRr/DZ3wsDmtQgw3QTrUK666sR" +
- "MBnbqdnyCyvM1J2V1xxLXPUeRBmR2CXorYGF9Dye7NkgVdfA+9g9L/0Au6Ugn+2Cj5leoIgkgApN" +
- "vuEcZegFlNOUPVEs3SlBgUF1BY6OBM0UBHTPwGGxFBBcetcuMRbUnu65vyDG0pslT59qpaR0TMVs" +
- "P+tcheEzhyjbfM32/vwhnL9dBEgM8qMt0sqF6itNOQU/F4WGkK2Cm2v4CYEyKYw325fEhzTXosck" +
- "MhbqmcyLab8EPceWF3dweoUT76+jEZx8lV2dapR+CmczQI43tV9btsd1xiBbBHAKvymm9Ep9bPzM" +
- "J0MQi+OtURL9Lxke/70/MRueqbPeUlOaGvANTmXQD2OnW7PISwJ9lpeLfTG0LcqkoqkbtLKQLYHI" +
- "rQfV5j0j+wmvmpMxzjN3uvNajLa4zQ8l0Eok9SFaRr2RL0gN8Q2JegfOL4pUiHPsh64WWya2NB7f" +
- "V+1s65eA5ospXYsShRjo046QhGTmymwXXzdzuxu8IlnTEont6P4+J+GsWk6cldGbl20hctuUKzyx" +
- "OptjEPOKejV60iDCYGmHbCWAzQ8h5MILV82IclzNViZmzAapeeCnexhpXhWTs+xDEYSKEiG/camt" +
- "bhmZc3BcyVJrW23PktSfpBQ6D8ZxoMfF0L7V2GQMaUg+3r7ucrx82kpqotjv0xHghNIm95aBr1Qw" +
- "1gaEjsC/0wGmmBDg1dTDH+F1p9TInzr3EFuYD0YiQ7YlAHq3cPuyGoLXJ5dXYuSBfhDXJSeddUkl" +
- "k1ufZyOOcskeInQge7jzaRfmKg3U94r+spMEvb0AzDQVOKvjjo1ivxMSgFRZaDb/4qw=";
-
- /**
- * Defines the keystore contents for the client, BKS version. Holds just a
- * single self-generated key. The subject name is "Test Client".
- */
- private static final String CLIENT_KEYS_BKS =
- "AAAAAQAAABT4Rka6fxbFps98Y5k2VilmbibNkQAABfQEAAVteWtleQAAARpYl+POAAAAAQAFWC41" +
- "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU9TANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET" +
- "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV" +
- "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgQ2xpZW50MB4XDTA4MDYwNTExNTg0NVoXDTA4MDkw" +
- "MzExNTg0NVowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U" +
- "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IENsaWVu" +
- "dDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEApUvmWsQDHPpbDKK13Yez2/q54tTOmRml/qva" +
- "2K6dZjkjSTW0iRuk7ztaVEvdJpfVIDv1oBsCI51ttyLHROy1epjF+GoL74mJb7fkcd0VOoSOTjtD" +
- "+3GgZkHPAm5YmUYxiJXqxKKJJqMCTIW46eJaA2nAep9QIwZ14/NFAs4ObV8CAwEAATANBgkqhkiG" +
- "9w0BAQUFAAOBgQCJrCr3hZQFDlLIfsSKI1/w+BLvyf4fubOid0pBxfklR8KBNPTiqjSmu7pd/C/F" +
- "1FR8CdZUDoPflZHCOU+fj5r5KUC1HyigY/tEUvlforBpfB0uCF+tXW4DbUfOWhfMtLV4nCOJOOZg" +
- "awfZLJWBJouLKOp427vDftxTSB+Ks8YjlgAAAqwAAAAU+NH6TtrzjyDdCXm5B6Vo7xX5G4YAAAZx" +
- "EAUkcZtmykn7YdaYxC1jRFJ+GEJpC8nZVg83QClVuCSIS8a5f8Hl44Bk4oepOZsPzhtz3RdVzDVi" +
- "RFfoyZFsrk9F5bDTVJ6sQbb/1nfJkLhZFXokka0vND5AXMSoD5Bj1Fqem3cK7fSUyqKvFoRKC3XD" +
- "FQvhqoam29F1rbl8FaYdPvhhZo8TfZQYUyUKwW+RbR44M5iHPx+ykieMe/C/4bcM3z8cwIbYI1aO" +
- "gjQKS2MK9bs17xaDzeAh4sBKrskFGrDe+2dgvrSKdoakJhLTNTBSG6m+rzqMSCeQpafLKMSjTSSz" +
- "+KoQ9bLyax8cbvViGGju0SlVhquloZmKOfHr8TukIoV64h3uCGFOVFtQjCYDOq6NbfRvMh14UVF5" +
- "zgDIGczoD9dMoULWxBmniGSntoNgZM+QP6Id7DBasZGKfrHIAw3lHBqcvB5smemSu7F4itRoa3D8" +
- "N7hhUEKAc+xA+8NKmXfiCBoHfPHTwDvt4IR7gWjeP3Xv5vitcKQ/MAfO5RwfzkYCXQ3FfjfzmsE1" +
- "1IfLRDiBj+lhQSulhRVStKI88Che3M4JUNGKllrc0nt1pWa1vgzmUhhC4LSdm6trTHgyJnB6OcS9" +
- "t2furYjK88j1AuB4921oxMxRm8c4Crq8Pyuf+n3YKi8Pl2BzBtw++0gj0ODlgwut8SrVj66/nvIB" +
- "jN3kLVahR8nZrEFF6vTTmyXi761pzq9yOVqI57wJGx8o3Ygox1p+pWUPl1hQR7rrhUbgK/Q5wno9" +
- "uJk07h3IZnNxE+/IKgeMTP/H4+jmyT4mhsexJ2BFHeiKF1KT/FMcJdSi+ZK5yoNVcYuY8aZbx0Ef" +
- "lHorCXAmLFB0W6Cz4KPP01nD9YBB4olxiK1t7m0AU9zscdivNiuUaB5OIEr+JuZ6dNw=";
-
- String cipherSuiteJKS = "SSL_RSA_WITH_RC4_128_MD5";
- /**
- * Defines the keystore contents for the server, JKS version. Holds just a
- * single self-generated key. The subject name is "Test Server".
- */
- private static final String SERVER_KEYS_JKS =
- "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFfBeAAAArowggK2MA4GCisGAQQBKgIRAQEFAASC" +
- "AqI2kp5XjnF8YZkhcF92YsJNQkvsmH7zqMM87j23zSoV4DwyE3XeC/gZWq1ToScIhoqZkzlbWcu4" +
- "T/Zfc/DrfGk/rKbBL1uWKGZ8fMtlZk8KoAhxZk1JSyJvdkyKxqmzUbxk1OFMlN2VJNu97FPVH+du" +
- "dvjTvmpdoM81INWBW/1fZJeQeDvn4mMbbe0IxgpiLnI9WSevlaDP/sm1X3iO9yEyzHLL+M5Erspo" +
- "Cwa558fOu5DdsICMXhvDQxjWFKFhPHnKtGe+VvwkG9/bAaDgx3kfhk0w5zvdnkKb+8Ed9ylNRzdk" +
- "ocAa/mxlMTOsTvDKXjjsBupNPIIj7OP4GNnZaxkJjSs98pEO67op1GX2qhy6FSOPNuq8k/65HzUc" +
- "PYn6voEeh6vm02U/sjEnzRevQ2+2wXoAdp0EwtQ/DlMe+NvcwPGWKuMgX4A4L93DZGb04N2VmAU3" +
- "YLOtZwTO0LbuWrcCM/q99G/7LcczkxIVrO2I/rh8RXVczlf9QzcrFObFv4ATuspWJ8xG7DhsMbnk" +
- "rT94Pq6TogYeoz8o8ZMykesAqN6mt/9+ToIemmXv+e+KU1hI5oLwWMnUG6dXM6hIvrULY6o+QCPH" +
- "172YQJMa+68HAeS+itBTAF4Clm/bLn6reHCGGU6vNdwU0lYldpiOj9cB3t+u2UuLo6tiFWjLf5Zs" +
- "EQJETd4g/EK9nHxJn0GAKrWnTw7pEHQJ08elzUuy04C/jEEG+4QXU1InzS4o/kR0Sqz2WTGDoSoq" +
- "ewuPRU5bzQs/b9daq3mXrnPtRBL6HfSDAdpTK76iHqLCGdqx3avHjVSBm4zFvEuYBCev+3iKOBmg" +
- "yh7eQRTjz4UOWfy85omMBr7lK8PtfVBDzOXpasxS0uBgdUyBDX4tO6k9jZ8a1kmQRQAAAAEABVgu" +
- "NTA5AAACSDCCAkQwggGtAgRIR8SKMA0GCSqGSIb3DQEBBAUAMGkxCzAJBgNVBAYTAlVTMRMwEQYD" +
- "VQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzANBgNVBAoTBkdvb2dsZTEQMA4GA1UECxMH" +
- "QW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBTZXJ2ZXIwHhcNMDgwNjA1MTA0ODQyWhcNMDgwOTAzMTA0" +
- "ODQyWjBpMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8w" +
- "DQYDVQQKEwZHb29nbGUxEDAOBgNVBAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMIGf" +
- "MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwoC6chqCI84rj1PrXuJgbiit4EV909zR6N0jNlYfg" +
- "itwB39bP39wH03rFm8T59b3mbSptnGmCIpLZn25KPPFsYD3JJ+wFlmiUdEP9H05flfwtFQJnw9uT" +
- "3rRIdYVMPcQ3RoZzwAMliGr882I2thIDbA6xjGU/1nRIdvk0LtxH3QIDAQABMA0GCSqGSIb3DQEB" +
- "BAUAA4GBAJn+6YgUlY18Ie+0+Vt8oEi81DNi/bfPrAUAh63fhhBikx/3R9dl3wh09Z6p7cIdNxjW" +
- "n2ll+cRW9eqF7z75F0Omm0C7/KAEPjukVbszmzeU5VqzkpSt0j84YWi+TfcHRrfvhLbrlmGITVpY" +
- "ol5pHLDyqGmDs53pgwipWqsn/nEXEBgj3EoqPeqHbDf7YaP8h/5BSt0=";
-
- /**
- * Defines the keystore contents for the client, JKS version. Holds just a
- * single self-generated key. The subject name is "Test Client".
- */
- private static final String CLIENT_KEYS_JKS =
- "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFhyMAAAArkwggK1MA4GCisGAQQBKgIRAQEFAASC" +
- "AqGVSfXolBStZy4nnRNn4fAr+S7kfU2BS23wwW8uB2Ru3GvtLzlK9q08Gvq/LNqBafjyFTVL5FV5" +
- "SED/8YomO5a98GpskSeRvytCiTBLJdgGhws5TOGekgIAcBROPGIyOtJPQ0HfOQs+BqgzGDHzHQhw" +
- "u/8Tm6yQwiP+W/1I9B1QnaEztZA3mhTyMMJsmsFTYroGgAog885D5Cmzd8sYGfxec3R6I+xcmBAY" +
- "eibR5kGpWwt1R+qMvRrtBqh5r6WSKhCBNax+SJVbtUNRiKyjKccdJg6fGqIWWeivwYTy0OhjA6b4" +
- "NiZ/ZZs5pxFGWUj/Rlp0RYy8fCF6aw5/5s4Bf4MI6dPSqMG8Hf7sJR91GbcELyzPdM0h5lNavgit" +
- "QPEzKeuDrGxhY1frJThBsNsS0gxeu+OgfJPEb/H4lpYX5IvuIGbWKcxoO9zq4/fimIZkdA8A+3eY" +
- "mfDaowvy65NBVQPJSxaOyFhLHfeLqOeCsVENAea02vA7andZHTZehvcrqyKtm+z8ncHGRC2H9H8O" +
- "jKwKHfxxrYY/jMAKLl00+PBb3kspO+BHI2EcQnQuMw/zr83OR9Meq4TJ0TMuNkApZELAeFckIBbS" +
- "rBr8NNjAIfjuCTuKHhsTFWiHfk9ZIzigxXagfeDRiyVc6khOuF/bGorj23N2o7Rf3uLoU6PyXWi4" +
- "uhctR1aL6NzxDoK2PbYCeA9hxbDv8emaVPIzlVwpPK3Ruvv9mkjcOhZ74J8bPK2fQmbplbOljcZi" +
- "tZijOfzcO/11JrwhuJZRA6wanTqHoujgChV9EukVrmbWGGAcewFnAsSbFXIik7/+QznXaDIt5NgL" +
- "H/Bcz4Z/fdV7Ae1eUaxKXdPbI//4J+8liVT/d8awjW2tldIaDlmGMR3aoc830+3mAAAAAQAFWC41" +
- "MDkAAAJIMIICRDCCAa0CBEhHxLgwDQYJKoZIhvcNAQEEBQAwaTELMAkGA1UEBhMCVVMxEzARBgNV" +
- "BAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01UVjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdB" +
- "bmRyb2lkMRQwEgYDVQQDEwtUZXN0IENsaWVudDAeFw0wODA2MDUxMDQ5MjhaFw0wODA5MDMxMDQ5" +
- "MjhaMGkxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzAN" +
- "BgNVBAoTBkdvb2dsZTEQMA4GA1UECxMHQW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBDbGllbnQwgZ8w" +
- "DQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAIK3Q+KiFbmCGg422TAo4gggdhMH6FJhiuz8DxRyeMKR" +
- "UAfP4MK0wtc8N42waZ6OKvxpBFUy0BRfBsX0GD4Ku99yu9/tavSigTraeJtwV3WWRRjIqk7L3wX5" +
- "cmgS2KSD43Y0rNUKrko26lnt9N4qiYRBSj+tcAN3Lx9+ptqk1LApAgMBAAEwDQYJKoZIhvcNAQEE" +
- "BQADgYEANb7Q1GVSuy1RPJ0FmiXoMYCCtvlRLkmJphwxovK0cAQK12Vll+yAzBhHiQHy/RA11mng" +
- "wYudC7u3P8X/tBT8GR1Yk7QW3KgFyPafp3lQBBCraSsfrjKj+dCLig1uBLUr4f68W8VFWZWWTHqp" +
- "NMGpCX6qmjbkJQLVK/Yfo1ePaUexPSOX0G9m8+DoV3iyNw6at01NRw==";
-
-
- int port;
- SSLSocket serverSocket;
- MyHandshakeListener listener;
- String host = "localhost";
- boolean notFinished = true;
- SSLSession clientSession = null;
- SSLContext clientSslContext = null;
- String testData = "PING";
-
- private String PASSWORD = "android";
-
- String cipherSuite = (useBKS ? cipherSuiteBKS : cipherSuiteJKS);
-
- /**
- * Implements a test SSL socket server. It waits for a connection on a given
- * port, requests client authentication (if specified), reads from the socket,
- * and writes to the socket.
- */
- class TestServer implements Runnable {
-
- public static final int CLIENT_AUTH_NONE = 0;
-
- public static final int CLIENT_AUTH_WANTED = 1;
-
- public static final int CLIENT_AUTH_NEEDED = 2;
-
- private TestTrustManager trustManager;
-
- private Exception exception;
-
- String keys;
-
- private int clientAuth;
-
- private boolean provideKeys;
-
- private KeyStore store;
-
- public TestServer(boolean provideKeys, int clientAuth, String keys) {
- this.keys = keys;
- this.clientAuth = clientAuth;
- this.provideKeys = provideKeys;
-
- trustManager = new TestTrustManager();
- }
-
- public void run() {
- try {
- store = provideKeys ? getKeyStore(keys) : null;
- KeyManager[] keyManagers = store != null ? getKeyManagers(store) : null;
- TrustManager[] trustManagers = new TrustManager[] { trustManager };
-
- SSLContext sslContext = SSLContext.getInstance("TLS");
- sslContext.init(keyManagers, trustManagers, null);
-
- SSLServerSocket serverSocket = (SSLServerSocket)sslContext
- .getServerSocketFactory().createServerSocket();
-
- if (clientAuth == CLIENT_AUTH_WANTED) {
- serverSocket.setWantClientAuth(true);
- } else if (clientAuth == CLIENT_AUTH_NEEDED) {
- serverSocket.setNeedClientAuth(true);
- } else {
- serverSocket.setWantClientAuth(false);
- }
-
- serverSocket.bind(new InetSocketAddress(port));
-
- SSLSocket clientSocket = (SSLSocket)serverSocket.accept();
-
- InputStream istream = clientSocket.getInputStream();
- byte[] buffer = new byte[1024];
- istream.read(buffer);
-
- OutputStream ostream = clientSocket.getOutputStream();
- ostream.write(testData.getBytes());
- ostream.flush();
-
- while (notFinished) {
- Thread.currentThread().sleep(500);
- }
-
- clientSocket.close();
- serverSocket.close();
-
- } catch (Exception ex) {
- exception = ex;
- }
- }
-
- public Exception getException() {
- return exception;
- }
-
- public X509Certificate[] getChain() {
- return trustManager.getChain();
- }
-
- public KeyStore getStore() {
- return store;
- }
-
- }
-
- /**
- * Implements a test SSL socket client. It opens a connection to localhost on
- * a given port, writes to the socket, and reads from the socket.
- */
- class TestClient implements Runnable {
-
- private TestTrustManager trustManager;
-
- private Exception exception;
-
- private String keys;
-
- private boolean provideKeys;
-
- private KeyStore store;
-
- public TestClient(boolean provideKeys, String keys) {
- this.keys = keys;
- this.provideKeys = provideKeys;
-
- trustManager = new TestTrustManager();
- }
-
- public void run() {
- try {
- store = provideKeys ? getKeyStore(keys) : null;
- KeyManager[] keyManagers = store != null ? getKeyManagers(store) : null;
- TrustManager[] trustManagers = new TrustManager[] { trustManager };
-
- clientSslContext = SSLContext.getInstance("TLS");
- clientSslContext.init(keyManagers, trustManagers, null);
-
- SSLSocket socket = (SSLSocket)clientSslContext.getSocketFactory().createSocket();
-
- socket.connect(new InetSocketAddress(port));
- OutputStream ostream = socket.getOutputStream();
- ostream.write(testData.getBytes());
- ostream.flush();
-
- InputStream istream = socket.getInputStream();
- byte[] buffer = new byte[1024];
- istream.read(buffer);
-
- clientSession = socket.getSession();
- while (notFinished) {
- Thread.currentThread().sleep(500);
- }
- socket.close();
-
- } catch (Exception ex) {
- exception = ex;
- }
- }
-
- public Exception getException() {
- return exception;
- }
-
- public X509Certificate[] getChain() {
- return trustManager.getChain();
- }
-
- public KeyStore getStore() {
- return store;
- }
- }
-
- /**
- * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
- * for the result.
- */
- private KeyStore getKeyStore(String keys) throws Exception {
- byte[] bytes = new Base64().decode(keys.getBytes());
- InputStream inputStream = new ByteArrayInputStream(bytes);
-
- KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
- keyStore.load(inputStream, PASSWORD.toCharArray());
- inputStream.close();
- return keyStore;
- }
-
- /**
- * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
- * for the result.
- */
- private KeyManager[] getKeyManagers(KeyStore keyStore) throws Exception {
- String algorithm = KeyManagerFactory.getDefaultAlgorithm();
- KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
- keyManagerFactory.init(keyStore, PASSWORD.toCharArray());
-
- return keyManagerFactory.getKeyManagers();
- }
-}
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/SSLSocketFactoryTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/SSLSocketFactoryTest.java
deleted file mode 100644
index 05308de..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/SSLSocketFactoryTest.java
+++ /dev/null
@@ -1,178 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.BrokenTest;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.IOException;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.net.UnknownHostException;
-
-import javax.net.SocketFactory;
-import javax.net.ssl.SSLSocketFactory;
-
-import junit.framework.TestCase;
-
-import tests.support.Support_PortManager;
-
-@TestTargetClass(SSLSocketFactory.class)
-public class SSLSocketFactoryTest extends TestCase {
-
- private ServerSocket ss;
-
- protected int startServer(String name) {
- int portNumber = Support_PortManager.getNextPort();
- try {
- ss = new ServerSocket(portNumber);
- } catch (IOException e) {
- fail(name + ": " + e);
- }
- return ss.getLocalPort();
- }
-
- /**
- * @tests javax.net.ssl.SSLSocketFactory#SSLSocketFactory()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SSLSocketFactory",
- args = {}
- )
- public void test_Constructor() {
- try {
- SocketFactory sf = SSLSocketFactory.getDefault();
- assertTrue(sf instanceof SSLSocketFactory);
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLSocketFactory#getDefault()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDefault",
- args = {}
- )
- public void test_getDefault() {
- assertNotNull("Incorrect default socket factory",
- SSLSocketFactory.getDefault());
- }
-
- /**
- * @tests javax.net.ssl.SSLSocketFactory#createSocket(Socket s, String host, int port, boolean autoClose)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "createSocket",
- args = {java.net.Socket.class, java.lang.String.class, int.class, boolean.class}
- )
- public void test_createSocket() {
- SSLSocketFactory sf = (SSLSocketFactory)SSLSocketFactory.getDefault();
- int sport = startServer("test_createSocket()");
- int[] invalid = {
- Integer.MIN_VALUE, -1, 65536, Integer.MAX_VALUE
- };
- try {
- Socket st = new Socket("localhost", sport);
- Socket s = sf.createSocket(st, "localhost", sport, false);
- assertFalse(s.isClosed());
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- try {
- Socket st = new Socket("localhost", sport);
- Socket s = sf.createSocket(st, "localhost", sport, true);
- s.close();
- assertTrue(st.isClosed());
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- try {
- sf.createSocket(null, "localhost", sport, true);
- fail("IOException wasn't thrown");
- } catch (IOException ioe) {
- // expected
- } catch (NullPointerException e) {
- // expected
- }
- for (int i = 0; i < invalid.length; i++) {
- try {
- Socket s = sf.createSocket(new Socket(), "localhost", 1080, false);
- fail("IOException wasn't thrown");
- } catch (IOException ioe) {
- // expected
- }
- }
-
- try {
- Socket st = new Socket("bla-bla", sport);
- Socket s = sf.createSocket(st, "bla-bla", sport, false);
- fail("UnknownHostException wasn't thrown: " + "bla-bla");
- } catch (UnknownHostException uhe) {
- // expected
- } catch (Exception e) {
- fail(e + " was thrown instead of UnknownHostException");
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLSocketFactory#getDefaultCipherSuites()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDefaultCipherSuites",
- args = {}
- )
- public void test_getDefaultCipherSuites() {
- try {
- SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- assertTrue("no default cipher suites returned",
- sf.getDefaultCipherSuites().length > 0);
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLSocketFactory#getSupportedCipherSuites()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSupportedCipherSuites",
- args = {}
- )
- public void test_getSupportedCipherSuites() {
- try {
- SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
- assertTrue("no supported cipher suites returned",
- sf.getSupportedCipherSuites().length > 0);
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
-}
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/SSLSocketTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/SSLSocketTest.java
deleted file mode 100644
index a17df93..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/SSLSocketTest.java
+++ /dev/null
@@ -1,916 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import javax.net.ssl.*;
-import javax.security.cert.X509Certificate;
-
-import java.net.*;
-import java.security.KeyStore;
-import java.security.SecureRandom;
-import java.util.Arrays;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.luni.util.Base64;
-
-import tests.api.javax.net.ssl.HandshakeCompletedEventTest.TestTrustManager;
-import tests.support.Support_PortManager;
-
-@TestTargetClass(SSLSocket.class)
-public class SSLSocketTest extends TestCase {
-
- public class HandshakeCL implements HandshakeCompletedListener {
- HandshakeCL() {
- super();
- }
- public void handshakeCompleted(HandshakeCompletedEvent event) {
- }
- }
-
- /**
- * @tests javax.net.ssl.SSLSocket#SSLSocket()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SSLSocket",
- args = {}
- )
- public void testConstructor_01() {
- try {
- SSLSocket ssl = getSSLSocket();
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
- }
-
- /**
- * @throws IOException
- * @throws UnknownHostException
- * @tests javax.net.ssl.SSLSocket#SSLSocket(InetAddress address, int port)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SSLSocket",
- args = {java.net.InetAddress.class, int.class}
- )
- public void testConstructor_02() throws UnknownHostException, IOException {
- SSLSocket ssl;
- int sport = startServer("Cons InetAddress,I");
- int[] invalidPort = {-1, Integer.MIN_VALUE, 65536, Integer.MAX_VALUE};
-
- ssl = getSSLSocket(InetAddress.getLocalHost(), sport);
- assertNotNull(ssl);
- assertEquals(sport, ssl.getPort());
-
- try {
- ssl = getSSLSocket(InetAddress.getLocalHost(), sport + 1);
- fail("IOException wasn't thrown ...");
- } catch (IOException e) {
- //expected
- }
-
- for (int i = 0; i < invalidPort.length; i++) {
- try {
- ssl = getSSLSocket(InetAddress.getLocalHost(), invalidPort[i]);
- fail("IllegalArgumentException wasn't thrown for " + invalidPort[i]);
- } catch (IllegalArgumentException iae) {
- // expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException for " + invalidPort[i]);
- }
- }
- }
-
- /**
- * @throws IOException
- * @throws UnknownHostException
- * @tests javax.net.ssl.SSLSocket#SSLSocket(InetAddress address, int port,
- * InetAddress clientAddress, int clientPort)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SSLSocket",
- args = {java.net.InetAddress.class, int.class, java.net.InetAddress.class, int.class}
- )
- public void testConstructor_03() throws UnknownHostException, IOException {
- SSLSocket ssl;
- int sport = startServer("Cons InetAddress,I,InetAddress,I");
- int portNumber = Support_PortManager.getNextPort();
-
- ssl = getSSLSocket(InetAddress.getLocalHost(), sport,
- InetAddress.getLocalHost(), portNumber);
- assertNotNull(ssl);
- assertEquals(sport, ssl.getPort());
- assertEquals(portNumber, ssl.getLocalPort());
-
- try {
- ssl = getSSLSocket(InetAddress.getLocalHost(), 8081, InetAddress.getLocalHost(), 8082);
- fail("IOException wasn't thrown ...");
- } catch (IOException e) {
- //expected
- }
-
- try {
- ssl = getSSLSocket(InetAddress.getLocalHost(), -1,
- InetAddress.getLocalHost(), sport + 1);
- fail("IllegalArgumentException wasn't thrown for -1");
- } catch (IllegalArgumentException iae) {
- // expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException for -1");
- }
- try {
- ssl = getSSLSocket(InetAddress.getLocalHost(), sport,
- InetAddress.getLocalHost(), -1);
- fail("IllegalArgumentException wasn't thrown for -1");
- } catch (IllegalArgumentException iae) {
- // expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException for -1");
- }
-
- try {
- ssl = getSSLSocket(InetAddress.getLocalHost(), Integer.MIN_VALUE,
- InetAddress.getLocalHost(), sport + 1);
- fail("IOException wasn't thrown for " + Integer.MIN_VALUE);
- } catch (IOException ioe) {
- // expected on RI
- } catch (IllegalArgumentException iae) {
- // expected on Android
- } catch (Exception e) {
- fail(e + " was thrown instead of IOException for "
- + Integer.MIN_VALUE);
- }
- try {
- ssl = getSSLSocket(InetAddress.getLocalHost(), sport,
- InetAddress.getLocalHost(), Integer.MIN_VALUE);
- fail("IllegalArgumentException wasn't thrown for "
- + Integer.MIN_VALUE);
- } catch (IllegalArgumentException iae) {
- // expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException for "
- + Integer.MIN_VALUE);
- }
-
- try {
- ssl = getSSLSocket(InetAddress.getLocalHost(), 65536,
- InetAddress.getLocalHost(), sport + 1);
- fail("IOException wasn't thrown for 65536");
- } catch (IOException ioe) {
- // expected on RI
- } catch (IllegalArgumentException iae) {
- // expected on Android
- } catch (Exception e) {
- fail(e + " was thrown instead of IOException for 65536");
- }
- try {
- ssl = getSSLSocket(InetAddress.getLocalHost(), sport,
- InetAddress.getLocalHost(), 65536);
- fail("IllegalArgumentException wasn't thrown for 65536");
- } catch (IllegalArgumentException iae) {
- // expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException for 65536");
- }
-
- try {
- ssl = getSSLSocket(InetAddress.getLocalHost(), Integer.MAX_VALUE,
- InetAddress.getLocalHost(), sport + 1);
- fail("IOException wasn't thrown for " + Integer.MAX_VALUE);
- } catch (IOException ioe) {
- // expected on RI
- } catch (IllegalArgumentException iae) {
- // expected on Android
- } catch (Exception e) {
- fail(e + " was thrown instead of IOException for "
- + Integer.MAX_VALUE);
- }
- try {
- ssl = getSSLSocket(InetAddress.getLocalHost(), sport,
- InetAddress.getLocalHost(), Integer.MAX_VALUE);
- fail("IllegalArgumentException wasn't thrown for "
- + Integer.MAX_VALUE);
- } catch (IllegalArgumentException iae) {
- // expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException for "
- + Integer.MAX_VALUE);
- }
- }
-
- /**
- * @throws IOException
- * @throws UnknownHostException
- * @tests javax.net.ssl.SSLSocket#SSLSocket(String host, int port)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SSLSocket",
- args = {java.lang.String.class, int.class}
- )
- public void testConstructor_04() throws UnknownHostException, IOException {
- SSLSocket ssl;
- int sport = startServer("Cons String,I");
- int[] invalidPort = {-1, Integer.MIN_VALUE, 65536, Integer.MAX_VALUE};
-
- ssl = getSSLSocket(InetAddress.getLocalHost().getHostName(), sport);
- assertNotNull(ssl);
- assertEquals(sport, ssl.getPort());
-
- try {
- ssl = getSSLSocket("localhost", 8082);
- fail("IOException wasn't thrown ...");
- } catch (IOException e) {
- //expected
- }
-
- for (int i = 0; i < invalidPort.length; i++) {
- try {
- ssl = getSSLSocket(InetAddress.getLocalHost().getHostName(), invalidPort[i]);
- fail("IllegalArgumentException wasn't thrown for " + invalidPort[i]);
- } catch (IllegalArgumentException iae) {
- // expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException for " + invalidPort[i]);
- }
- }
-
- try {
- ssl = getSSLSocket("bla-bla", sport);
- fail("UnknownHostException wasn't thrown");
- } catch (UnknownHostException uhp) {
- // expected
- } catch (Exception e) {
- fail(e + " was thrown instead of UnknownHostException");
- }
- }
-
- /**
- * @throws IOException
- * @throws UnknownHostException
- * @tests javax.net.ssl.SSLSocket#SSLSocket(String host, int port, InetAddress clientAddress,
- * int clientPort)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SSLSocket",
- args = {java.lang.String.class, int.class, java.net.InetAddress.class, int.class}
- )
- public void testConstructor_05() throws UnknownHostException, IOException {
- SSLSocket ssl;
- int sport = startServer("Cons String,I,InetAddress,I");
- int portNumber = Support_PortManager.getNextPort();
- int[] invalidPort = {-1, Integer.MIN_VALUE, 65536, Integer.MAX_VALUE};
-
- ssl = getSSLSocket(InetAddress.getLocalHost().getHostName(), sport,
- InetAddress.getLocalHost(), portNumber);
- assertNotNull(ssl);
- assertEquals(sport, ssl.getPort());
- assertEquals(portNumber, ssl.getLocalPort());
-
- try {
- ssl = getSSLSocket("localhost", 8081, InetAddress.getLocalHost(), 8082);
- fail("IOException wasn't thrown ...");
- } catch (IOException e) {
- //expected
- }
-
- for (int i = 0; i < invalidPort.length; i++) {
- portNumber = Support_PortManager.getNextPort();
- try {
- ssl = getSSLSocket(InetAddress.getLocalHost().getHostName(), invalidPort[i],
- InetAddress.getLocalHost(), portNumber);
- fail("IllegalArgumentException wasn't thrown for " + invalidPort[i]);
- } catch (IllegalArgumentException iae) {
- // expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException for " + invalidPort[i]);
- }
- try {
- ssl = getSSLSocket(InetAddress.getLocalHost().getHostName(), sport,
- InetAddress.getLocalHost(), invalidPort[i]);
- fail("IllegalArgumentException wasn't thrown for " + invalidPort[i]);
- } catch (IllegalArgumentException iae) {
- // expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException for " + invalidPort[i]);
- }
- }
-
- portNumber = Support_PortManager.getNextPort();
- try {
- ssl = getSSLSocket("bla-bla", sport, InetAddress.getLocalHost(), portNumber);
- fail("UnknownHostException wasn't thrown");
- } catch (UnknownHostException uhp) {
- // expected
- } catch (Exception e) {
- fail(e + " was thrown instead of UnknownHostException");
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Guard against native resource leakage.",
- method = "SSLSocket",
- args = {}
- )
- public void test_creationStressTest() throws Exception {
- // Test the default codepath, which uses /dev/urandom.
- SSLContext sslContext = SSLContext.getInstance("TLS");
- sslContext.init(null, null, null);
- for (int i = 0; i < 2048; ++i) {
- sslContext.getSocketFactory().createSocket();
- }
-
- // Test the other codepath, which copies a seed from a byte[].
- sslContext.init(null, null, new SecureRandom());
- for (int i = 0; i < 2048; ++i) {
- sslContext.getSocketFactory().createSocket();
- }
- }
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.SSLSocket#addHandshakeCompletedListener(HandshakeCompletedListener listener)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "addHandshakeCompletedListener",
- args = {javax.net.ssl.HandshakeCompletedListener.class}
- )
- @AndroidOnly("RI doesn't throw the specified IAE")
- public void test_addHandshakeCompletedListener() throws IOException {
- SSLSocket ssl = getSSLSocket();
- HandshakeCompletedListener ls = new HandshakeCL();
- try {
- ssl.addHandshakeCompletedListener(null);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- }
- try {
- ssl.addHandshakeCompletedListener(ls);
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
- }
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.SSLSocket#removeHandshakeCompletedListener(HandshakeCompletedListener listener)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "removeHandshakeCompletedListener",
- args = {javax.net.ssl.HandshakeCompletedListener.class}
- )
- public void test_removeHandshakeCompletedListener() throws IOException {
- SSLSocket ssl = getSSLSocket();
- HandshakeCompletedListener ls = new HandshakeCL();
- try {
- ssl.removeHandshakeCompletedListener(null);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- }
-
- try {
- ssl.removeHandshakeCompletedListener(ls);
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
-
- ssl.addHandshakeCompletedListener(ls);
- try {
- ssl.removeHandshakeCompletedListener(ls);
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
- }
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.SSLSocket#setEnableSessionCreation(boolean flag)
- * @tests javax.net.ssl.SSLSocket#getEnableSessionCreation()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getEnableSessionCreation",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setEnableSessionCreation",
- args = {boolean.class}
- )
- })
- public void test_EnableSessionCreation() throws IOException {
- SSLSocket ssl = getSSLSocket();
- assertTrue(ssl.getEnableSessionCreation());
- ssl.setEnableSessionCreation(false);
- assertFalse(ssl.getEnableSessionCreation());
- ssl.setEnableSessionCreation(true);
- assertTrue(ssl.getEnableSessionCreation());
- }
-
- /**
- * @throws IOException
- * @throws UnknownHostException
- * @tests javax.net.ssl.SSLSocket#setNeedClientAuth(boolean need)
- * @tests javax.net.ssl.SSLSocket#getNeedClientAuthCreation()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setNeedClientAuth",
- args = {boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getNeedClientAuth",
- args = {}
- )
- })
- public void test_NeedClientAuth() throws UnknownHostException, IOException {
- SSLSocket ssl = getSSLSocket();
- ssl.setNeedClientAuth(true);
- assertTrue(ssl.getNeedClientAuth());
- ssl.setNeedClientAuth(false);
- assertFalse(ssl.getNeedClientAuth());
- }
-
- /**
- * @throws IOException
- * @throws UnknownHostException
- * @tests javax.net.ssl.SSLSocket#setWantClientAuth(boolean want)
- * @tests javax.net.ssl.SSLSocket#getWantClientAuthCreation()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setWantClientAuth",
- args = {boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getWantClientAuth",
- args = {}
- )
- })
- public void test_WantClientAuth() throws UnknownHostException, IOException {
- SSLSocket ssl = getSSLSocket();
- ssl.setWantClientAuth(true);
- assertTrue(ssl.getWantClientAuth());
- ssl.setWantClientAuth(false);
- assertFalse(ssl.getWantClientAuth());
- }
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.SSLSocket#getSupportedProtocols()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSupportedProtocols",
- args = {}
- )
- public void test_getSupportedProtocols() throws IOException {
- SSLSocket ssl = getSSLSocket();
- String[] res = ssl.getSupportedProtocols();
- assertTrue("No supported protocols found", res.length > 0);
- }
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.SSLSocket#getEnabledProtocols()
- * @tests javax.net.ssl.SSLSocket#setEnabledProtocols(String[] protocols)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setEnabledProtocols",
- args = {java.lang.String[].class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getEnabledProtocols",
- args = {}
- )
- })
- public void test_EnabledProtocols() throws IOException {
- SSLSocket ssl = getSSLSocket();
- try {
- ssl.setEnabledProtocols(null);
- } catch (IllegalArgumentException iae) {
- //expected
- }
- try {
- ssl.setEnabledProtocols(new String[] {});
- } catch (IllegalArgumentException iae) {
- //expected
- }
- try {
- ssl.setEnabledProtocols(new String[] {"blubb"});
- } catch (IllegalArgumentException iae) {
- //expected
- }
- ssl.setEnabledProtocols(ssl.getEnabledProtocols());
- String[] res = ssl.getEnabledProtocols();
- assertEquals("no enabled protocols set",
- ssl.getEnabledProtocols().length, res.length);
- }
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.SSLSocket#getSession()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSession",
- args = {}
- )
- public void test_getSession() throws IOException {
- SSLSocket ssl = getSSLSocket();
- try {
- assertNotNull(ssl.getSession());
- } catch (Exception e) {
- fail("Unexpected exception " + e);
- }
- }
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.SSLSocket#getSupportedCipherSuites()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSupportedCipherSuites",
- args = {}
- )
- public void test_getSupportedCipherSuites() throws IOException {
- SSLSocket ssl = getSSLSocket();
- String[] res = ssl.getSupportedCipherSuites();
- assertTrue("no supported cipher suites", res.length > 0);
- }
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.SSLSocket#getEnabledCipherSuites()
- * @tests javax.net.ssl.SSLSocket#setEnabledCipherSuites(String[] suites)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getEnabledCipherSuites",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setEnabledCipherSuites",
- args = {java.lang.String[].class}
- )
- })
- public void test_EnabledCipherSuites() throws IOException {
- SSLSocket ssl = getSSLSocket();
- try {
- ssl.setEnabledCipherSuites(null);
- } catch (IllegalArgumentException iae) {
- //expected
- }
- try {
- ssl.setEnabledCipherSuites(new String[] {});
- } catch (IllegalArgumentException iae) {
- //expected
- }
- try {
- ssl.setEnabledCipherSuites(new String[] {"blubb"});
- } catch (IllegalArgumentException iae) {
- //expected
- }
- ssl.setEnabledCipherSuites(ssl.getSupportedCipherSuites());
- String[] res = ssl.getEnabledCipherSuites();
- assertNotNull("NULL result", res);
- assertEquals("not all supported cipher suites were enabled",
- Arrays.asList(ssl.getSupportedCipherSuites()),
- Arrays.asList(res));
- }
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.SSLSocket#getUseClientMode()
- * @tests javax.net.ssl.SSLSocket#setUseClientMode(boolean mode)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getUseClientMode",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setUseClientMode",
- args = {boolean.class}
- )
- })
- public void test_UseClientMode() throws IOException {
- SSLSocket ssl = getSSLSocket();
- assertTrue(ssl.getUseClientMode());
- ssl.setUseClientMode(false);
- assertFalse(ssl.getUseClientMode());
-
- ssl = getSSLSocket("localhost", startServer("UseClientMode"));
- try {
- ssl.startHandshake();
- } catch (IOException ioe) {
- //fail(ioe + " was thrown for method startHandshake()");
- }
- try {
- ssl.setUseClientMode(false);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
- }
-
- /**
- * @throws IOException
- * @tests javax.net.ssl.SSLSocket#startHandshake()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "startHandshake",
- args = {}
- )
- public void test_startHandshake() throws IOException {
- SSLSocket ssl = getSSLSocket();
- try {
- ssl.startHandshake();
- fail("IOException wasn't thrown");
- } catch (IOException ioe) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IOException");
- }
- }
-
- // Change this to false if on RI
- boolean useBKS = true;
-
- private String PASSWORD = "android";
-
- private int port = Support_PortManager.getNextPort();
-
- private boolean serverReady = false;
-
- /**
- * Defines the keystore contents for the server, BKS version. Holds just a
- * single self-generated key. The subject name is "Test Server".
- */
- private static final String SERVER_KEYS_BKS =
- "AAAAAQAAABQDkebzoP1XwqyWKRCJEpn/t8dqIQAABDkEAAVteWtleQAAARpYl20nAAAAAQAFWC41" +
- "MDkAAAJNMIICSTCCAbKgAwIBAgIESEfU1jANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQGEwJVUzET" +
- "MBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8wDQYDVQQKEwZHb29nbGUxEDAOBgNV" +
- "BAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMB4XDTA4MDYwNTExNTgxNFoXDTA4MDkw" +
- "MzExNTgxNFowaTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExDDAKBgNVBAcTA01U" +
- "VjEPMA0GA1UEChMGR29vZ2xlMRAwDgYDVQQLEwdBbmRyb2lkMRQwEgYDVQQDEwtUZXN0IFNlcnZl" +
- "cjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0LIdKaIr9/vsTq8BZlA3R+NFWRaH4lGsTAQy" +
- "DPMF9ZqEDOaL6DJuu0colSBBBQ85hQTPa9m9nyJoN3pEi1hgamqOvQIWcXBk+SOpUGRZZFXwniJV" +
- "zDKU5nE9MYgn2B9AoiH3CSuMz6HRqgVaqtppIe1jhukMc/kHVJvlKRNy9XMCAwEAATANBgkqhkiG" +
- "9w0BAQUFAAOBgQC7yBmJ9O/eWDGtSH9BH0R3dh2NdST3W9hNZ8hIa8U8klhNHbUCSSktZmZkvbPU" +
- "hse5LI3dh6RyNDuqDrbYwcqzKbFJaq/jX9kCoeb3vgbQElMRX8D2ID1vRjxwlALFISrtaN4VpWzV" +
- "yeoHPW4xldeZmoVtjn8zXNzQhLuBqX2MmAAAAqwAAAAUvkUScfw9yCSmALruURNmtBai7kQAAAZx" +
- "4Jmijxs/l8EBaleaUru6EOPioWkUAEVWCxjM/TxbGHOi2VMsQWqRr/DZ3wsDmtQgw3QTrUK666sR" +
- "MBnbqdnyCyvM1J2V1xxLXPUeRBmR2CXorYGF9Dye7NkgVdfA+9g9L/0Au6Ugn+2Cj5leoIgkgApN" +
- "vuEcZegFlNOUPVEs3SlBgUF1BY6OBM0UBHTPwGGxFBBcetcuMRbUnu65vyDG0pslT59qpaR0TMVs" +
- "P+tcheEzhyjbfM32/vwhnL9dBEgM8qMt0sqF6itNOQU/F4WGkK2Cm2v4CYEyKYw325fEhzTXosck" +
- "MhbqmcyLab8EPceWF3dweoUT76+jEZx8lV2dapR+CmczQI43tV9btsd1xiBbBHAKvymm9Ep9bPzM" +
- "J0MQi+OtURL9Lxke/70/MRueqbPeUlOaGvANTmXQD2OnW7PISwJ9lpeLfTG0LcqkoqkbtLKQLYHI" +
- "rQfV5j0j+wmvmpMxzjN3uvNajLa4zQ8l0Eok9SFaRr2RL0gN8Q2JegfOL4pUiHPsh64WWya2NB7f" +
- "V+1s65eA5ospXYsShRjo046QhGTmymwXXzdzuxu8IlnTEont6P4+J+GsWk6cldGbl20hctuUKzyx" +
- "OptjEPOKejV60iDCYGmHbCWAzQ8h5MILV82IclzNViZmzAapeeCnexhpXhWTs+xDEYSKEiG/camt" +
- "bhmZc3BcyVJrW23PktSfpBQ6D8ZxoMfF0L7V2GQMaUg+3r7ucrx82kpqotjv0xHghNIm95aBr1Qw" +
- "1gaEjsC/0wGmmBDg1dTDH+F1p9TInzr3EFuYD0YiQ7YlAHq3cPuyGoLXJ5dXYuSBfhDXJSeddUkl" +
- "k1ufZyOOcskeInQge7jzaRfmKg3U94r+spMEvb0AzDQVOKvjjo1ivxMSgFRZaDb/4qw=";
-
- /**
- * Defines the keystore contents for the server, JKS version. Holds just a
- * single self-generated key. The subject name is "Test Server".
- */
- private static final String SERVER_KEYS_JKS =
- "/u3+7QAAAAIAAAABAAAAAQAFbXlrZXkAAAEaWFfBeAAAArowggK2MA4GCisGAQQBKgIRAQEFAASC" +
- "AqI2kp5XjnF8YZkhcF92YsJNQkvsmH7zqMM87j23zSoV4DwyE3XeC/gZWq1ToScIhoqZkzlbWcu4" +
- "T/Zfc/DrfGk/rKbBL1uWKGZ8fMtlZk8KoAhxZk1JSyJvdkyKxqmzUbxk1OFMlN2VJNu97FPVH+du" +
- "dvjTvmpdoM81INWBW/1fZJeQeDvn4mMbbe0IxgpiLnI9WSevlaDP/sm1X3iO9yEyzHLL+M5Erspo" +
- "Cwa558fOu5DdsICMXhvDQxjWFKFhPHnKtGe+VvwkG9/bAaDgx3kfhk0w5zvdnkKb+8Ed9ylNRzdk" +
- "ocAa/mxlMTOsTvDKXjjsBupNPIIj7OP4GNnZaxkJjSs98pEO67op1GX2qhy6FSOPNuq8k/65HzUc" +
- "PYn6voEeh6vm02U/sjEnzRevQ2+2wXoAdp0EwtQ/DlMe+NvcwPGWKuMgX4A4L93DZGb04N2VmAU3" +
- "YLOtZwTO0LbuWrcCM/q99G/7LcczkxIVrO2I/rh8RXVczlf9QzcrFObFv4ATuspWJ8xG7DhsMbnk" +
- "rT94Pq6TogYeoz8o8ZMykesAqN6mt/9+ToIemmXv+e+KU1hI5oLwWMnUG6dXM6hIvrULY6o+QCPH" +
- "172YQJMa+68HAeS+itBTAF4Clm/bLn6reHCGGU6vNdwU0lYldpiOj9cB3t+u2UuLo6tiFWjLf5Zs" +
- "EQJETd4g/EK9nHxJn0GAKrWnTw7pEHQJ08elzUuy04C/jEEG+4QXU1InzS4o/kR0Sqz2WTGDoSoq" +
- "ewuPRU5bzQs/b9daq3mXrnPtRBL6HfSDAdpTK76iHqLCGdqx3avHjVSBm4zFvEuYBCev+3iKOBmg" +
- "yh7eQRTjz4UOWfy85omMBr7lK8PtfVBDzOXpasxS0uBgdUyBDX4tO6k9jZ8a1kmQRQAAAAEABVgu" +
- "NTA5AAACSDCCAkQwggGtAgRIR8SKMA0GCSqGSIb3DQEBBAUAMGkxCzAJBgNVBAYTAlVTMRMwEQYD" +
- "VQQIEwpDYWxpZm9ybmlhMQwwCgYDVQQHEwNNVFYxDzANBgNVBAoTBkdvb2dsZTEQMA4GA1UECxMH" +
- "QW5kcm9pZDEUMBIGA1UEAxMLVGVzdCBTZXJ2ZXIwHhcNMDgwNjA1MTA0ODQyWhcNMDgwOTAzMTA0" +
- "ODQyWjBpMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEMMAoGA1UEBxMDTVRWMQ8w" +
- "DQYDVQQKEwZHb29nbGUxEDAOBgNVBAsTB0FuZHJvaWQxFDASBgNVBAMTC1Rlc3QgU2VydmVyMIGf" +
- "MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwoC6chqCI84rj1PrXuJgbiit4EV909zR6N0jNlYfg" +
- "itwB39bP39wH03rFm8T59b3mbSptnGmCIpLZn25KPPFsYD3JJ+wFlmiUdEP9H05flfwtFQJnw9uT" +
- "3rRIdYVMPcQ3RoZzwAMliGr882I2thIDbA6xjGU/1nRIdvk0LtxH3QIDAQABMA0GCSqGSIb3DQEB" +
- "BAUAA4GBAJn+6YgUlY18Ie+0+Vt8oEi81DNi/bfPrAUAh63fhhBikx/3R9dl3wh09Z6p7cIdNxjW" +
- "n2ll+cRW9eqF7z75F0Omm0C7/KAEPjukVbszmzeU5VqzkpSt0j84YWi+TfcHRrfvhLbrlmGITVpY" +
- "ol5pHLDyqGmDs53pgwipWqsn/nEXEBgj3EoqPeqHbDf7YaP8h/5BSt0=";
-
- protected int startServer(String name) {
- String keys = useBKS ? SERVER_KEYS_BKS : SERVER_KEYS_JKS;
- TestServer server = new TestServer(true, keys);
- Thread serverThread = new Thread(server);
- serverThread.start();
- try {
- while (!serverReady) {
- Thread.currentThread().sleep(50);
- }
- // give the server 100 millis to accept
- Thread.currentThread().sleep(100);
- } catch (InterruptedException e) {
- // ignore
- }
- return server.sport;
- }
-
- /**
- * Implements a test SSL socket server. It wait for a connection on a given
- * port, requests client authentication (if specified), and read 256 bytes
- * from the socket.
- */
- class TestServer implements Runnable {
-
- public static final int CLIENT_AUTH_NONE = 0;
-
- public static final int CLIENT_AUTH_WANTED = 1;
-
- public static final int CLIENT_AUTH_NEEDED = 2;
-
- private TestTrustManager trustManager;
-
- private Exception exception;
-
- String keys;
-
- private boolean provideKeys;
-
- int sport;
-
- public TestServer(boolean provideKeys, String keys) {
- this.keys = keys;
- this.provideKeys = provideKeys;
-
- trustManager = new TestTrustManager();
- }
-
- public void run() {
- try {
- KeyManager[] keyManagers = provideKeys ? getKeyManagers(keys) : null;
- TrustManager[] trustManagers = new TrustManager[] { trustManager };
-
- SSLContext sslContext = SSLContext.getInstance("TLS");
- sslContext.init(keyManagers, trustManagers, null);
-
- SSLServerSocket serverSocket = (SSLServerSocket)sslContext.getServerSocketFactory().createServerSocket();
-
- serverSocket.bind(new InetSocketAddress(port));
- sport = serverSocket.getLocalPort();
- serverReady = true;
-
- SSLSocket clientSocket = (SSLSocket)serverSocket.accept();
-
- InputStream stream = clientSocket.getInputStream();
-
- for (int i = 0; i < 256; i++) {
- int j = stream.read();
- if (i != j) {
- throw new RuntimeException("Error reading socket, expected " + i + ", got " + j);
- }
- }
-
- stream.close();
- clientSocket.close();
- serverSocket.close();
-
- } catch (Exception ex) {
- exception = ex;
- }
- }
-
- public Exception getException() {
- return exception;
- }
-
- public X509Certificate[] getChain() {
- return trustManager.getChain();
- }
-
- }
-
- /**
- * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
- * for the result.
- */
- private KeyManager[] getKeyManagers(String keys) throws Exception {
- byte[] bytes = new Base64().decode(keys.getBytes());
- InputStream inputStream = new ByteArrayInputStream(bytes);
-
- KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
- keyStore.load(inputStream, PASSWORD.toCharArray());
- inputStream.close();
-
- String algorithm = KeyManagerFactory.getDefaultAlgorithm();
- KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
- keyManagerFactory.init(keyStore, PASSWORD.toCharArray());
-
- return keyManagerFactory.getKeyManagers();
- }
-
- private SSLSocket getSSLSocket() throws IOException {
- SSLSocket ssl = null;
- ssl = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
- return ssl;
- }
-
- private SSLSocket getSSLSocket(InetAddress host, int port) throws IOException {
- SSLSocket ssl = null;
- ssl = (SSLSocket) SSLSocketFactory.getDefault().createSocket(host, port);
- return ssl;
- }
-
- private SSLSocket getSSLSocket(String host, int port) throws UnknownHostException, IOException {
- SSLSocket ssl = null;
- ssl = (SSLSocket) SSLSocketFactory.getDefault().createSocket(host, port);
- return ssl;
- }
-
- private SSLSocket getSSLSocket(InetAddress host, int port, InetAddress localHost, int localPort) throws IOException {
- SSLSocket ssl = null;
- ssl = (SSLSocket) SSLSocketFactory.getDefault().createSocket(host, port, localHost, localPort);
- return ssl;
- }
-
- private SSLSocket getSSLSocket(String host, int port, InetAddress localHost, int localPort) throws UnknownHostException, IOException {
- SSLSocket ssl = null;
- ssl = (SSLSocket) SSLSocketFactory.getDefault().createSocket(host, port, localHost, localPort);
- return ssl;
- }
-}
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/TrustManagerFactory1Test.java b/x-net/src/test/java/tests/api/javax/net/ssl/TrustManagerFactory1Test.java
deleted file mode 100644
index a933288..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/TrustManagerFactory1Test.java
+++ /dev/null
@@ -1,712 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.KnownFailure;
-
-import java.io.IOException;
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.Provider;
-import java.security.PublicKey;
-import java.security.Security;
-import java.security.cert.CertificateException;
-
-import javax.net.ssl.ManagerFactoryParameters;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
-import javax.net.ssl.TrustManagerFactorySpi;
-
-import org.apache.harmony.security.tests.support.SpiEngUtils;
-import org.apache.harmony.security.tests.support.TestKeyPair;
-import org.apache.harmony.xnet.tests.support.MyTrustManagerFactorySpi;
-import junit.framework.TestCase;
-
-//
-import java.security.cert.TrustAnchor;
-import java.security.cert.X509CertSelector;
-import java.security.cert.PKIXBuilderParameters;
-import javax.net.ssl.CertPathTrustManagerParameters;
-
-import java.util.HashSet;
-import java.util.Set;
-
-/**
- * Tests for <code>TrustManagerFactory</code> class constructors and methods.
- *
- */
-@TestTargetClass(TrustManagerFactory.class)
-public class TrustManagerFactory1Test extends TestCase {
-
- private static final String srvTrustManagerFactory = "TrustManagerFactory";
-
- private static String defaultAlgorithm = null;
-
- private static String defaultProviderName = null;
-
- private static Provider defaultProvider = null;
-
- private static boolean DEFSupported = false;
-
- private static final String NotSupportedMsg = "There is no suitable provider for TrustManagerFactory";
-
- private static final String[] invalidValues = SpiEngUtils.invalidValues;
-
- private static String[] validValues = new String[3];
- static {
- defaultAlgorithm = Security
- .getProperty("ssl.TrustManagerFactory.algorithm");
- if (defaultAlgorithm != null) {
- defaultProvider = SpiEngUtils.isSupport(defaultAlgorithm,
- srvTrustManagerFactory);
- DEFSupported = (defaultProvider != null);
- defaultProviderName = (DEFSupported ? defaultProvider.getName()
- : null);
- validValues[0] = defaultAlgorithm;
- validValues[1] = defaultAlgorithm.toUpperCase();
- validValues[2] = defaultAlgorithm.toLowerCase();
- }
- }
-
- protected TrustManagerFactory[] createTMFac() {
- if (!DEFSupported) {
- fail(defaultAlgorithm + " algorithm is not supported");
- return null;
- }
- TrustManagerFactory[] tMF = new TrustManagerFactory[3];
- try {
- tMF[0] = TrustManagerFactory.getInstance(defaultAlgorithm);
- tMF[1] = TrustManagerFactory.getInstance(defaultAlgorithm,
- defaultProvider);
- tMF[2] = TrustManagerFactory.getInstance(defaultAlgorithm,
- defaultProviderName);
- return tMF;
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
-
- /**
- * Test for
- * <code>TrustManagerFactory(TrustManagerFactorySpi impl, Provider prov, String algoriyjm) </code>
- * constructor
- * Assertion: created new TrustManagerFactory object
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "TrustManagerFactory",
- args = {javax.net.ssl.TrustManagerFactorySpi.class, java.security.Provider.class, java.lang.String.class}
- )
- public void test_ConstructorLjavax_net_ssl_TrustManagerFactorySpiLjava_security_ProviderLjava_lang_String()
- throws NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- TrustManagerFactorySpi spi = new MyTrustManagerFactorySpi();
- TrustManagerFactory tmF = new myTrustManagerFactory(spi, defaultProvider,
- defaultAlgorithm);
- assertTrue("Not CertStore object", tmF instanceof TrustManagerFactory);
- assertEquals("Incorrect algorithm", tmF.getAlgorithm(),
- defaultAlgorithm);
- assertEquals("Incorrect provider", tmF.getProvider(), defaultProvider);
- assertNull("Incorrect result", tmF.getTrustManagers());
-
- tmF = new myTrustManagerFactory(null, null, null);
- assertTrue("Not CertStore object", tmF instanceof TrustManagerFactory);
- assertNull("Provider must be null", tmF.getProvider());
- assertNull("Algorithm must be null", tmF.getAlgorithm());
- try {
- tmF.getTrustManagers();
- fail("NullPointerException must be thrown");
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * Test for <code>getAlgorithm()</code> method
- * Assertion: returns the algorithm name of this object
- * @throws NoSuchAlgorithmException
- * @throws NoSuchProviderException
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAlgorithm",
- args = {}
- )
- public void test_getAlgorithm()
- throws NoSuchAlgorithmException, NoSuchProviderException {
- if (!DEFSupported) fail(NotSupportedMsg);
- assertEquals("Incorrect algorithm",
- defaultAlgorithm,
- TrustManagerFactory
- .getInstance(defaultAlgorithm).getAlgorithm());
- assertEquals("Incorrect algorithm",
- defaultAlgorithm,
- TrustManagerFactory
- .getInstance(defaultAlgorithm, defaultProviderName)
- .getAlgorithm());
- assertEquals("Incorrect algorithm",
- defaultAlgorithm,
- TrustManagerFactory.getInstance(defaultAlgorithm, defaultProvider)
- .getAlgorithm());
- }
-
- /**
- * Test for <code>getDefaultAlgorithm()</code> method
- * Assertion: returns value which is specifoed in security property
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDefaultAlgorithm",
- args = {}
- )
- public void test_getDefaultAlgorithm() {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- String def = TrustManagerFactory.getDefaultAlgorithm();
- if (defaultAlgorithm == null) {
- assertNull("DefaultAlgorithm must be null", def);
- } else {
- assertEquals("Invalid default algorithm", def, defaultAlgorithm);
- }
- String defA = "Proba.trustmanagerfactory.defaul.type";
- Security.setProperty("ssl.TrustManagerFactory.algorithm", defA);
- assertEquals("Incorrect defaultAlgorithm",
- TrustManagerFactory.getDefaultAlgorithm(), defA);
- if (def == null) {
- def = "";
- }
- Security.setProperty("ssl.TrustManagerFactory.algorithm", def);
- assertEquals("Incorrect defaultAlgorithm",
- TrustManagerFactory.getDefaultAlgorithm(), def);
- }
-
- /**
- * Test for <code>getInstance(String algorithm)</code> method
- * Assertions: returns security property "ssl.TrustManagerFactory.algorithm";
- * returns instance of TrustManagerFactory
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class}
- )
- public void test_getInstanceLjava_lang_String01() throws NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- TrustManagerFactory trustMF;
- for (int i = 0; i < validValues.length; i++) {
- trustMF = TrustManagerFactory.getInstance(validValues[i]);
- assertTrue("Not TrustManagerFactory object",
- trustMF instanceof TrustManagerFactory);
- assertEquals("Invalid algorithm", trustMF.getAlgorithm(),
- validValues[i]);
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm)</code> method
- * Assertion:
- * throws NullPointerException when algorithm is null;
- * throws NoSuchAlgorithmException when algorithm is not correct;
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class}
- )
- public void test_getInstanceLjava_lang_String02() {
- try {
- TrustManagerFactory.getInstance(null);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- TrustManagerFactory.getInstance(invalidValues[i]);
- fail("NoSuchAlgorithmException was not thrown as expected for algorithm: "
- .concat(invalidValues[i]));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, String provider)</code>
- * method
- * Assertion: throws IllegalArgumentException when provider is null
- * or empty
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_lang_String01() throws NoSuchProviderException,
- NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- String provider = null;
- for (int i = 0; i < validValues.length; i++) {
- try {
- TrustManagerFactory.getInstance(validValues[i], provider);
- fail("IllegalArgumentException must be thrown when provider is null");
- } catch (IllegalArgumentException e) {
- }
- try {
- TrustManagerFactory.getInstance(validValues[i], "");
- fail("IllegalArgumentException must be thrown when provider is empty");
- } catch (IllegalArgumentException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, String provider)</code>
- * method
- * Assertion:
- * throws NullPointerException when algorithm is null;
- * throws NoSuchAlgorithmException when algorithm is not correct;
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_lang_String02() throws NoSuchProviderException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- try {
- TrustManagerFactory.getInstance(null, defaultProviderName);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- TrustManagerFactory.getInstance(invalidValues[i],
- defaultProviderName);
- fail("NoSuchAlgorithmException must be thrown (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, String provider)</code>
- * method
- * Assertion: throws NoSuchProviderException when provider has
- * invalid value
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_lang_String03() throws NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- for (int i = 1; i < invalidValues.length; i++) {
- for (int j = 0; j < validValues.length; j++) {
- try {
- TrustManagerFactory.getInstance(validValues[j],
- invalidValues[i]);
- fail("NuSuchProviderException must be thrown (algorithm: "
- .concat(validValues[j]).concat(" provider: ")
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchProviderException e) {
- }
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, String provider)</code>
- * method
- * Assertion: returns instance of TrustManagerFactory
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_lang_String04() throws NoSuchAlgorithmException,
- NoSuchProviderException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- TrustManagerFactory trustMF;
- for (int i = 0; i < validValues.length; i++) {
- trustMF = TrustManagerFactory.getInstance(validValues[i],
- defaultProviderName);
- assertTrue("Not TrustManagerFactory object",
- trustMF instanceof TrustManagerFactory);
- assertEquals("Invalid algorithm", trustMF.getAlgorithm(),
- validValues[i]);
- assertEquals("Invalid provider", trustMF.getProvider(),
- defaultProvider);
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, Provider provider)</code>
- * method
- * Assertion: throws IllegalArgumentException when provider is null
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.security.Provider.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_security_Provider01() throws NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- Provider provider = null;
- for (int i = 0; i < validValues.length; i++) {
- try {
- TrustManagerFactory.getInstance(validValues[i], provider);
- fail("IllegalArgumentException must be thrown when provider is null");
- } catch (IllegalArgumentException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, Provider provider)</code>
- * method
- * Assertion:
- * throws NullPointerException when algorithm is null;
- * throws NoSuchAlgorithmException when algorithm is not correct;
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.security.Provider.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_security_Provider02() {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- try {
- TrustManagerFactory.getInstance(null, defaultProvider);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- TrustManagerFactory.getInstance(invalidValues[i],
- defaultProvider);
- fail("NoSuchAlgorithmException must be thrown (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, Provider provider)</code>
- * method
- * Assertion: returns instance of TrustManagerFactory
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.security.Provider.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_security_Provider03() throws NoSuchAlgorithmException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- TrustManagerFactory trustMF;
- for (int i = 0; i < validValues.length; i++) {
- trustMF = TrustManagerFactory.getInstance(validValues[i],
- defaultProvider);
- assertTrue("Not TrustManagerFactory object",
- trustMF instanceof TrustManagerFactory);
- assertEquals("Invalid algorithm", trustMF.getAlgorithm(),
- validValues[i]);
- assertEquals("Invalid provider", trustMF.getProvider(),
- defaultProvider);
- }
- }
-
- /**
- * Test for <code>getProvider()</code>
- * @throws NoSuchAlgorithmException
- * @throws NoSuchProviderException
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getProvider",
- args = {}
- )
- public void test_getProvider()
- throws NoSuchAlgorithmException, NoSuchProviderException {
- if (!DEFSupported) fail(NotSupportedMsg);
- assertEquals("Incorrect provider",
- defaultProvider,
- TrustManagerFactory
- .getInstance(defaultAlgorithm).getProvider());
- assertEquals("Incorrect provider",
- defaultProvider,
- TrustManagerFactory
- .getInstance(defaultAlgorithm, defaultProviderName)
- .getProvider());
- assertEquals("Incorrect provider",
- defaultProvider,
- TrustManagerFactory.getInstance(defaultAlgorithm, defaultProvider)
- .getProvider());
- }
-
- /**
- * Test for <code>geTrustManagers()</code>
- * @throws KeyStoreException
- * @throws IOException
- * @throws CertificateException
- * @throws NoSuchAlgorithmException
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTrustManagers",
- args = {}
- )
- public void test_getTrustManagers() {
- try {
- TrustManagerFactory trustMF = TrustManagerFactory.getInstance(defaultAlgorithm);
- KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
- ks.load(null, null);
- trustMF.init(ks);
- TrustManager[] tm = trustMF.getTrustManagers();
- assertNotNull("Result has not be null", tm);
- assertTrue("Length of result TrustManager array should not be 0",
- (tm.length > 0));
- } catch (Exception ex) {
- fail("Unexpected exception " + ex.toString());
- }
- }
-
- /**
- * Test for <code>init(KeyStore keyStore)</code>
- * Assertion: call method with null parameter
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "init",
- args = {java.security.KeyStore.class}
- )
- public void test_initLjava_security_KeyStore_01() {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
-
- KeyStore ksNull = null;
- TrustManagerFactory[] trustMF = createTMFac();
- assertNotNull("TrustManagerFactory objects were not created", trustMF);
- // null parameter
- try {
- trustMF[0].init(ksNull);
- } catch (Exception ex) {
- fail(ex + " unexpected exception was thrown for null parameter");
- }
- }
-
- /**
- * Test for <code>init(KeyStore keyStore)</code>
- * Assertion: call method with not null parameter
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "init",
- args = {java.security.KeyStore.class}
- )
- public void test_initLjava_security_KeyStore_02() throws KeyStoreException {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
-
- KeyStore ks;
- ks = KeyStore.getInstance(KeyStore.getDefaultType());
- TrustManagerFactory[] trustMF = createTMFac();
- assertNotNull("TrustManagerFactory objects were not created", trustMF);
-
- // not null parameter
- try {
- trustMF[0].init(ks);
- } catch (Exception ex) {
- fail(ex + " unexpected exception was thrown for not null parameter");
- }
- }
-
- /**
- * Test for <code>init(ManagerFactoryParameters params)</code>
- * Assertion:
- * throws InvalidAlgorithmParameterException when params is null
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "init",
- args = {javax.net.ssl.ManagerFactoryParameters.class}
- )
- @KnownFailure("ManagerFactoryParameters object is not supported " +
- "and InvalidAlgorithmParameterException was thrown.")
- public void test_initLjavax_net_ssl_ManagerFactoryParameters() {
- if (!DEFSupported) {
- fail(NotSupportedMsg);
- return;
- }
- ManagerFactoryParameters par = null;
- TrustManagerFactory[] trustMF = createTMFac();
- assertNotNull("TrustManagerFactory objects were not created", trustMF);
- for (int i = 0; i < trustMF.length; i++) {
- try {
- trustMF[i].init(par);
- fail("InvalidAlgorithmParameterException must be thrown");
- } catch (InvalidAlgorithmParameterException e) {
- }
- }
-
- //
- String keyAlg = "DSA";
- String validCaNameRfc2253 = "CN=Test CA," +
- "OU=Testing Division," +
- "O=Test It All," +
- "L=Test Town," +
- "ST=Testifornia," +
- "C=Testland";
-
- try {
- KeyStore kStore = KeyStore.getInstance(KeyStore.getDefaultType());
- kStore.load(null, null);
- PublicKey pk = new TestKeyPair(keyAlg).getPublic();
- TrustAnchor ta = new TrustAnchor(validCaNameRfc2253, pk, getFullEncoding());
- Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
- trustAnchors.add(ta);
- X509CertSelector xcs = new X509CertSelector();
- PKIXBuilderParameters pkixBP = new PKIXBuilderParameters(trustAnchors, xcs);
- CertPathTrustManagerParameters cptmp = new CertPathTrustManagerParameters(pkixBP);
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(defaultAlgorithm);
- try {
- tmf.init(cptmp);
- } catch (Exception ex) {
- fail(ex + " was thrown for init(ManagerFactoryParameters spec)");
- }
- } catch (Exception e) {
- fail("Unexpected exception for configuration: " + e);
- }
-
- }
-
- private static final byte[] getFullEncoding() {
- // DO NOT MODIFY!
- return new byte[] {
- (byte)0x30,(byte)0x81,(byte)0x8c,(byte)0xa0,
- (byte)0x44,(byte)0x30,(byte)0x16,(byte)0x86,
- (byte)0x0e,(byte)0x66,(byte)0x69,(byte)0x6c,
- (byte)0x65,(byte)0x3a,(byte)0x2f,(byte)0x2f,
- (byte)0x66,(byte)0x6f,(byte)0x6f,(byte)0x2e,
- (byte)0x63,(byte)0x6f,(byte)0x6d,(byte)0x80,
- (byte)0x01,(byte)0x00,(byte)0x81,(byte)0x01,
- (byte)0x01,(byte)0x30,(byte)0x16,(byte)0x86,
- (byte)0x0e,(byte)0x66,(byte)0x69,(byte)0x6c,
- (byte)0x65,(byte)0x3a,(byte)0x2f,(byte)0x2f,
- (byte)0x62,(byte)0x61,(byte)0x72,(byte)0x2e,
- (byte)0x63,(byte)0x6f,(byte)0x6d,(byte)0x80,
- (byte)0x01,(byte)0x00,(byte)0x81,(byte)0x01,
- (byte)0x01,(byte)0x30,(byte)0x12,(byte)0x86,
- (byte)0x0a,(byte)0x66,(byte)0x69,(byte)0x6c,
- (byte)0x65,(byte)0x3a,(byte)0x2f,(byte)0x2f,
- (byte)0x6d,(byte)0x75,(byte)0x75,(byte)0x80,
- (byte)0x01,(byte)0x00,(byte)0x81,(byte)0x01,
- (byte)0x01,(byte)0xa1,(byte)0x44,(byte)0x30,
- (byte)0x16,(byte)0x86,(byte)0x0e,(byte)0x68,
- (byte)0x74,(byte)0x74,(byte)0x70,(byte)0x3a,
- (byte)0x2f,(byte)0x2f,(byte)0x66,(byte)0x6f,
- (byte)0x6f,(byte)0x2e,(byte)0x63,(byte)0x6f,
- (byte)0x6d,(byte)0x80,(byte)0x01,(byte)0x00,
- (byte)0x81,(byte)0x01,(byte)0x01,(byte)0x30,
- (byte)0x16,(byte)0x86,(byte)0x0e,(byte)0x68,
- (byte)0x74,(byte)0x74,(byte)0x70,(byte)0x3a,
- (byte)0x2f,(byte)0x2f,(byte)0x62,(byte)0x61,
- (byte)0x72,(byte)0x2e,(byte)0x63,(byte)0x6f,
- (byte)0x6d,(byte)0x80,(byte)0x01,(byte)0x00,
- (byte)0x81,(byte)0x01,(byte)0x01,(byte)0x30,
- (byte)0x12,(byte)0x86,(byte)0x0a,(byte)0x68,
- (byte)0x74,(byte)0x74,(byte)0x70,(byte)0x3a,
- (byte)0x2f,(byte)0x2f,(byte)0x6d,(byte)0x75,
- (byte)0x75,(byte)0x80,(byte)0x01,(byte)0x00,
- (byte)0x81,(byte)0x01,(byte)0x01
- };
- }
-}
-
-/**
- * Addifional class to verify TrustManagerFactory constructor
- */
-
-class myTrustManagerFactory extends TrustManagerFactory {
- public myTrustManagerFactory(TrustManagerFactorySpi spi, Provider prov,
- String alg) {
- super(spi, prov, alg);
- }
-}
-
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/TrustManagerFactory2Test.java b/x-net/src/test/java/tests/api/javax/net/ssl/TrustManagerFactory2Test.java
deleted file mode 100644
index e16a62f..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/TrustManagerFactory2Test.java
+++ /dev/null
@@ -1,279 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.Provider;
-import java.security.Security;
-
-import javax.net.ssl.ManagerFactoryParameters;
-import javax.net.ssl.TrustManagerFactory;
-
-import org.apache.harmony.security.tests.support.SpiEngUtils;
-import org.apache.harmony.xnet.tests.support.MyTrustManagerFactorySpi;
-import junit.framework.TestCase;
-
-/**
- * Tests for TrustManagerFactory class constructors and methods
- *
- */
-@TestTargetClass(TrustManagerFactory.class)
-public class TrustManagerFactory2Test extends TestCase {
- private static final String srvTrustManagerFactory = "TrustManagerFactory";
- private static final String defaultAlg = "TMF";
- private static final String TrustManagerFactoryProviderClass = "org.apache.harmony.xnet.tests.support.MyTrustManagerFactorySpi";
-
- private static final String[] invalidValues = SpiEngUtils.invalidValues;
-
- private static final String[] validValues;
-
- static {
- validValues = new String[4];
- validValues[0] = defaultAlg;
- validValues[1] = defaultAlg.toLowerCase();
- validValues[2] = "Tmf";
- validValues[3] = "tMF";
- }
-
- Provider mProv;
-
- protected void setUp() throws Exception {
- super.setUp();
- mProv = (new SpiEngUtils()).new MyProvider("MyTMFProvider",
- "Provider for testing", srvTrustManagerFactory.concat(".")
- .concat(defaultAlg), TrustManagerFactoryProviderClass);
- Security.insertProviderAt(mProv, 1);
- }
-
- /*
- * @see TestCase#tearDown()
- */
- protected void tearDown() throws Exception {
- super.tearDown();
- Security.removeProvider(mProv.getName());
- }
-
- private void checkResult(TrustManagerFactory tmf) throws Exception {
- KeyStore kStore = null;
- ManagerFactoryParameters mfp = null;
-
- try {
- tmf.init(kStore);
- fail("KeyStoreException must be thrown");
- } catch (KeyStoreException e) {
- }
- try {
- tmf.init(mfp);
- fail("InvalidAlgorithmParameterException must be thrown");
- } catch (InvalidAlgorithmParameterException e) {
- }
- assertNull("getTrustManagers() should return null object", tmf
- .getTrustManagers());
-
- try {
- kStore = KeyStore.getInstance(KeyStore.getDefaultType());
- kStore.load(null, null);
- } catch (KeyStoreException e) {
- fail("default keystore is not supported");
- return;
- }
- tmf.init(kStore);
- mfp = (ManagerFactoryParameters) new MyTrustManagerFactorySpi.Parameters(null);
- try {
- tmf.init(mfp);
- fail("RuntimeException must be thrown");
- } catch (RuntimeException e) {
- assertTrue("Incorrect exception", e.getCause() instanceof KeyStoreException);
- }
- mfp = (ManagerFactoryParameters) new MyTrustManagerFactorySpi.Parameters(kStore);
- tmf.init(mfp);
- }
-
- /**
- * Test for <code>getInstance(String algorithm)</code> method
- * Assertions:
- * throws NullPointerException when algorithm is null;
- * throws NoSuchAlgorithmException when algorithm is not correct;
- * returns TrustManagerFactory object
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class}
- )
- public void test_getInstanceLjava_lang_String() throws Exception {
- try {
- TrustManagerFactory.getInstance(null);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- TrustManagerFactory.getInstance(invalidValues[i]);
- fail("NoSuchAlgorithmException must be thrown (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- TrustManagerFactory tmf;
- for (int i = 0; i < validValues.length; i++) {
- tmf = TrustManagerFactory.getInstance(validValues[i]);
- assertTrue("Not instanceof TrustManagerFactory object",
- tmf instanceof TrustManagerFactory);
- assertEquals("Incorrect algorithm", tmf.getAlgorithm(),
- validValues[i]);
- assertEquals("Incorrect provider", tmf.getProvider(), mProv);
- checkResult(tmf);
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, String provider)</code>
- * method
- * Assertions:
- * throws NullPointerException when algorithm is null;
- * throws NoSuchAlgorithmException when algorithm is not correct;
- * throws IllegalArgumentException when provider is null or empty;
- * throws NoSuchProviderException when provider is available;
- * returns TrustManagerFactory object
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_getInstanceLjava_lang_StringLjava_lang_String() throws Exception {
- try {
- TrustManagerFactory.getInstance(null, mProv.getName());
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- TrustManagerFactory.getInstance(invalidValues[i], mProv
- .getName());
- fail("NoSuchAlgorithmException must be thrown (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- String prov = null;
- for (int i = 0; i < validValues.length; i++) {
- try {
- TrustManagerFactory.getInstance(validValues[i], prov);
- fail("IllegalArgumentException must be thrown when provider is null (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (IllegalArgumentException e) {
- }
- try {
- TrustManagerFactory.getInstance(validValues[i], "");
- fail("IllegalArgumentException must be thrown when provider is empty (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (IllegalArgumentException e) {
- }
- }
- for (int i = 0; i < validValues.length; i++) {
- for (int j = 1; j < invalidValues.length; j++) {
- try {
- TrustManagerFactory.getInstance(validValues[i],
- invalidValues[j]);
- fail("NoSuchProviderException must be thrown (algorithm: "
- .concat(invalidValues[i]).concat(" provider: ")
- .concat(invalidValues[j]).concat(")"));
- } catch (NoSuchProviderException e) {
- }
- }
- }
- TrustManagerFactory tmf;
- for (int i = 0; i < validValues.length; i++) {
- tmf = TrustManagerFactory.getInstance(validValues[i], mProv
- .getName());
- assertTrue("Not instanceof TrustManagerFactory object",
- tmf instanceof TrustManagerFactory);
- assertEquals("Incorrect algorithm", tmf.getAlgorithm(),
- validValues[i]);
- assertEquals("Incorrect provider", tmf.getProvider().getName(),
- mProv.getName());
- checkResult(tmf);
- }
- }
-
- /**
- * Test for <code>getInstance(String algorithm, Provider provider)</code>
- * method
- * Assertions:
- * throws NullPointerException when algorithm is null;
- * throws NoSuchAlgorithmException when algorithm is not correct;
- * throws IllegalArgumentException when provider is null;
- * returns TrustManagerFactory object
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.lang.String.class, java.security.Provider.class}
- )
- public void testLjava_lang_StringLjava_security_Provider() throws Exception {
- try {
- TrustManagerFactory.getInstance(null, mProv);
- fail("NoSuchAlgorithmException or NullPointerException should be thrown (algorithm is null");
- } catch (NoSuchAlgorithmException e) {
- } catch (NullPointerException e) {
- }
- for (int i = 0; i < invalidValues.length; i++) {
- try {
- TrustManagerFactory.getInstance(invalidValues[i], mProv);
- fail("NoSuchAlgorithmException must be thrown (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (NoSuchAlgorithmException e) {
- }
- }
- Provider prov = null;
- for (int i = 0; i < validValues.length; i++) {
- try {
- TrustManagerFactory.getInstance(validValues[i], prov);
- fail("IllegalArgumentException must be thrown when provider is null (algorithm: "
- .concat(invalidValues[i]).concat(")"));
- } catch (IllegalArgumentException e) {
- }
- }
- TrustManagerFactory tmf;
- for (int i = 0; i < validValues.length; i++) {
- tmf = TrustManagerFactory.getInstance(validValues[i], mProv);
- assertTrue("Not instanceof TrustManagerFactory object",
- tmf instanceof TrustManagerFactory);
- assertEquals("Incorrect algorithm", tmf.getAlgorithm(),
- validValues[i]);
- assertEquals("Incorrect provider", tmf.getProvider(), mProv);
- checkResult(tmf);
- }
- }
-} \ No newline at end of file
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/TrustManagerFactorySpiTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/TrustManagerFactorySpiTest.java
deleted file mode 100644
index 6c6d9aa..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/TrustManagerFactorySpiTest.java
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.security.AccessController;
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.Provider;
-
-import javax.net.ssl.ManagerFactoryParameters;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
-import javax.net.ssl.TrustManagerFactorySpi;
-
-import junit.framework.TestCase;
-import org.apache.harmony.xnet.tests.support.TrustManagerFactorySpiImpl;
-import org.apache.harmony.xnet.tests.support.MyTrustManagerFactorySpi.Parameters;
-
-@TestTargetClass(TrustManagerFactorySpi.class)
-public class TrustManagerFactorySpiTest extends TestCase {
-
- private TrustManagerFactorySpiImpl factory = new TrustManagerFactorySpiImpl();
- /**
- * @tests javax.net.ssl.TrustManagerFactorySpi#TrustManagerFactorySpi()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "TrustManagerFactorySpi",
- args = {}
- )
- public void test_Constructor() {
- try {
- TrustManagerFactorySpiImpl tmf = new TrustManagerFactorySpiImpl();
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @throws KeyStoreException
- * @tests javax.net.ssl.TrustManagerFactorySpi#engineInit(KeyStore ks)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "engineInit",
- args = {java.security.KeyStore.class}
- )
- public void test_engineInit_01() throws NoSuchAlgorithmException,
- KeyStoreException {
- factory.reset();
- Provider provider = new MyProvider();
- TrustManagerFactory tmf = TrustManagerFactory.getInstance("MyTMF",
- provider);
- KeyStore ks = null;
- try {
- ks = KeyStore.getInstance(KeyStore.getDefaultType());
- ks.load(null, null);
- tmf.init(ks);
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- assertTrue(factory.isEngineInitCalled());
- assertEquals(ks, factory.getKs());
- factory.reset();
- tmf.init((KeyStore) null);
- assertTrue(factory.isEngineInitCalled());
- assertNull(factory.getKs());
- }
-
- /**
- * @throws InvalidAlgorithmParameterException
- * @throws NoSuchAlgorithmException
- * @tests javax.net.ssl.TrustManagerFactorySpi#engineInit(ManagerFactoryParameters spec)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "engineInit",
- args = {javax.net.ssl.ManagerFactoryParameters.class}
- )
- public void test_engineInit_02() throws InvalidAlgorithmParameterException,
- NoSuchAlgorithmException {
- factory.reset();
- Provider provider = new MyProvider();
- TrustManagerFactory tmf = TrustManagerFactory.getInstance("MyTMF",
- provider);
- Parameters pr = null;
- try {
- KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
- ks.load(null, null);
- pr = new Parameters(ks);
- tmf.init(pr);
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- assertTrue(factory.isEngineInitCalled());
- assertEquals(pr, factory.getSpec());
- factory.reset();
- tmf.init((ManagerFactoryParameters) null);
- assertTrue(factory.isEngineInitCalled());
- assertNull(factory.getSpec());
- }
-
- /**
- * @throws NoSuchAlgorithmException
- * @tests javax.net.ssl.TrustManagerFactorySpi#engineGetTrustManagers()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "engineGetTrustManagers",
- args = {}
- )
- public void test_engineGetTrustManagers() throws NoSuchAlgorithmException {
- factory.reset();
- Provider provider = new MyProvider();
- TrustManagerFactory tmf = TrustManagerFactory.getInstance("MyTMF",
- provider);
- TrustManager[] tm = tmf.getTrustManagers();
- assertTrue(factory.isEngineGetTrustManagersCalled());
- factory.reset();
- try {
- KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
- ks.load(null, null);
- tmf.init(ks);
- tm = tmf.getTrustManagers();
- assertTrue(factory.isEngineGetTrustManagersCalled());
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-}
-
-class MyProvider extends Provider {
-
- public MyProvider() {
- super("MyProvider", 1.0, "My Test Provider");
- AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
- public Void run() {
- put("TrustManagerFactory.MyTMF",
- "org.apache.harmony.xnet.tests.support.TrustManagerFactorySpiImpl");
- return null;
- }
- });
- }
-}
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/X509ExtendedKeyManagerTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/X509ExtendedKeyManagerTest.java
deleted file mode 100644
index 5f711b1..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/X509ExtendedKeyManagerTest.java
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.Socket;
-import java.security.Principal;
-import java.security.PrivateKey;
-import java.security.cert.X509Certificate;
-
-import javax.net.ssl.X509ExtendedKeyManager;
-
-import junit.framework.TestCase;
-
-/**
- * Tests for <code>X509ExtendedKeyManager</code> class constructors and methods.
- *
- */
-@TestTargetClass(X509ExtendedKeyManager.class)
-public class X509ExtendedKeyManagerTest extends TestCase {
-
- private class MockX509ExtendedKeyManager extends X509ExtendedKeyManager {
- public MockX509ExtendedKeyManager() {
- super();
- }
-
- /**
- * @see javax.net.ssl.X509KeyManager#chooseClientAlias(java.lang.String[], java.security.Principal[], java.net.Socket)
- */
- public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) {
- // it is a fake
- return null;
- }
-
- /**
- * @see javax.net.ssl.X509KeyManager#chooseServerAlias(java.lang.String, java.security.Principal[], java.net.Socket)
- */
- public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) {
- // it is a fake
- return null;
- }
-
- /**
- * @see javax.net.ssl.X509KeyManager#getCertificateChain(java.lang.String)
- */
- public X509Certificate[] getCertificateChain(String arg0) {
- // it is a fake
- return null;
- }
-
- /**
- * @see javax.net.ssl.X509KeyManager#getClientAliases(java.lang.String, java.security.Principal[])
- */
- public String[] getClientAliases(String arg0, Principal[] arg1) {
- // it is a fake
- return null;
- }
-
- /**
- * @see javax.net.ssl.X509KeyManager#getPrivateKey(java.lang.String)
- */
- public PrivateKey getPrivateKey(String arg0) {
- // it is a fake
- return null;
- }
-
- /**
- * @see javax.net.ssl.X509KeyManager#getServerAliases(java.lang.String, java.security.Principal[])
- */
- public String[] getServerAliases(String arg0, Principal[] arg1) {
- // it is a fake
- return null;
- }
- }
-
- /**
- * @tests javax.net.ssl.X509ExtendedKeyManager#X509ExtendedKeyManager()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "X509ExtendedKeyManager",
- args = {}
- )
- public final void test_Constructor() {
- try {
- new MockX509ExtendedKeyManager();
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- /**
- * @tests javax.net.ssl.X509ExtendedKeyManager
- * #chooseEngineClientAlias(java.lang.String[],
- * java.security.Principal[], javax.net.ssl.SSLEngine)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "chooseEngineClientAlias",
- args = {java.lang.String[].class, java.security.Principal[].class, javax.net.ssl.SSLEngine.class}
- )
- public final void test_chooseEngineClientAlias() {
- X509ExtendedKeyManager km = new MyX509ExtendedKeyManager();
- if (km.chooseEngineClientAlias(null, null, null) != null) {
- fail("non null result");
- }
- }
-
- /**
- * @tests javax.net.ssl.X509ExtendedKeyManager
- * #chooseEngineServerAlias(java.lang.String,
- * java.security.Principal[], javax.net.ssl.SSLEngine)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "chooseEngineServerAlias",
- args = {java.lang.String.class, java.security.Principal[].class, javax.net.ssl.SSLEngine.class}
- )
- public final void test_chooseEngineServerAlias() {
- X509ExtendedKeyManager km = new MyX509ExtendedKeyManager();
- if (km.chooseEngineServerAlias(null, null, null) != null) {
- fail("non null result");
- }
- }
-
-}
-
-class MyX509ExtendedKeyManager extends X509ExtendedKeyManager {
-
- /*
- * @see javax.net.ssl.X509KeyManager#chooseClientAlias(java.lang.String[],
- * java.security.Principal[], java.net.Socket)
- */
- public String chooseClientAlias(String[] keyType, Principal[] issuers,
- Socket socket) {
- return null;
- }
-
- /*
- * @see javax.net.ssl.X509KeyManager#chooseServerAlias(java.lang.String,
- * java.security.Principal[], java.net.Socket)
- */
- public String chooseServerAlias(String keyType, Principal[] issuers,
- Socket socket) {
- return null;
- }
-
- /*
- * @see javax.net.ssl.X509KeyManager#getCertificateChain(java.lang.String)
- */
- public X509Certificate[] getCertificateChain(String alias) {
- return null;
- }
-
- /*
- * @see javax.net.ssl.X509KeyManager#getClientAliases(java.lang.String,
- * java.security.Principal[])
- */
- public String[] getClientAliases(String keyType, Principal[] issuers) {
- return null;
- }
-
- /*
- * @see javax.net.ssl.X509KeyManager#getServerAliases(java.lang.String,
- * java.security.Principal[])
- */
- public String[] getServerAliases(String keyType, Principal[] issuers) {
- return null;
- }
-
- /*
- * @see javax.net.ssl.X509KeyManager#getPrivateKey(java.lang.String)
- */
- public PrivateKey getPrivateKey(String alias) {
- return null;
- }
-
-}
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/X509KeyManagerTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/X509KeyManagerTest.java
deleted file mode 100644
index 715efcd..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/X509KeyManagerTest.java
+++ /dev/null
@@ -1,794 +0,0 @@
-package tests.api.javax.net.ssl;
-
-import java.io.ByteArrayInputStream;
-import java.net.Socket;
-import java.security.KeyFactory;
-import java.security.KeyStore;
-import java.security.NoSuchAlgorithmException;
-import java.security.PrivateKey;
-import java.security.cert.CertificateFactory;
-import java.security.cert.X509Certificate;
-import java.security.spec.PKCS8EncodedKeySpec;
-
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.X509KeyManager;
-
-import junit.framework.TestCase;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-/**
- * Tests for <code>X509KeyManager</code> class constructors and methods.
- */
-@TestTargetClass(X509KeyManager.class)
-public class X509KeyManagerTest extends TestCase {
-
- private X509KeyManager manager;
- private KeyManagerFactory factory;
-
- private String keyType;
- private String client = "CLIENT";
- private String server = "SERVER";
- private String type = "RSA";
- private KeyStore keyTest;
- private X509Certificate[] cert = null;
- private PrivateKey[] keys = null;
- private String password = "1234";
-
-
- /*
- Certificate:
- Data:
- Version: 3 (0x2)
- Serial Number: 0 (0x0)
- Signature Algorithm: sha1WithRSAEncryption
- Issuer: C=AN, ST=Android, O=Android, OU=Android, CN=Android/emailAddress=android@android.com
- Validity
- Not Before: Mar 20 17:00:06 2009 GMT
- Not After : Mar 19 17:00:06 2012 GMT
- Subject: C=AN, ST=Android, O=Android, OU=Android, CN=Android/emailAddress=android@android.com
- Subject Public Key Info:
- Public Key Algorithm: rsaEncryption
- RSA Public Key: (1024 bit)
- Modulus (1024 bit):
- 00:aa:42:40:ed:92:21:17:99:5f:0e:e4:42:b8:cb:
- 66:3d:63:2a:16:34:3c:7b:d3:3e:1f:a8:3f:bd:9a:
- eb:b3:24:6b:8c:e4:da:2f:31:bc:61:07:27:2e:28:
- 71:77:58:ae:b4:89:7c:eb:b0:06:24:07:57:3c:54:
- 71:db:71:41:05:ab:3d:9f:05:d2:ca:cb:1c:bf:9d:
- 8a:21:96:8f:13:61:25:69:12:3b:77:bd:f7:34:b2:
- 09:a9:e0:52:94:44:31:ce:db:3d:eb:64:f1:d6:ca:
- c5:7d:2f:d6:6f:8d:e4:29:8b:06:98:8a:95:3d:7a:
- 97:41:9a:f1:66:c5:09:82:0d
- Exponent: 65537 (0x10001)
- X509v3 extensions:
- X509v3 Subject Key Identifier:
- E7:9B:7D:90:29:EA:90:0B:7F:08:41:76:4E:41:23:E8:43:2C:A9:03
- X509v3 Authority Key Identifier:
- keyid:E7:9B:7D:90:29:EA:90:0B:7F:08:41:76:4E:41:23:E8:43:2C:A9:03
- DirName:/C=AN/ST=Android/O=Android/OU=Android/CN=Android/emailAddress=android@android.com
- serial:00
-
- X509v3 Basic Constraints:
- CA:TRUE
- Signature Algorithm: sha1WithRSAEncryption
- 14:98:30:29:42:ef:ab:e6:b8:25:4b:55:85:04:a5:c4:dd:1d:
- 8b:6a:c1:6f:6c:1c:1d:c3:61:34:30:07:34:4d:6a:8b:55:6f:
- 75:55:6e:15:58:c5:f8:af:e0:be:73:ba:d9:a5:85:d7:b5:1a:
- 85:44:2b:88:fd:cc:cb:d1:ed:46:69:43:ff:59:ae:9b:5c:17:
- 26:da:ee:c8:bf:67:55:01:a0:0e:10:b9:85:49:54:d9:79:1e:
- 7b:2e:6f:65:4f:d9:10:2e:9d:b8:92:63:67:74:8b:22:0d:6d:
- d3:5d:9e:29:63:f9:36:93:1b:a7:80:e2:b1:f1:bf:29:19:81:
- 3d:07
- */
- String certificate = "-----BEGIN CERTIFICATE-----\n"
- + "MIIDPzCCAqigAwIBAgIBADANBgkqhkiG9w0BAQUFADB5MQswCQYDVQQGEwJBTjEQ\n"
- + "MA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5k\n"
- + "cm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBh\n"
- + "bmRyb2lkLmNvbTAeFw0wOTAzMjAxNzAwMDZaFw0xMjAzMTkxNzAwMDZaMHkxCzAJ\n"
- + "BgNVBAYTAkFOMRAwDgYDVQQIEwdBbmRyb2lkMRAwDgYDVQQKEwdBbmRyb2lkMRAw\n"
- + "DgYDVQQLEwdBbmRyb2lkMRAwDgYDVQQDEwdBbmRyb2lkMSIwIAYJKoZIhvcNAQkB\n"
- + "FhNhbmRyb2lkQGFuZHJvaWQuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB\n"
- + "gQCqQkDtkiEXmV8O5EK4y2Y9YyoWNDx70z4fqD+9muuzJGuM5NovMbxhBycuKHF3\n"
- + "WK60iXzrsAYkB1c8VHHbcUEFqz2fBdLKyxy/nYohlo8TYSVpEjt3vfc0sgmp4FKU\n"
- + "RDHO2z3rZPHWysV9L9ZvjeQpiwaYipU9epdBmvFmxQmCDQIDAQABo4HWMIHTMB0G\n"
- + "A1UdDgQWBBTnm32QKeqQC38IQXZOQSPoQyypAzCBowYDVR0jBIGbMIGYgBTnm32Q\n"
- + "KeqQC38IQXZOQSPoQyypA6F9pHsweTELMAkGA1UEBhMCQU4xEDAOBgNVBAgTB0Fu\n"
- + "ZHJvaWQxEDAOBgNVBAoTB0FuZHJvaWQxEDAOBgNVBAsTB0FuZHJvaWQxEDAOBgNV\n"
- + "BAMTB0FuZHJvaWQxIjAgBgkqhkiG9w0BCQEWE2FuZHJvaWRAYW5kcm9pZC5jb22C\n"
- + "AQAwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOBgQAUmDApQu+r5rglS1WF\n"
- + "BKXE3R2LasFvbBwdw2E0MAc0TWqLVW91VW4VWMX4r+C+c7rZpYXXtRqFRCuI/czL\n"
- + "0e1GaUP/Wa6bXBcm2u7Iv2dVAaAOELmFSVTZeR57Lm9lT9kQLp24kmNndIsiDW3T\n"
- + "XZ4pY/k2kxungOKx8b8pGYE9Bw==\n"
- + "-----END CERTIFICATE-----";
-
- ByteArrayInputStream certArray = new ByteArrayInputStream(certificate
- .getBytes());
-
- /*
- * The key in DER format.
- * Below is the same key in PEM format as reference
- */
- byte[] keyBytes = new byte[] {
- (byte)0x30, (byte)0x82, (byte)0x02, (byte)0x77, (byte)0x02, (byte)0x01, (byte)0x00,
- (byte)0x30, (byte)0x0d, (byte)0x06, (byte)0x09, (byte)0x2a, (byte)0x86, (byte)0x48,
- (byte)0x86, (byte)0xf7, (byte)0x0d, (byte)0x01, (byte)0x01, (byte)0x01, (byte)0x05,
- (byte)0x00, (byte)0x04, (byte)0x82, (byte)0x02, (byte)0x61, (byte)0x30, (byte)0x82,
- (byte)0x02, (byte)0x5d, (byte)0x02, (byte)0x01, (byte)0x00, (byte)0x02, (byte)0x81,
- (byte)0x81, (byte)0x00, (byte)0xaa, (byte)0x42, (byte)0x40, (byte)0xed, (byte)0x92,
- (byte)0x21, (byte)0x17, (byte)0x99, (byte)0x5f, (byte)0x0e, (byte)0xe4, (byte)0x42,
- (byte)0xb8, (byte)0xcb, (byte)0x66, (byte)0x3d, (byte)0x63, (byte)0x2a, (byte)0x16,
- (byte)0x34, (byte)0x3c, (byte)0x7b, (byte)0xd3, (byte)0x3e, (byte)0x1f, (byte)0xa8,
- (byte)0x3f, (byte)0xbd, (byte)0x9a, (byte)0xeb, (byte)0xb3, (byte)0x24, (byte)0x6b,
- (byte)0x8c, (byte)0xe4, (byte)0xda, (byte)0x2f, (byte)0x31, (byte)0xbc, (byte)0x61,
- (byte)0x07, (byte)0x27, (byte)0x2e, (byte)0x28, (byte)0x71, (byte)0x77, (byte)0x58,
- (byte)0xae, (byte)0xb4, (byte)0x89, (byte)0x7c, (byte)0xeb, (byte)0xb0, (byte)0x06,
- (byte)0x24, (byte)0x07, (byte)0x57, (byte)0x3c, (byte)0x54, (byte)0x71, (byte)0xdb,
- (byte)0x71, (byte)0x41, (byte)0x05, (byte)0xab, (byte)0x3d, (byte)0x9f, (byte)0x05,
- (byte)0xd2, (byte)0xca, (byte)0xcb, (byte)0x1c, (byte)0xbf, (byte)0x9d, (byte)0x8a,
- (byte)0x21, (byte)0x96, (byte)0x8f, (byte)0x13, (byte)0x61, (byte)0x25, (byte)0x69,
- (byte)0x12, (byte)0x3b, (byte)0x77, (byte)0xbd, (byte)0xf7, (byte)0x34, (byte)0xb2,
- (byte)0x09, (byte)0xa9, (byte)0xe0, (byte)0x52, (byte)0x94, (byte)0x44, (byte)0x31,
- (byte)0xce, (byte)0xdb, (byte)0x3d, (byte)0xeb, (byte)0x64, (byte)0xf1, (byte)0xd6,
- (byte)0xca, (byte)0xc5, (byte)0x7d, (byte)0x2f, (byte)0xd6, (byte)0x6f, (byte)0x8d,
- (byte)0xe4, (byte)0x29, (byte)0x8b, (byte)0x06, (byte)0x98, (byte)0x8a, (byte)0x95,
- (byte)0x3d, (byte)0x7a, (byte)0x97, (byte)0x41, (byte)0x9a, (byte)0xf1, (byte)0x66,
- (byte)0xc5, (byte)0x09, (byte)0x82, (byte)0x0d, (byte)0x02, (byte)0x03, (byte)0x01,
- (byte)0x00, (byte)0x01, (byte)0x02, (byte)0x81, (byte)0x80, (byte)0x34, (byte)0x91,
- (byte)0x8e, (byte)0x50, (byte)0x8b, (byte)0xfc, (byte)0xf1, (byte)0xb7, (byte)0x66,
- (byte)0x35, (byte)0x47, (byte)0xdf, (byte)0x1e, (byte)0x05, (byte)0x97, (byte)0x44,
- (byte)0xbe, (byte)0xf8, (byte)0x80, (byte)0xb0, (byte)0x92, (byte)0x38, (byte)0x3d,
- (byte)0x4a, (byte)0x02, (byte)0x26, (byte)0x45, (byte)0xbf, (byte)0xfa, (byte)0x34,
- (byte)0x6a, (byte)0x34, (byte)0x85, (byte)0x8c, (byte)0x94, (byte)0x20, (byte)0x95,
- (byte)0xcf, (byte)0xca, (byte)0x75, (byte)0x3e, (byte)0xeb, (byte)0x27, (byte)0x02,
- (byte)0x4f, (byte)0xbe, (byte)0x64, (byte)0xc0, (byte)0x54, (byte)0x77, (byte)0xda,
- (byte)0xfd, (byte)0x3e, (byte)0x75, (byte)0x36, (byte)0xec, (byte)0x99, (byte)0x4f,
- (byte)0xc4, (byte)0x56, (byte)0xff, (byte)0x45, (byte)0x61, (byte)0xa8, (byte)0xa8,
- (byte)0x41, (byte)0xe4, (byte)0x42, (byte)0x71, (byte)0x7a, (byte)0x8c, (byte)0x84,
- (byte)0xc2, (byte)0x02, (byte)0x40, (byte)0x0b, (byte)0x3d, (byte)0x42, (byte)0xe0,
- (byte)0x8b, (byte)0x22, (byte)0xf7, (byte)0x4c, (byte)0xa3, (byte)0xbb, (byte)0xd8,
- (byte)0x8f, (byte)0x45, (byte)0xa2, (byte)0x55, (byte)0xc7, (byte)0xd0, (byte)0x6a,
- (byte)0x25, (byte)0xbf, (byte)0xda, (byte)0x54, (byte)0x57, (byte)0x14, (byte)0x91,
- (byte)0x0c, (byte)0x09, (byte)0x0b, (byte)0x9a, (byte)0x50, (byte)0xca, (byte)0xe6,
- (byte)0x9e, (byte)0x28, (byte)0xc3, (byte)0x78, (byte)0x39, (byte)0x10, (byte)0x06,
- (byte)0x02, (byte)0x96, (byte)0x10, (byte)0x1a, (byte)0xd2, (byte)0x4b, (byte)0x7b,
- (byte)0x6c, (byte)0x72, (byte)0x9e, (byte)0x1e, (byte)0xac, (byte)0xd2, (byte)0xc1,
- (byte)0x02, (byte)0x41, (byte)0x00, (byte)0xde, (byte)0x27, (byte)0xbd, (byte)0x43,
- (byte)0xa4, (byte)0xbd, (byte)0x95, (byte)0x14, (byte)0x2e, (byte)0x1c, (byte)0xa0,
- (byte)0x74, (byte)0xa5, (byte)0x3e, (byte)0xfa, (byte)0xf9, (byte)0x15, (byte)0xb2,
- (byte)0x29, (byte)0x6a, (byte)0x2a, (byte)0x42, (byte)0x94, (byte)0x5a, (byte)0xf2,
- (byte)0x81, (byte)0xf3, (byte)0xe1, (byte)0x76, (byte)0x49, (byte)0x11, (byte)0x9d,
- (byte)0x18, (byte)0xc5, (byte)0xeb, (byte)0xb6, (byte)0xbc, (byte)0x81, (byte)0x3a,
- (byte)0x14, (byte)0x9c, (byte)0x41, (byte)0x01, (byte)0x58, (byte)0x56, (byte)0xa9,
- (byte)0x9b, (byte)0x73, (byte)0x2f, (byte)0xd9, (byte)0xa8, (byte)0x8e, (byte)0xc4,
- (byte)0x48, (byte)0x69, (byte)0x35, (byte)0xe6, (byte)0xf4, (byte)0x73, (byte)0x2f,
- (byte)0xf9, (byte)0x12, (byte)0x12, (byte)0x71, (byte)0x02, (byte)0x41, (byte)0x00,
- (byte)0xc4, (byte)0x32, (byte)0x81, (byte)0x5d, (byte)0x19, (byte)0x54, (byte)0x2c,
- (byte)0x29, (byte)0x5a, (byte)0x9f, (byte)0x36, (byte)0x4c, (byte)0x6f, (byte)0x2d,
- (byte)0xfd, (byte)0x62, (byte)0x0e, (byte)0xe6, (byte)0x37, (byte)0xc2, (byte)0xf6,
- (byte)0x69, (byte)0x64, (byte)0xf9, (byte)0x3a, (byte)0xcc, (byte)0xb2, (byte)0x63,
- (byte)0x2f, (byte)0xa9, (byte)0xfe, (byte)0x7e, (byte)0x8b, (byte)0x2d, (byte)0x69,
- (byte)0x13, (byte)0xe5, (byte)0x61, (byte)0x58, (byte)0xb7, (byte)0xfa, (byte)0x55,
- (byte)0x74, (byte)0x2c, (byte)0xe8, (byte)0xa1, (byte)0xac, (byte)0xc3, (byte)0xdd,
- (byte)0x5b, (byte)0x62, (byte)0xae, (byte)0x0a, (byte)0x27, (byte)0xce, (byte)0xb0,
- (byte)0xf2, (byte)0x81, (byte)0x5f, (byte)0x9a, (byte)0x6f, (byte)0x5f, (byte)0x3f,
- (byte)0x5d, (byte)0x02, (byte)0x41, (byte)0x00, (byte)0x92, (byte)0x42, (byte)0xff,
- (byte)0xac, (byte)0xe5, (byte)0x6d, (byte)0x9c, (byte)0x15, (byte)0x29, (byte)0x36,
- (byte)0xd7, (byte)0xbd, (byte)0x74, (byte)0x7e, (byte)0x3e, (byte)0xa6, (byte)0x77,
- (byte)0xce, (byte)0x50, (byte)0xce, (byte)0x00, (byte)0xfc, (byte)0xcc, (byte)0xc8,
- (byte)0x04, (byte)0x19, (byte)0xe3, (byte)0x03, (byte)0x71, (byte)0xe9, (byte)0x31,
- (byte)0x9b, (byte)0x88, (byte)0x8f, (byte)0xe6, (byte)0x5c, (byte)0xed, (byte)0x46,
- (byte)0xf7, (byte)0x82, (byte)0x52, (byte)0x4d, (byte)0xca, (byte)0x20, (byte)0xeb,
- (byte)0x0d, (byte)0xc7, (byte)0xb6, (byte)0xd2, (byte)0xae, (byte)0x2e, (byte)0xf7,
- (byte)0xaf, (byte)0xeb, (byte)0x2c, (byte)0xb9, (byte)0xbc, (byte)0x50, (byte)0xfc,
- (byte)0xf5, (byte)0x7c, (byte)0xba, (byte)0x95, (byte)0x41, (byte)0x02, (byte)0x40,
- (byte)0x54, (byte)0xf8, (byte)0x46, (byte)0x9c, (byte)0x6a, (byte)0x5e, (byte)0xd0,
- (byte)0xed, (byte)0x6c, (byte)0x08, (byte)0xed, (byte)0xfc, (byte)0x36, (byte)0x5e,
- (byte)0x65, (byte)0x91, (byte)0x75, (byte)0x40, (byte)0x71, (byte)0x3f, (byte)0xe7,
- (byte)0x76, (byte)0x07, (byte)0xbc, (byte)0x04, (byte)0xa2, (byte)0x28, (byte)0x53,
- (byte)0xda, (byte)0x8d, (byte)0xb5, (byte)0xe1, (byte)0x5a, (byte)0x27, (byte)0x65,
- (byte)0x8d, (byte)0xaf, (byte)0x56, (byte)0xf4, (byte)0x94, (byte)0x61, (byte)0x3f,
- (byte)0x67, (byte)0x1c, (byte)0x17, (byte)0xf8, (byte)0x05, (byte)0x19, (byte)0xa2,
- (byte)0xa1, (byte)0x74, (byte)0x60, (byte)0x49, (byte)0x97, (byte)0xa9, (byte)0xe5,
- (byte)0x6a, (byte)0x71, (byte)0x6b, (byte)0x55, (byte)0x38, (byte)0x0c, (byte)0xb9,
- (byte)0x25, (byte)0x02, (byte)0x41, (byte)0x00, (byte)0xae, (byte)0xf2, (byte)0xa8,
- (byte)0x6d, (byte)0x1d, (byte)0x35, (byte)0x38, (byte)0x73, (byte)0x98, (byte)0x15,
- (byte)0xc7, (byte)0x15, (byte)0x02, (byte)0x2f, (byte)0x29, (byte)0x5d, (byte)0x18,
- (byte)0x4b, (byte)0x7d, (byte)0xb2, (byte)0x59, (byte)0xbe, (byte)0x5a, (byte)0xc7,
- (byte)0x72, (byte)0xd0, (byte)0x80, (byte)0xd8, (byte)0x77, (byte)0xa1, (byte)0x7f,
- (byte)0xb2, (byte)0x35, (byte)0x0d, (byte)0x78, (byte)0x92, (byte)0x91, (byte)0x35,
- (byte)0x47, (byte)0xeb, (byte)0x4b, (byte)0x00, (byte)0x59, (byte)0xb4, (byte)0xc4,
- (byte)0x2c, (byte)0x29, (byte)0xe7, (byte)0x39, (byte)0x9d, (byte)0x48, (byte)0x8b,
- (byte)0x4f, (byte)0x46, (byte)0xe6, (byte)0xce, (byte)0xd3, (byte)0x6c, (byte)0x84,
- (byte)0x9b, (byte)0xd2, (byte)0x10, (byte)0xb0, (byte)0xe1
- };
-
- /*
- * The same key in PEM format.
- * The DER version of this key was created using
- *
- * openssl pkcs8 -topk8 -nocrypt -in key1.pem
- * -inform PEM -out key1.der -outform DER
- *
- * -----BEGIN RSA PRIVATE KEY-----
- * Proc-Type: 4,ENCRYPTED
- * DEK-Info: DES-EDE3-CBC,69E26FCC3A7F136E
- *
- * YKiLXOwf2teog4IoOvbbROy9vqp0EMt1KF9eNKeKFCWGCS4RFATaAGjKrdA26bOV
- * MBdyB4V7qaxLC8/UwLlzFLpprouIfGqrEoR/NT0eKQ+4Pl25GlMvlPaR0pATBLZ2
- * OEaB3zcNygOQ02Jdrmw2+CS9qVtGGXjn6Qp6TVFm6edNCoOVZODLP9kkzPLn8Mkm
- * /isgsprwMELuth8Y5BC0brI5XYdMqZFI5dLz4wzVH81wBYbRmJqR7yOE1pzAJS9I
- * gJ5YvcP7pSmoA2SHVN4v4qolM+GAM9YIp2bwEyWFRjbriNlF1yM+HflGMEZ1HNpZ
- * FSFFA3G8EIH9ogbZ3j+7EujrndJC7GIibwiu5rd3eIHtcwrWprp+wEoPc/vM8OpR
- * so9ms7iQYV6faYCWK4yeCfErYw7t+AhGqfLiqHO6bO2XAYJcD28RYV9gXmugZOhT
- * 9471MOw94HWF5tBVjgIkyNBcbRyMF9iyQKafbkHYpmxaB4s2EqQr1SNZl3SLEwhX
- * MEGy3/tyveuMLAvdTlSDZbt6memWoXXEX4Ep/q6r0ErCTY31awdP/XaJcJBGb9ni
- * Iai8DICaG1v4bUuBVgaiacZlgw1O4Hhj8D2DWfVZsgpx5y8tBRM2lGWvyzEi5n2F
- * PiR2UlT0DjCD1ObjCpWJ5insX/w8dXSHGZLLb9ccGRUrw/+5Bptn+AoEfdP+8S3j
- * UdMdxl6qt2gneCYu1Lr3cQ+qKPqikQty2UQ6Yp8dJkheLJ2Tr+rnaytOCp2dAT9K
- * KXTimIcXV+ftvUMbDPXYu4LJBldr2VokD+k3QbHDgFnfHIiNkwiPzA==
- * -----END RSA PRIVATE KEY-----
- */
-
- /*
- Certificate:
- Data:
- Version: 3 (0x2)
- Serial Number: 1 (0x1)
- Signature Algorithm: sha1WithRSAEncryption
- Issuer: C=AN, ST=Android, O=Android, OU=Android, CN=Android/emailAddress=android@android.com
- Validity
- Not Before: Mar 20 17:00:40 2009 GMT
- Not After : Mar 20 17:00:40 2010 GMT
- Subject: C=AN, ST=Android, L=Android, O=Android, OU=Android, CN=Android/emailAddress=android@android.com
- Subject Public Key Info:
- Public Key Algorithm: rsaEncryption
- RSA Public Key: (1024 bit)
- Modulus (1024 bit):
- 00:d0:44:5a:c4:76:ef:ae:ff:99:5b:c3:37:c1:09:
- 33:c1:97:e5:64:7a:a9:7e:98:4b:3a:a3:33:d0:5c:
- c7:56:ac:d8:42:e8:4a:ac:9c:d9:8f:89:84:c8:46:
- 95:ce:22:f7:6a:09:de:91:47:9c:38:23:a5:4a:fc:
- 08:af:5a:b4:6e:39:8e:e9:f5:0e:46:00:69:e1:e5:
- cc:4c:81:b6:82:7b:56:fb:f4:dc:04:ff:61:e2:7e:
- 5f:e2:f9:97:53:93:d4:69:9b:ba:79:20:cd:1e:3e:
- d5:9a:44:95:7c:cf:c1:51:f2:22:fc:ec:cc:66:18:
- 74:60:2a:a2:be:06:c2:9e:8d
- Exponent: 65537 (0x10001)
- X509v3 extensions:
- X509v3 Basic Constraints:
- CA:FALSE
- Netscape Comment:
- OpenSSL Generated Certificate
- X509v3 Subject Key Identifier:
- 95:3E:C3:46:69:52:78:08:05:46:B9:00:69:E5:E7:A7:99:E3:C4:67
- X509v3 Authority Key Identifier:
- keyid:E7:9B:7D:90:29:EA:90:0B:7F:08:41:76:4E:41:23:E8:43:2C:A9:03
-
- Signature Algorithm: sha1WithRSAEncryption
- a3:5b:30:f5:28:3f:87:f6:1b:36:6a:22:6d:66:48:fa:cb:ee:
- 4c:04:cf:11:14:e2:1f:b5:68:0c:e7:61:0e:bc:d3:69:19:02:
- 8b:d5:d3:05:4a:c8:29:e8:e3:d0:e9:32:ad:6c:7d:9c:c4:46:
- 6c:f9:66:e6:64:60:47:6b:ef:8e:c8:1c:67:5a:5a:cf:73:a3:
- 7e:9d:6e:89:0c:67:99:17:3d:b2:b8:8e:41:95:9c:84:95:bf:
- 57:95:24:22:8f:19:12:c1:fd:23:45:75:7f:4f:61:06:e3:9f:
- 05:dc:e7:29:9a:6b:17:e1:e1:37:d5:8b:ba:b4:d0:8a:3c:dd:
- 3f:6a
- */
- String certificate2 = "-----BEGIN CERTIFICATE-----\n"
- + "MIIC9jCCAl+gAwIBAgIBATANBgkqhkiG9w0BAQUFADB5MQswCQYDVQQGEwJBTjEQ\n"
- + "MA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5k\n"
- + "cm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBh\n"
- + "bmRyb2lkLmNvbTAeFw0wOTAzMjAxNzAwNDBaFw0xMDAzMjAxNzAwNDBaMIGLMQsw\n"
- + "CQYDVQQGEwJBTjEQMA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEBxMHQW5kcm9pZDEQ\n"
- + "MA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5k\n"
- + "cm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTCBnzANBgkq\n"
- + "hkiG9w0BAQEFAAOBjQAwgYkCgYEA0ERaxHbvrv+ZW8M3wQkzwZflZHqpfphLOqMz\n"
- + "0FzHVqzYQuhKrJzZj4mEyEaVziL3agnekUecOCOlSvwIr1q0bjmO6fUORgBp4eXM\n"
- + "TIG2gntW+/TcBP9h4n5f4vmXU5PUaZu6eSDNHj7VmkSVfM/BUfIi/OzMZhh0YCqi\n"
- + "vgbCno0CAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgBhvhCAQ0EHxYdT3BlblNT\n"
- + "TCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFJU+w0ZpUngIBUa5AGnl\n"
- + "56eZ48RnMB8GA1UdIwQYMBaAFOebfZAp6pALfwhBdk5BI+hDLKkDMA0GCSqGSIb3\n"
- + "DQEBBQUAA4GBAKNbMPUoP4f2GzZqIm1mSPrL7kwEzxEU4h+1aAznYQ6802kZAovV\n"
- + "0wVKyCno49DpMq1sfZzERmz5ZuZkYEdr747IHGdaWs9zo36dbokMZ5kXPbK4jkGV\n"
- + "nISVv1eVJCKPGRLB/SNFdX9PYQbjnwXc5ymaaxfh4TfVi7q00Io83T9q\n\n"
- + "-----END CERTIFICATE-----";
-
- ByteArrayInputStream certArray2 = new ByteArrayInputStream(certificate2
- .getBytes());
-
- /*
- * The key in DER format.
- * Below is the same key in PEM format as reference
- */
- byte[] key2Bytes = new byte[] {
- (byte)0x30, (byte)0x82, (byte)0x02, (byte)0x75, (byte)0x02, (byte)0x01, (byte)0x00,
- (byte)0x30, (byte)0x0d, (byte)0x06, (byte)0x09, (byte)0x2a, (byte)0x86, (byte)0x48,
- (byte)0x86, (byte)0xf7, (byte)0x0d, (byte)0x01, (byte)0x01, (byte)0x01, (byte)0x05,
- (byte)0x00, (byte)0x04, (byte)0x82, (byte)0x02, (byte)0x5f, (byte)0x30, (byte)0x82,
- (byte)0x02, (byte)0x5b, (byte)0x02, (byte)0x01, (byte)0x00, (byte)0x02, (byte)0x81,
- (byte)0x81, (byte)0x00, (byte)0xd0, (byte)0x44, (byte)0x5a, (byte)0xc4, (byte)0x76,
- (byte)0xef, (byte)0xae, (byte)0xff, (byte)0x99, (byte)0x5b, (byte)0xc3, (byte)0x37,
- (byte)0xc1, (byte)0x09, (byte)0x33, (byte)0xc1, (byte)0x97, (byte)0xe5, (byte)0x64,
- (byte)0x7a, (byte)0xa9, (byte)0x7e, (byte)0x98, (byte)0x4b, (byte)0x3a, (byte)0xa3,
- (byte)0x33, (byte)0xd0, (byte)0x5c, (byte)0xc7, (byte)0x56, (byte)0xac, (byte)0xd8,
- (byte)0x42, (byte)0xe8, (byte)0x4a, (byte)0xac, (byte)0x9c, (byte)0xd9, (byte)0x8f,
- (byte)0x89, (byte)0x84, (byte)0xc8, (byte)0x46, (byte)0x95, (byte)0xce, (byte)0x22,
- (byte)0xf7, (byte)0x6a, (byte)0x09, (byte)0xde, (byte)0x91, (byte)0x47, (byte)0x9c,
- (byte)0x38, (byte)0x23, (byte)0xa5, (byte)0x4a, (byte)0xfc, (byte)0x08, (byte)0xaf,
- (byte)0x5a, (byte)0xb4, (byte)0x6e, (byte)0x39, (byte)0x8e, (byte)0xe9, (byte)0xf5,
- (byte)0x0e, (byte)0x46, (byte)0x00, (byte)0x69, (byte)0xe1, (byte)0xe5, (byte)0xcc,
- (byte)0x4c, (byte)0x81, (byte)0xb6, (byte)0x82, (byte)0x7b, (byte)0x56, (byte)0xfb,
- (byte)0xf4, (byte)0xdc, (byte)0x04, (byte)0xff, (byte)0x61, (byte)0xe2, (byte)0x7e,
- (byte)0x5f, (byte)0xe2, (byte)0xf9, (byte)0x97, (byte)0x53, (byte)0x93, (byte)0xd4,
- (byte)0x69, (byte)0x9b, (byte)0xba, (byte)0x79, (byte)0x20, (byte)0xcd, (byte)0x1e,
- (byte)0x3e, (byte)0xd5, (byte)0x9a, (byte)0x44, (byte)0x95, (byte)0x7c, (byte)0xcf,
- (byte)0xc1, (byte)0x51, (byte)0xf2, (byte)0x22, (byte)0xfc, (byte)0xec, (byte)0xcc,
- (byte)0x66, (byte)0x18, (byte)0x74, (byte)0x60, (byte)0x2a, (byte)0xa2, (byte)0xbe,
- (byte)0x06, (byte)0xc2, (byte)0x9e, (byte)0x8d, (byte)0x02, (byte)0x03, (byte)0x01,
- (byte)0x00, (byte)0x01, (byte)0x02, (byte)0x81, (byte)0x80, (byte)0x06, (byte)0x41,
- (byte)0xd7, (byte)0x7c, (byte)0x49, (byte)0x9a, (byte)0x7f, (byte)0xe6, (byte)0x7c,
- (byte)0x04, (byte)0x0e, (byte)0xc4, (byte)0x71, (byte)0x0f, (byte)0x46, (byte)0xb7,
- (byte)0xcd, (byte)0x49, (byte)0x7e, (byte)0x10, (byte)0x55, (byte)0x61, (byte)0x51,
- (byte)0x50, (byte)0x09, (byte)0x4d, (byte)0xf7, (byte)0xf3, (byte)0x8d, (byte)0xa6,
- (byte)0x0b, (byte)0x8b, (byte)0x9b, (byte)0xdf, (byte)0xbe, (byte)0xbc, (byte)0xe7,
- (byte)0x9c, (byte)0xba, (byte)0xc8, (byte)0x9e, (byte)0x38, (byte)0x18, (byte)0x10,
- (byte)0x4e, (byte)0xd5, (byte)0xe7, (byte)0xa5, (byte)0x09, (byte)0x51, (byte)0x8c,
- (byte)0x97, (byte)0x4e, (byte)0xd0, (byte)0x79, (byte)0xbb, (byte)0x50, (byte)0x6f,
- (byte)0x05, (byte)0x4d, (byte)0x79, (byte)0x7f, (byte)0x3f, (byte)0x26, (byte)0x76,
- (byte)0xc1, (byte)0xcc, (byte)0x40, (byte)0x0f, (byte)0xde, (byte)0x42, (byte)0x5d,
- (byte)0xc1, (byte)0x5f, (byte)0x70, (byte)0x46, (byte)0x70, (byte)0x8d, (byte)0xff,
- (byte)0x26, (byte)0x35, (byte)0x75, (byte)0x9a, (byte)0x97, (byte)0xd2, (byte)0x74,
- (byte)0x53, (byte)0x11, (byte)0x2b, (byte)0xc1, (byte)0x76, (byte)0x9c, (byte)0x9f,
- (byte)0x93, (byte)0xaa, (byte)0xa8, (byte)0x41, (byte)0x23, (byte)0x9a, (byte)0x04,
- (byte)0x11, (byte)0x6e, (byte)0x56, (byte)0xea, (byte)0xf5, (byte)0xd6, (byte)0x1d,
- (byte)0x49, (byte)0x2a, (byte)0x83, (byte)0x49, (byte)0x7d, (byte)0xb7, (byte)0xd1,
- (byte)0xe6, (byte)0x8d, (byte)0x93, (byte)0x1a, (byte)0x81, (byte)0x8e, (byte)0xc2,
- (byte)0xb9, (byte)0xbf, (byte)0xfd, (byte)0x00, (byte)0xe2, (byte)0xb5, (byte)0x01,
- (byte)0x02, (byte)0x41, (byte)0x00, (byte)0xea, (byte)0xce, (byte)0xc6, (byte)0x11,
- (byte)0x1e, (byte)0xf6, (byte)0xcf, (byte)0x3a, (byte)0x8c, (byte)0xe7, (byte)0x80,
- (byte)0x16, (byte)0x8f, (byte)0x1d, (byte)0xeb, (byte)0xa2, (byte)0xd2, (byte)0x23,
- (byte)0x9e, (byte)0xf9, (byte)0xf1, (byte)0x14, (byte)0x16, (byte)0xc8, (byte)0x87,
- (byte)0xf2, (byte)0x17, (byte)0xdf, (byte)0xc6, (byte)0xe4, (byte)0x1c, (byte)0x74,
- (byte)0x74, (byte)0xb0, (byte)0xbb, (byte)0x40, (byte)0xeb, (byte)0xa6, (byte)0xb2,
- (byte)0x5b, (byte)0x6d, (byte)0xf5, (byte)0x9a, (byte)0x85, (byte)0xf1, (byte)0x73,
- (byte)0x84, (byte)0xec, (byte)0xdb, (byte)0x9b, (byte)0xf9, (byte)0xf8, (byte)0x3d,
- (byte)0xba, (byte)0xeb, (byte)0xd7, (byte)0x6c, (byte)0x45, (byte)0x7b, (byte)0xca,
- (byte)0x12, (byte)0x67, (byte)0x5f, (byte)0xcd, (byte)0x02, (byte)0x41, (byte)0x00,
- (byte)0xe3, (byte)0x10, (byte)0x5b, (byte)0xd0, (byte)0xad, (byte)0x59, (byte)0x90,
- (byte)0x18, (byte)0x17, (byte)0xdc, (byte)0x68, (byte)0xd4, (byte)0x75, (byte)0x55,
- (byte)0xab, (byte)0x7d, (byte)0xd1, (byte)0xb5, (byte)0x5a, (byte)0xc4, (byte)0xb0,
- (byte)0x2d, (byte)0xa9, (byte)0xd1, (byte)0x6f, (byte)0xe9, (byte)0x21, (byte)0x4a,
- (byte)0x27, (byte)0xc4, (byte)0x98, (byte)0x89, (byte)0xfa, (byte)0x65, (byte)0xb6,
- (byte)0x10, (byte)0x5d, (byte)0x66, (byte)0xdd, (byte)0x17, (byte)0xb3, (byte)0xf3,
- (byte)0xd3, (byte)0xe3, (byte)0xa0, (byte)0x1a, (byte)0x93, (byte)0xe4, (byte)0xfb,
- (byte)0x88, (byte)0xa7, (byte)0x3b, (byte)0x97, (byte)0x1b, (byte)0xf1, (byte)0x08,
- (byte)0x0c, (byte)0x66, (byte)0xd0, (byte)0x86, (byte)0x5e, (byte)0x39, (byte)0xf9,
- (byte)0xc1, (byte)0x02, (byte)0x40, (byte)0x24, (byte)0x7c, (byte)0xcd, (byte)0x3a,
- (byte)0x8b, (byte)0xdd, (byte)0x3e, (byte)0x86, (byte)0x92, (byte)0xae, (byte)0xc6,
- (byte)0xb0, (byte)0xba, (byte)0xbc, (byte)0xa3, (byte)0x89, (byte)0x41, (byte)0xae,
- (byte)0x57, (byte)0x5d, (byte)0xef, (byte)0xa0, (byte)0x77, (byte)0x89, (byte)0xe1,
- (byte)0xd6, (byte)0x34, (byte)0xef, (byte)0x89, (byte)0x30, (byte)0x99, (byte)0x5b,
- (byte)0x5f, (byte)0x66, (byte)0xb7, (byte)0x32, (byte)0x77, (byte)0x6c, (byte)0x07,
- (byte)0xfb, (byte)0x3d, (byte)0x33, (byte)0x15, (byte)0x38, (byte)0x0b, (byte)0x35,
- (byte)0x30, (byte)0x4a, (byte)0xbe, (byte)0x35, (byte)0x96, (byte)0xba, (byte)0x84,
- (byte)0x9d, (byte)0x2f, (byte)0x58, (byte)0xe2, (byte)0x72, (byte)0x49, (byte)0xb2,
- (byte)0x34, (byte)0xf9, (byte)0xeb, (byte)0x61, (byte)0x02, (byte)0x40, (byte)0x2a,
- (byte)0xd4, (byte)0x89, (byte)0x1d, (byte)0x21, (byte)0xb5, (byte)0xc5, (byte)0x32,
- (byte)0x66, (byte)0x3d, (byte)0xd3, (byte)0x20, (byte)0x50, (byte)0x49, (byte)0xaa,
- (byte)0xa1, (byte)0x7f, (byte)0x0f, (byte)0x20, (byte)0x61, (byte)0xfd, (byte)0x81,
- (byte)0x7f, (byte)0x88, (byte)0xdb, (byte)0xfd, (byte)0x33, (byte)0xa4, (byte)0x53,
- (byte)0x40, (byte)0x08, (byte)0x2d, (byte)0xee, (byte)0xa7, (byte)0x84, (byte)0xe2,
- (byte)0x2d, (byte)0x5c, (byte)0x1b, (byte)0xd4, (byte)0x3e, (byte)0xc3, (byte)0x7d,
- (byte)0x72, (byte)0x70, (byte)0x5e, (byte)0xd3, (byte)0x0a, (byte)0xdc, (byte)0x4f,
- (byte)0x78, (byte)0x8c, (byte)0x0b, (byte)0x02, (byte)0xe0, (byte)0x42, (byte)0x4e,
- (byte)0x64, (byte)0x8e, (byte)0x6c, (byte)0xea, (byte)0x15, (byte)0x31, (byte)0x81,
- (byte)0x02, (byte)0x40, (byte)0x57, (byte)0x72, (byte)0xb9, (byte)0x78, (byte)0xc0,
- (byte)0x1f, (byte)0x5b, (byte)0x1d, (byte)0xb2, (byte)0xcf, (byte)0x94, (byte)0x42,
- (byte)0xed, (byte)0xbd, (byte)0xe7, (byte)0xaa, (byte)0x14, (byte)0x56, (byte)0xd0,
- (byte)0x94, (byte)0x25, (byte)0x30, (byte)0x87, (byte)0x35, (byte)0x82, (byte)0xa0,
- (byte)0x42, (byte)0xb5, (byte)0x7f, (byte)0x66, (byte)0x77, (byte)0xb0, (byte)0x13,
- (byte)0xbe, (byte)0x57, (byte)0x06, (byte)0x7e, (byte)0x50, (byte)0x67, (byte)0x13,
- (byte)0xa7, (byte)0x09, (byte)0xac, (byte)0xd6, (byte)0xbf, (byte)0x22, (byte)0x74,
- (byte)0x6b, (byte)0x37, (byte)0x92, (byte)0x2b, (byte)0x91, (byte)0xbd, (byte)0x0a,
- (byte)0xd8, (byte)0x0f, (byte)0x8d, (byte)0x86, (byte)0x4b, (byte)0x20, (byte)0x5e,
- (byte)0x50, (byte)0x60, (byte)0x80
- };
-
- /*
- * The same key in PEM format.
- * The DER version of this key was created using
- *
- * openssl pkcs8 -topk8 -nocrypt -in key1.pem
- * -inform PEM -out key1.der -outform DER
- *
- * -----BEGIN RSA PRIVATE KEY-----
- * Proc-Type: 4,ENCRYPTED
- * DEK-Info: DES-EDE3-CBC,370723FFDC1B1CFA
- *
- * KJ20ODBEQujoOpnzNfHNoo5DF/qENhw9IaApChGMj+WhqYuFfKfPQKuRli8sJSEk
- * uoPmEqjJndHz5M5bI7wVxiafv/Up4+SaNKhn/vu6xjx/senJMX8HMUchqfvn0eCd
- * 31NHQeNbQ67O73xGIdltLzwTRsavTu/hwhnnJxiXzXnYtI5HTZUaRbVJQNpdlkNW
- * H91u70lwlT8W2MATBhl3R3wIbRHQG1I0RQX12O04gMfK1PBl9d/tnFOi4ESfth1W
- * e06XV0U12g06V5/UUuicJANvgyf0Pix0xxPr2tqibWeGpFwCvJpNHl4L3tUocydF
- * HYoUKx/r3VSmesnZ1zUMsuO2zXOuLLcwCSFN+73GBLWocCxBvag6HFvCemy5Tuhs
- * 9MhfF+5lKER/9Ama/e7C61usaoUhR1OvpGWMfjewrFLCsyWlInscoZ1ad5YtcWGx
- * MM7+BsTnK00fcXZuPHTPsiwQ0fMVeNM2a/e65aIivfzzHmb6gqUigNpfNYcqQsJJ
- * Wwoc5hXVO92vugdHOHOiAUpfZZgNDZwgCTluMuI+KJ0QCb0dhF5w/TDA8z+vRwmW
- * sz5WrA4F+T3LfwwLQfxJyHTnbAu38VlMMZP98iIobOX3AAkBw4+kTOCEedvmKt0f
- * s7iSKrnnV6AyzRPEJUWknMF8xNFH7HDqkZf4Mv8cMM6e45K4kBGd17d3tcEFi2An
- * 5l6S9hHtoyMhHjnAcyuHJbD9rGRgyOlbhSYTcbX/gKiECZj0kf8xHi20qntO3c+p
- * jdpp97fIMnQTl5IDNxOy5h9MDLs/SYAR7iyF19RkIGc=
- * -----END RSA PRIVATE KEY-----
- */
-
- /*
- Certificate:
- Data:
- Version: 3 (0x2)
- Serial Number: 2 (0x2)
- Signature Algorithm: sha1WithRSAEncryption
- Issuer: C=AN, ST=Android, O=Android, OU=Android, CN=Android/emailAddress=android@android.com
- Validity
- Not Before: Mar 20 17:02:32 2009 GMT
- Not After : Mar 20 17:02:32 2010 GMT
- Subject: C=AN, ST=Android, L=Android, O=Android, OU=Android, CN=Android/emailAddress=android@android.com
- Subject Public Key Info:
- Public Key Algorithm: rsaEncryption
- RSA Public Key: (1024 bit)
- Modulus (1024 bit):
- 00:b4:c5:ed:df:30:42:6d:8b:af:4b:e4:9c:13:5e:
- 83:23:cd:2f:ce:34:e2:43:d7:6c:72:bb:03:b3:b9:
- 24:02:e0:cc:b5:8d:d6:92:41:04:2b:5c:94:b2:c3:
- 9c:9d:56:f0:99:bc:0f:81:af:eb:54:ed:80:a6:a0:
- c7:c2:43:05:04:7c:9c:7e:07:03:10:b9:bd:c5:16:
- cf:19:dd:e3:4f:73:83:72:c5:66:e4:5b:14:c4:96:
- d1:e3:24:0b:b6:d4:f7:84:2e:b1:e7:93:02:9d:f5:
- da:aa:c1:d9:cc:5e:36:e9:8f:bf:8b:da:a7:45:82:
- f2:b0:f5:a7:e4:e1:80:a3:17
- Exponent: 65537 (0x10001)
- X509v3 extensions:
- X509v3 Basic Constraints:
- CA:FALSE
- Netscape Comment:
- OpenSSL Generated Certificate
- X509v3 Subject Key Identifier:
- 3B:5B:3D:DB:45:F5:8F:58:70:0B:FC:70:3E:31:2B:43:63:A9:FE:2B
- X509v3 Authority Key Identifier:
- keyid:E7:9B:7D:90:29:EA:90:0B:7F:08:41:76:4E:41:23:E8:43:2C:A9:03
-
- Signature Algorithm: sha1WithRSAEncryption
- 1c:7f:93:1c:59:21:88:15:45:4b:e0:9c:78:3a:88:3e:55:19:
- 86:31:e8:53:3d:74:e2:4a:34:9f:92:17:4e:13:46:92:54:f8:
- 43:eb:5e:03:4f:14:51:61:d2:04:b8:04:5a:31:eb:14:6a:18:
- b0:20:03:92:0c:7f:07:c4:1b:f9:9e:7f:5f:ec:03:7a:c8:e3:
- df:d3:94:6e:68:8a:3a:3d:e4:61:f3:e0:87:5d:40:d8:cb:99:
- 4d:9a:7b:bc:95:7c:d2:9d:b7:04:9a:9a:63:89:cd:39:ec:32:
- 60:0a:97:da:e9:50:a5:73:4a:a2:aa:9c:9b:a8:7f:5a:20:d6:
- 48:bd
- */
- String certificate3 = "-----BEGIN CERTIFICATE-----\n"
- + "MIIC9jCCAl+gAwIBAgIBAjANBgkqhkiG9w0BAQUFADB5MQswCQYDVQQGEwJBTjEQ\n"
- + "MA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5k\n"
- + "cm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBh\n"
- + "bmRyb2lkLmNvbTAeFw0wOTAzMjAxNzAyMzJaFw0xMDAzMjAxNzAyMzJaMIGLMQsw\n"
- + "CQYDVQQGEwJBTjEQMA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEBxMHQW5kcm9pZDEQ\n"
- + "MA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5k\n"
- + "cm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTCBnzANBgkq\n"
- + "hkiG9w0BAQEFAAOBjQAwgYkCgYEAtMXt3zBCbYuvS+ScE16DI80vzjTiQ9dscrsD\n"
- + "s7kkAuDMtY3WkkEEK1yUssOcnVbwmbwPga/rVO2ApqDHwkMFBHycfgcDELm9xRbP\n"
- + "Gd3jT3ODcsVm5FsUxJbR4yQLttT3hC6x55MCnfXaqsHZzF426Y+/i9qnRYLysPWn\n"
- + "5OGAoxcCAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgBhvhCAQ0EHxYdT3BlblNT\n"
- + "TCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFDtbPdtF9Y9YcAv8cD4x\n"
- + "K0Njqf4rMB8GA1UdIwQYMBaAFOebfZAp6pALfwhBdk5BI+hDLKkDMA0GCSqGSIb3\n"
- + "DQEBBQUAA4GBABx/kxxZIYgVRUvgnHg6iD5VGYYx6FM9dOJKNJ+SF04TRpJU+EPr\n"
- + "XgNPFFFh0gS4BFox6xRqGLAgA5IMfwfEG/mef1/sA3rI49/TlG5oijo95GHz4Idd\n"
- + "QNjLmU2ae7yVfNKdtwSammOJzTnsMmAKl9rpUKVzSqKqnJuof1og1ki9\n"
- + "-----END CERTIFICATE-----";
-
- ByteArrayInputStream certArray3 = new ByteArrayInputStream(certificate3
- .getBytes());
-
- /*
- * The key in DER format.
- * Below is the same key in PEM format as reference
- */
- byte[] key3Bytes = new byte[] {
- (byte)0x30, (byte)0x82, (byte)0x02, (byte)0x76, (byte)0x02, (byte)0x01, (byte)0x00,
- (byte)0x30, (byte)0x0d, (byte)0x06, (byte)0x09, (byte)0x2a, (byte)0x86, (byte)0x48,
- (byte)0x86, (byte)0xf7, (byte)0x0d, (byte)0x01, (byte)0x01, (byte)0x01, (byte)0x05,
- (byte)0x00, (byte)0x04, (byte)0x82, (byte)0x02, (byte)0x60, (byte)0x30, (byte)0x82,
- (byte)0x02, (byte)0x5c, (byte)0x02, (byte)0x01, (byte)0x00, (byte)0x02, (byte)0x81,
- (byte)0x81, (byte)0x00, (byte)0xb4, (byte)0xc5, (byte)0xed, (byte)0xdf, (byte)0x30,
- (byte)0x42, (byte)0x6d, (byte)0x8b, (byte)0xaf, (byte)0x4b, (byte)0xe4, (byte)0x9c,
- (byte)0x13, (byte)0x5e, (byte)0x83, (byte)0x23, (byte)0xcd, (byte)0x2f, (byte)0xce,
- (byte)0x34, (byte)0xe2, (byte)0x43, (byte)0xd7, (byte)0x6c, (byte)0x72, (byte)0xbb,
- (byte)0x03, (byte)0xb3, (byte)0xb9, (byte)0x24, (byte)0x02, (byte)0xe0, (byte)0xcc,
- (byte)0xb5, (byte)0x8d, (byte)0xd6, (byte)0x92, (byte)0x41, (byte)0x04, (byte)0x2b,
- (byte)0x5c, (byte)0x94, (byte)0xb2, (byte)0xc3, (byte)0x9c, (byte)0x9d, (byte)0x56,
- (byte)0xf0, (byte)0x99, (byte)0xbc, (byte)0x0f, (byte)0x81, (byte)0xaf, (byte)0xeb,
- (byte)0x54, (byte)0xed, (byte)0x80, (byte)0xa6, (byte)0xa0, (byte)0xc7, (byte)0xc2,
- (byte)0x43, (byte)0x05, (byte)0x04, (byte)0x7c, (byte)0x9c, (byte)0x7e, (byte)0x07,
- (byte)0x03, (byte)0x10, (byte)0xb9, (byte)0xbd, (byte)0xc5, (byte)0x16, (byte)0xcf,
- (byte)0x19, (byte)0xdd, (byte)0xe3, (byte)0x4f, (byte)0x73, (byte)0x83, (byte)0x72,
- (byte)0xc5, (byte)0x66, (byte)0xe4, (byte)0x5b, (byte)0x14, (byte)0xc4, (byte)0x96,
- (byte)0xd1, (byte)0xe3, (byte)0x24, (byte)0x0b, (byte)0xb6, (byte)0xd4, (byte)0xf7,
- (byte)0x84, (byte)0x2e, (byte)0xb1, (byte)0xe7, (byte)0x93, (byte)0x02, (byte)0x9d,
- (byte)0xf5, (byte)0xda, (byte)0xaa, (byte)0xc1, (byte)0xd9, (byte)0xcc, (byte)0x5e,
- (byte)0x36, (byte)0xe9, (byte)0x8f, (byte)0xbf, (byte)0x8b, (byte)0xda, (byte)0xa7,
- (byte)0x45, (byte)0x82, (byte)0xf2, (byte)0xb0, (byte)0xf5, (byte)0xa7, (byte)0xe4,
- (byte)0xe1, (byte)0x80, (byte)0xa3, (byte)0x17, (byte)0x02, (byte)0x03, (byte)0x01,
- (byte)0x00, (byte)0x01, (byte)0x02, (byte)0x81, (byte)0x80, (byte)0x53, (byte)0xbc,
- (byte)0x1f, (byte)0x1c, (byte)0x34, (byte)0x09, (byte)0x81, (byte)0x1e, (byte)0xa3,
- (byte)0xfb, (byte)0x5e, (byte)0x90, (byte)0xa1, (byte)0x34, (byte)0x35, (byte)0x40,
- (byte)0x9f, (byte)0x29, (byte)0xd6, (byte)0xb5, (byte)0x8e, (byte)0x5d, (byte)0x68,
- (byte)0x6a, (byte)0xf6, (byte)0x96, (byte)0x03, (byte)0xf7, (byte)0xfa, (byte)0xf9,
- (byte)0x60, (byte)0x4f, (byte)0xea, (byte)0xe2, (byte)0xea, (byte)0x29, (byte)0x8b,
- (byte)0x23, (byte)0x8c, (byte)0x9f, (byte)0xdd, (byte)0x49, (byte)0x8f, (byte)0xa8,
- (byte)0xa6, (byte)0x62, (byte)0x07, (byte)0x44, (byte)0x79, (byte)0xa1, (byte)0xaf,
- (byte)0xf9, (byte)0x1d, (byte)0x98, (byte)0xbf, (byte)0x85, (byte)0x28, (byte)0x03,
- (byte)0x87, (byte)0x14, (byte)0x20, (byte)0xba, (byte)0xd4, (byte)0x96, (byte)0x61,
- (byte)0x2a, (byte)0xd0, (byte)0xaa, (byte)0x30, (byte)0x19, (byte)0x4b, (byte)0x40,
- (byte)0x35, (byte)0xb0, (byte)0x79, (byte)0x0b, (byte)0x7f, (byte)0xd7, (byte)0xcd,
- (byte)0x64, (byte)0xd9, (byte)0x93, (byte)0x38, (byte)0xe2, (byte)0x59, (byte)0xe0,
- (byte)0x9e, (byte)0x3a, (byte)0x25, (byte)0x27, (byte)0xa2, (byte)0xd9, (byte)0x20,
- (byte)0xb0, (byte)0x45, (byte)0x5f, (byte)0x6c, (byte)0x15, (byte)0x6f, (byte)0x10,
- (byte)0x55, (byte)0xa7, (byte)0xf9, (byte)0x3d, (byte)0x92, (byte)0x3c, (byte)0x7c,
- (byte)0x23, (byte)0x1b, (byte)0xc0, (byte)0xb5, (byte)0x17, (byte)0x41, (byte)0x5e,
- (byte)0x8c, (byte)0xdc, (byte)0x25, (byte)0x1d, (byte)0x35, (byte)0x2b, (byte)0xd3,
- (byte)0x97, (byte)0x1a, (byte)0x6f, (byte)0xae, (byte)0xeb, (byte)0xf5, (byte)0xf9,
- (byte)0x02, (byte)0x41, (byte)0x00, (byte)0xd7, (byte)0x3e, (byte)0xed, (byte)0x70,
- (byte)0xfe, (byte)0xee, (byte)0x0e, (byte)0x30, (byte)0x29, (byte)0xfa, (byte)0xd7,
- (byte)0x38, (byte)0xcf, (byte)0x8e, (byte)0xc1, (byte)0x9c, (byte)0x78, (byte)0x06,
- (byte)0x2d, (byte)0xda, (byte)0x33, (byte)0x58, (byte)0xa1, (byte)0x7b, (byte)0xbf,
- (byte)0x00, (byte)0xb9, (byte)0xdf, (byte)0xea, (byte)0x65, (byte)0x86, (byte)0xbb,
- (byte)0xcc, (byte)0x83, (byte)0xce, (byte)0xde, (byte)0xc3, (byte)0xf8, (byte)0x89,
- (byte)0xf5, (byte)0x9f, (byte)0xa6, (byte)0x1d, (byte)0xc9, (byte)0xfb, (byte)0x98,
- (byte)0xa1, (byte)0x2e, (byte)0xe0, (byte)0x57, (byte)0x6e, (byte)0xbd, (byte)0x57,
- (byte)0x20, (byte)0xf9, (byte)0x6b, (byte)0x13, (byte)0x42, (byte)0x9d, (byte)0x8d,
- (byte)0x66, (byte)0x4d, (byte)0x7a, (byte)0x2d, (byte)0x02, (byte)0x41, (byte)0x00,
- (byte)0xd7, (byte)0x00, (byte)0x18, (byte)0x54, (byte)0xe8, (byte)0x37, (byte)0xdb,
- (byte)0xf8, (byte)0x98, (byte)0x7b, (byte)0x18, (byte)0x33, (byte)0xf6, (byte)0x28,
- (byte)0xa8, (byte)0x8c, (byte)0xd9, (byte)0xfd, (byte)0x4c, (byte)0x4e, (byte)0x41,
- (byte)0x73, (byte)0x2e, (byte)0x79, (byte)0x31, (byte)0xcc, (byte)0x7d, (byte)0x42,
- (byte)0xb7, (byte)0xa1, (byte)0xd2, (byte)0xbc, (byte)0x1f, (byte)0x62, (byte)0xcf,
- (byte)0x15, (byte)0x7c, (byte)0x62, (byte)0x97, (byte)0x70, (byte)0xf1, (byte)0x15,
- (byte)0xf1, (byte)0x33, (byte)0xa1, (byte)0x9d, (byte)0xbb, (byte)0x5f, (byte)0xd7,
- (byte)0x5a, (byte)0xf9, (byte)0x24, (byte)0x58, (byte)0xac, (byte)0x86, (byte)0x6a,
- (byte)0xed, (byte)0xd4, (byte)0x84, (byte)0xe4, (byte)0x3f, (byte)0xfe, (byte)0xb0,
- (byte)0xd3, (byte)0x02, (byte)0x41, (byte)0x00, (byte)0xd4, (byte)0xb7, (byte)0x84,
- (byte)0xb2, (byte)0x39, (byte)0xce, (byte)0x0b, (byte)0x49, (byte)0x80, (byte)0x03,
- (byte)0x3c, (byte)0xb5, (byte)0x11, (byte)0x32, (byte)0x34, (byte)0x96, (byte)0xac,
- (byte)0x6a, (byte)0xf6, (byte)0xdf, (byte)0x80, (byte)0x04, (byte)0xe4, (byte)0x39,
- (byte)0xc6, (byte)0x0e, (byte)0x32, (byte)0xa3, (byte)0x5e, (byte)0x23, (byte)0x0d,
- (byte)0x9f, (byte)0x04, (byte)0xc3, (byte)0x72, (byte)0x2a, (byte)0xe6, (byte)0xa2,
- (byte)0xf5, (byte)0xbc, (byte)0x3f, (byte)0x15, (byte)0x4c, (byte)0xb5, (byte)0x33,
- (byte)0x26, (byte)0xa8, (byte)0x8c, (byte)0x09, (byte)0xfb, (byte)0x7e, (byte)0x1e,
- (byte)0x32, (byte)0x40, (byte)0x0d, (byte)0x1d, (byte)0xcb, (byte)0x7f, (byte)0xf6,
- (byte)0xf2, (byte)0x29, (byte)0x9b, (byte)0x01, (byte)0xd5, (byte)0x02, (byte)0x40,
- (byte)0x24, (byte)0x26, (byte)0x1c, (byte)0xf1, (byte)0x31, (byte)0xb6, (byte)0x2a,
- (byte)0xa3, (byte)0x0a, (byte)0xa8, (byte)0x2f, (byte)0xb2, (byte)0x94, (byte)0xe1,
- (byte)0xd3, (byte)0x2d, (byte)0x13, (byte)0x7d, (byte)0xd6, (byte)0x35, (byte)0x96,
- (byte)0x25, (byte)0x92, (byte)0x9b, (byte)0xc7, (byte)0xf6, (byte)0xb4, (byte)0xdc,
- (byte)0xe1, (byte)0xd9, (byte)0x30, (byte)0x80, (byte)0x76, (byte)0xda, (byte)0x7b,
- (byte)0x2d, (byte)0x06, (byte)0xa3, (byte)0xe1, (byte)0x08, (byte)0x99, (byte)0x50,
- (byte)0x72, (byte)0x24, (byte)0x97, (byte)0x38, (byte)0xd9, (byte)0x07, (byte)0x4d,
- (byte)0x43, (byte)0x3b, (byte)0x7e, (byte)0x93, (byte)0xf6, (byte)0x36, (byte)0x07,
- (byte)0x86, (byte)0x83, (byte)0x63, (byte)0xf0, (byte)0xa8, (byte)0x9d, (byte)0xdf,
- (byte)0x07, (byte)0x02, (byte)0x40, (byte)0x3e, (byte)0x58, (byte)0x03, (byte)0xbf,
- (byte)0xea, (byte)0x3e, (byte)0x34, (byte)0x2c, (byte)0xb7, (byte)0xc3, (byte)0x09,
- (byte)0xe9, (byte)0xf4, (byte)0x43, (byte)0x41, (byte)0xc4, (byte)0x7c, (byte)0x6e,
- (byte)0x75, (byte)0x72, (byte)0x5d, (byte)0xfc, (byte)0xa3, (byte)0x75, (byte)0x1d,
- (byte)0xa0, (byte)0xee, (byte)0xc2, (byte)0x1f, (byte)0x71, (byte)0xb0, (byte)0xf3,
- (byte)0x1d, (byte)0xec, (byte)0x81, (byte)0xdb, (byte)0x45, (byte)0xe5, (byte)0x6a,
- (byte)0xe8, (byte)0xe0, (byte)0x64, (byte)0x90, (byte)0xff, (byte)0xb9, (byte)0xf8,
- (byte)0x12, (byte)0xed, (byte)0x55, (byte)0x5c, (byte)0x9b, (byte)0x81, (byte)0xcd,
- (byte)0xbb, (byte)0x06, (byte)0x91, (byte)0xfe, (byte)0x27, (byte)0x2c, (byte)0x3a,
- (byte)0xed, (byte)0x96, (byte)0x3b, (byte)0xfe
- };
-
- /*
- * The same key in PEM format.
- * The DER version of this key was created using
- *
- * openssl pkcs8 -topk8 -nocrypt -in key1.pem
- * -inform PEM -out key1.der -outform DER
- *
- * -----BEGIN RSA PRIVATE KEY-----
- * Proc-Type: 4,ENCRYPTED
- * DEK-Info: DES-EDE3-CBC,0EE6B33EC2D92297
- *
- * r7lbWwtlmubgMG020XiOStqgrvPkP1hTrbOV7Gh2IVNTyXWyA8UriQlPyqBQNzy2
- * 5+Z+JUqzYoLCGY0fQ95ck+ya/wHJQX4OSKFOZwQKpU7pEY9wN1YPa7U9ZnyCPGtB
- * +ejvHuIMJhE5wq9Y1iEDIlON++onWTf4T36Sz3OQ8gEJbnx3x+UjcCINooj7kOeM
- * giCi5yJEOJaf4fkRioUh6S7cm/msTH3ID33rrvTjk7cD8mGzzTy4hWyKaK4K9GbC
- * dOvSORM9mVwTWMUdu1wJ5uyadwBhpSIhC/qpP8Je60nFy8YJlzB2FaMUpAuIOM7B
- * EVN2uAMDNOpGzcOJPbLig8smk2lA4+y1T3gFd9paskSjD9B8+/3KuagWEEQQL7T4
- * YK3xtjzXwEp6OdG2QjD4ZcK5D0MKuYPF3PszwzlCnBG/On6wIvIiTPWBn/G2u59D
- * gJPV7V3Jipn0iYYN+i7T5TNoT7Vko8s3BRpVSrlFUFFhtQPad6NcxGNNH5L1g3fF
- * +dp4TnG64PCQZtuu6I6gfuMXztOwQtEpxxHo9WktlCpwL0tT/tpx+zOVbLvgusjB
- * QKYCIplbSI7VtpOfcJ3kTTAWSOGZli4FayB/Dplf/FXN6ZwwASw09ioVQc/CFdLk
- * Xw05elxV8/AFvm+/VkUHK5JJSp32WMgAJA+XrUsOb5lw1Tl3Hlj9KHALp+Pt/i7N
- * +LPnxrpuTry31APt8aRup/pWOLa+f97Hz+arp4wJa5LK+GtTTtoI4+QZp5qzR/jy
- * oM+DoKtK+1WsCU7teJwEWXV/ayo1TEFEhcY0F7IAPCzDlG3XOFmulQ==
- * -----END RSA PRIVATE KEY-----
- */
-
- @Override
- protected void setUp() {
- String defAlg = KeyManagerFactory.getDefaultAlgorithm();
- try {
- factory = KeyManagerFactory.getInstance(defAlg);
- } catch (NoSuchAlgorithmException e) {
- fail("could not get default KeyManagerFactory");
- }
- }
-
- void init(String name) {
- keyType = name;
- try {
- CertificateFactory cf = CertificateFactory.getInstance("X.509");
- KeyFactory kf = KeyFactory.getInstance("RSA");
- keyTest = KeyStore.getInstance(KeyStore.getDefaultType());
- keyTest.load(null, "1234".toCharArray());
- if (keyType.equals(client)) {
- keys = new PrivateKey[3];
- keys[0] = kf.generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
- keys[1] = kf.generatePrivate(new PKCS8EncodedKeySpec(key2Bytes));
- keys[2] = kf.generatePrivate(new PKCS8EncodedKeySpec(key3Bytes));
- cert = new X509Certificate[3];
- cert[0] = (X509Certificate) cf.generateCertificate(certArray);
- cert[1] = (X509Certificate) cf.generateCertificate(certArray2);
- cert[2] = (X509Certificate) cf.generateCertificate(certArray3);
- keyTest.setKeyEntry("clientKey_01", keys[0], password.toCharArray(), new X509Certificate[] {cert[0]});
- keyTest.setKeyEntry("clientKey_02", keys[1], password.toCharArray(), new X509Certificate[] {cert[0], cert[1]});
- keyTest.setKeyEntry("clientKey_03", keys[2], password.toCharArray(), new X509Certificate[] {cert[0], cert[2]});
- keyTest.setCertificateEntry("clientAlias_01", cert[0]);
- keyTest.setCertificateEntry("clientAlias_02", cert[0]);
- keyTest.setCertificateEntry("clientAlias_03", cert[1]);
- } else if (keyType.equals(server)) {
- keys = new PrivateKey[1];
- keys[0] = kf.generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
- cert = new X509Certificate[1];
- cert[0] = (X509Certificate) cf.generateCertificate(certArray3);
- keyTest.setKeyEntry("serverKey_00", keys[0], password.toCharArray(), new X509Certificate[] {cert[0]});
- keyTest.setCertificateEntry("serverAlias_00", cert[0]);
- }
- } catch (Exception ex) {
- ex.printStackTrace();
- throw new IllegalArgumentException(ex.getMessage());
- }
- try {
- factory.init(keyTest, "1234".toCharArray());
- } catch (Exception e) {
- fail("Could't init the KeyManagerFactory");
- }
- manager = (X509KeyManager) factory.getKeyManagers()[0];
- }
-
- /**
- * @tests X509KeyManager#getClientAliases(String keyType, Principal[] issuers)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getClientAliases",
- args = {java.lang.String.class, java.security.Principal[].class}
- )
- public void test_getClientAliases() {
- init(client);
- assertNull(manager.getClientAliases(null, null));
- assertNull(manager.getClientAliases("", null));
- String[] resArray = manager.getClientAliases(type, null);
- assertNotNull(resArray);
- assertTrue("Incorrect result", compareC(resArray));
- }
-
- /**
- * @tests X509KeyManager#chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "chooseClientAlias",
- args = {java.lang.String[].class, java.security.Principal[].class, java.net.Socket.class}
- )
- public void test_chooseClientAlias() {
- String[] ar = {client};
- init(client);
- assertNull(manager.chooseClientAlias(null, null, new Socket()));
- assertNull(manager.chooseClientAlias(new String[0], null, new Socket()));
- assertNull(manager.chooseClientAlias(ar, null, new Socket()));
- String res = manager.chooseClientAlias(new String[]{type}, null, null);
- assertNotNull(res);
- assertEquals("clientkey_03", res.toLowerCase().toLowerCase());
- }
-
- /**
- * @tests X509KeyManager#getServerAliases(String keyType, Principal[] issuers)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getServerAliases",
- args = {java.lang.String.class, java.security.Principal[].class}
- )
- public void test_getServerAliases() {
- init(server);
- assertNull(manager.getServerAliases(null, null));
- assertNull(manager.getServerAliases("", null));
- String[] resArray = manager.getServerAliases(type, null);
- assertNotNull(resArray);
- assertEquals("Incorrect length", 1, resArray.length);
- assertEquals("Incorrect aliase", "serverkey_00", resArray[0].toLowerCase());
- }
-
- /**
- * @tests X509KeyManager#chooseServerAlias(String keyType, Principal[] issuers, Socket socket)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "chooseServerAlias",
- args = {java.lang.String.class, java.security.Principal[].class, java.net.Socket.class}
- )
- public void test_chooseServerAlias() {
- init(server);
- assertNull(manager.chooseServerAlias(null, null, new Socket()));
- assertNull(manager.chooseServerAlias("", null, new Socket()));
- String res = manager.chooseServerAlias(type, null, null);
- assertNotNull(res);
- assertEquals("serverkey_00", res.toLowerCase());
- res = manager.chooseServerAlias(type, null, new Socket());
- assertNotNull(res);
- assertEquals("serverkey_00", res.toLowerCase());
- }
-
- /**
- * @tests X509KeyManager#getCertificateChain(String alias)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCertificateChain",
- args = {java.lang.String.class}
- )
- public void test_getCertificateChain() {
- init(server);
- assertNull("Not NULL for NULL parameter", manager.getCertificateChain(null));
- assertNull("Not NULL for empty parameter",manager.getCertificateChain(""));
- assertNull("Not NULL for clientAlias_01 parameter", manager.getCertificateChain("clientAlias_01"));
- assertNull("Not NULL for serverAlias_00 parameter", manager.getCertificateChain("serverAlias_00"));
- }
-
- /**
- * @tests X509KeyManager#getPrivateKey(String alias)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPrivateKey",
- args = {java.lang.String.class}
- )
- public void test_getPrivateKey() {
- init(client);
- assertNull("Not NULL for NULL parameter", manager.getPrivateKey(null));
- assertNull("Not NULL for serverAlias_00 parameter", manager.getPrivateKey("serverAlias_00"));
- assertNull("Not NULL for clientAlias_02 parameter", manager.getPrivateKey("clientAlias_02"));
- }
-
-
- private boolean compareC(String[] ar) {
- if (ar.length != 3) {
- return false;
- }
- for (int i = 0; i < ar.length; i++) {
- if (!ar[i].toLowerCase().equals("clientkey_01") && !ar[i].toLowerCase().equals("clientkey_02") && !ar[i].toLowerCase().equals("clientkey_03")) {
- return false;
- }
- }
- return true;
- }
-}
-
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/X509TrustManagerTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/X509TrustManagerTest.java
deleted file mode 100644
index d5e4001..0000000
--- a/x-net/src/test/java/tests/api/javax/net/ssl/X509TrustManagerTest.java
+++ /dev/null
@@ -1,258 +0,0 @@
-package tests.api.javax.net.ssl;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.ByteArrayInputStream;
-import java.security.cert.CertificateFactory;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-import javax.net.ssl.X509TrustManager;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.security.tests.support.cert.TestUtils;
-import org.apache.harmony.xnet.tests.support.X509TrustManagerImpl;
-
-/**
- * Tests for <code>X509TrustManager</code> class constructors and methods.
- */
-@TestTargetClass(X509TrustManager.class)
-public class X509TrustManagerTest extends TestCase {
-
- private X509Certificate[] setX509Certificate() {
- try {
- CertificateFactory certFact = CertificateFactory.getInstance("X.509");
- X509Certificate pemCert = (X509Certificate) certFact
- .generateCertificate(new ByteArrayInputStream(TestUtils
- .getX509Certificate_v3()));
- X509Certificate[] xcert = {pemCert};
- return xcert;
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- return null;
- }
-
- private X509Certificate[] setInvalid() {
- try {
- CertificateFactory certFact = CertificateFactory.getInstance("X.509");
- X509Certificate pemCert = (X509Certificate) certFact
- .generateCertificate(new ByteArrayInputStream(TestUtils
- .getX509Certificate_v1()));
- X509Certificate[] xcert = {pemCert};
- return xcert;
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- return null;
- }
-
- /**
- * @tests javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[] chain, String authType)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "checkClientTrusted",
- args = {java.security.cert.X509Certificate[].class, java.lang.String.class}
- )
- public void test_checkClientTrusted_01() {
- X509TrustManagerImpl xtm = new X509TrustManagerImpl();
- X509Certificate[] xcert = null;
-
- try {
- xtm.checkClientTrusted(xcert, "SSL");
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- xcert = new X509Certificate[0];
- try {
- xtm.checkClientTrusted(xcert, "SSL");
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- xcert = setX509Certificate();
- try {
- xtm.checkClientTrusted(xcert, null);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- try {
- xtm.checkClientTrusted(xcert, "");
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
- }
-
- /**
- * @tests javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[] chain, String authType)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "checkClientTrusted",
- args = {java.security.cert.X509Certificate[].class, java.lang.String.class}
- )
- public void test_checkClientTrusted_02() {
- X509TrustManagerImpl xtm = new X509TrustManagerImpl();
- X509Certificate[] xcert = setInvalid();
-
- try {
- xtm.checkClientTrusted(xcert, "SSL");
- fail("CertificateException wasn't thrown");
- } catch (CertificateException ce) {
- //expected
- }
- }
-
- /**
- * @tests javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[] chain, String authType)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "checkClientTrusted",
- args = {java.security.cert.X509Certificate[].class, java.lang.String.class}
- )
- public void test_checkClientTrusted_03() {
- X509TrustManagerImpl xtm = new X509TrustManagerImpl();
- X509Certificate[] xcert = setX509Certificate();
-
- try {
- xtm.checkClientTrusted(xcert, "SSL");
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @tests javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[] chain, String authType)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "checkServerTrusted",
- args = {java.security.cert.X509Certificate[].class, java.lang.String.class}
- )
- public void test_checkServerTrusted_01() {
- X509TrustManagerImpl xtm = new X509TrustManagerImpl();
- X509Certificate[] xcert = null;
-
- try {
- xtm.checkServerTrusted(xcert, "SSL");
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- xcert = new X509Certificate[0];
- try {
- xtm.checkServerTrusted(xcert, "SSL");
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- xcert = setX509Certificate();
- try {
- xtm.checkServerTrusted(xcert, null);
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
-
- try {
- xtm.checkServerTrusted(xcert, "");
- fail("IllegalArgumentException wasn't thrown");
- } catch (IllegalArgumentException iae) {
- //expected
- } catch (Exception e) {
- fail(e + " was thrown instead of IllegalArgumentException");
- }
- }
-
- /**
- * @tests javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[] chain, String authType)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "checkServerTrusted",
- args = {java.security.cert.X509Certificate[].class, java.lang.String.class}
- )
- public void test_checkServerTrusted_02() {
- X509TrustManagerImpl xtm = new X509TrustManagerImpl();
- X509Certificate[] xcert = setInvalid();
-
- try {
- xtm.checkServerTrusted(xcert, "SSL");
- fail("CertificateException wasn't thrown");
- } catch (CertificateException ce) {
- //expected
- }
- }
-
- /**
- * @tests javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[] chain, String authType)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "checkServerTrusted",
- args = {java.security.cert.X509Certificate[].class, java.lang.String.class}
- )
- public void test_checkServerTrusted_03() {
- X509TrustManagerImpl xtm = new X509TrustManagerImpl();
- X509Certificate[] xcert = setX509Certificate();
-
- try {
- xtm.checkServerTrusted(xcert, "SSL");
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
- /**
- * @tests javax.net.ssl.X509TrustManager#getAcceptedIssuers()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAcceptedIssuers",
- args = {}
- )
- public void test_getAcceptedIssuers() {
- X509TrustManagerImpl xtm = new X509TrustManagerImpl();
-
- try {
- assertNotNull(xtm.getAcceptedIssuers());
- } catch (Exception ex) {
- fail("Unexpected exception " + ex);
- }
- }
-
-}
diff --git a/x-net/src/test/java/tests/xnet/AllTests.java b/x-net/src/test/java/tests/xnet/AllTests.java
deleted file mode 100644
index 04a2ed6..0000000
--- a/x-net/src/test/java/tests/xnet/AllTests.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package tests.xnet;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-/**
- * Test suite that includes all tests for the Math project.
- */
-public class AllTests {
- public static Test suite() {
- TestSuite suite = new TestSuite("All javax.net and javax.net.ssl test suites");
- // $JUnit-BEGIN$
- suite.addTest(tests.api.javax.net.AllTests.suite());
- suite.addTest(tests.api.javax.net.ssl.AllTests.suite());
- // $JUnit-END$
- return suite;
- }
-}