diff options
author | The Android Open Source Project <initial-contribution@android.com> | 2009-01-09 17:50:54 -0800 |
---|---|---|
committer | The Android Open Source Project <initial-contribution@android.com> | 2009-01-09 17:50:54 -0800 |
commit | a0881d052ee72e3f7e773374e9b1aa75fbd6be4c (patch) | |
tree | 8a9462436077d0d906368cb21f521f1bf8a25500 /support/src/test/java/org | |
parent | dd828f42a5c83b4270d4fbf6fce2da1878f1e84a (diff) | |
download | libcore-a0881d052ee72e3f7e773374e9b1aa75fbd6be4c.zip libcore-a0881d052ee72e3f7e773374e9b1aa75fbd6be4c.tar.gz libcore-a0881d052ee72e3f7e773374e9b1aa75fbd6be4c.tar.bz2 |
auto import from //branches/cupcake/...@125939
Diffstat (limited to 'support/src/test/java/org')
33 files changed, 2633 insertions, 678 deletions
diff --git a/support/src/test/java/org/apache/harmony/security/tests/support/MyKeyStoreSpi.java b/support/src/test/java/org/apache/harmony/security/tests/support/MyKeyStoreSpi.java index 18acec8..fc58639 100644 --- a/support/src/test/java/org/apache/harmony/security/tests/support/MyKeyStoreSpi.java +++ b/support/src/test/java/org/apache/harmony/security/tests/support/MyKeyStoreSpi.java @@ -44,6 +44,7 @@ import java.util.Enumeration; public class MyKeyStoreSpi extends KeyStoreSpi { + @SuppressWarnings("unused") public Key engineGetKey(String alias, char[] password) throws NoSuchAlgorithmException, UnrecoverableKeyException { return null; @@ -92,6 +93,10 @@ public class MyKeyStoreSpi extends KeyStoreSpi { } public boolean engineContainsAlias(String alias) { + if (alias != null) + { + return alias.startsWith("test_engineEntry"); + } return false; } @@ -120,6 +125,7 @@ public class MyKeyStoreSpi extends KeyStoreSpi { return ""; } + @SuppressWarnings("unused") public void engineStore(OutputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException { if (!(stream instanceof ByteArrayOutputStream)) { @@ -132,6 +138,7 @@ public class MyKeyStoreSpi extends KeyStoreSpi { } + @SuppressWarnings("unused") public void engineLoad(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException { } diff --git a/support/src/test/java/org/apache/harmony/security/tests/support/MyProvider.java b/support/src/test/java/org/apache/harmony/security/tests/support/MyProvider.java new file mode 100644 index 0000000..9c78b6d --- /dev/null +++ b/support/src/test/java/org/apache/harmony/security/tests/support/MyProvider.java @@ -0,0 +1,12 @@ +package org.apache.harmony.security.tests.support; + +import java.security.Provider; + +public class MyProvider extends Provider { + + public MyProvider() { + super("MyProvider", 1.0, "Test Provider 1.0"); + put("KeyStore.TestKeyStore", TestKeyStoreSpi.class.getName()); + } + +} diff --git a/support/src/test/java/org/apache/harmony/security/tests/support/MySSLContextSpi.java b/support/src/test/java/org/apache/harmony/security/tests/support/MySSLContextSpi.java index c503675..99c76ba 100644 --- a/support/src/test/java/org/apache/harmony/security/tests/support/MySSLContextSpi.java +++ b/support/src/test/java/org/apache/harmony/security/tests/support/MySSLContextSpi.java @@ -39,7 +39,9 @@ import javax.net.ssl.TrustManager; */ public class MySSLContextSpi extends SSLContextSpi { + private boolean init = false; + protected void engineInit(KeyManager[] km, TrustManager[] tm, SecureRandom sr) throws KeyManagementException { if (sr == null) { @@ -52,7 +54,7 @@ public class MySSLContextSpi extends SSLContextSpi { protected SSLSocketFactory engineGetSocketFactory() { if (!init) { throw new RuntimeException("Not initialiazed"); - }; + } return null; } @@ -118,7 +120,7 @@ public class MySSLContextSpi extends SSLContextSpi { public String[] getEnabledCipherSuites() { return null; } public String[] getEnabledProtocols() {return null; } public boolean getEnableSessionCreation() { return true; } - public SSLEngineResult.HandshakeStatus getHandshakeStatus() { return null; }; + public SSLEngineResult.HandshakeStatus getHandshakeStatus() { return null; } public boolean getNeedClientAuth() { return true; } public SSLSession getSession() { return null; } public String[] getSupportedCipherSuites() { return null; } diff --git a/support/src/test/java/org/apache/harmony/security/tests/support/Support_Configuration.java b/support/src/test/java/org/apache/harmony/security/tests/support/Support_Configuration.java deleted file mode 100644 index 51bb892..0000000 --- a/support/src/test/java/org/apache/harmony/security/tests/support/Support_Configuration.java +++ /dev/null @@ -1,475 +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.security.tests.support; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Hashtable; - -/** - * This class is responsible for providing the dynamic names and addresses for - * the java.net classes. There are two directories which need to be placed on an - * ftp server and an http server which should accompany this source. The - * ftp-files have to be placed on an ftp server and have to be the root of a - * user jcltest with password jclpass. The testres files must be available on an - * HTTP server and the name and location can be configured below. - */ -public class Support_Configuration { - - public static String DomainAddress = "apache.org"; - - public static String WebName = "jcltest."; - - public static final String HomeAddress; - - public static String TestResourcesDir = "/testres231"; - - public static final String TestResources; - - public static String HomeAddressResponse = "HTTP/1.1 200 OK"; - - public static String HomeAddressSoftware = "Jetty(6.0.x)"; - - public static String ProxyServerTestHost = "jcltest.apache.org"; - - public static String SocksServerTestHost = "jcltest.apache.org"; - - public static int SocksServerTestPort = 1080; - - // Need an IP address that does not resolve to a host name - public static String UnresolvedIP = "192.168.99.99"; - - // the bytes for an address which represents an address which is not - // one of the addresses for any of our machines on which tests will run - // it is used to verify we get the expected error when we try to bind - // to an address that is not one of the machines local addresses - public static byte nonLocalAddressBytes[] = { 1, 0, 0, 0 }; - - public static String InetTestAddress = "localhost"; - - public static String InetTestIP = "127.0.0.1"; - - public static String InetTestAddress2 = "localhost"; - - public static String InetTestIP2 = "127.0.0.1"; - - public static byte[] InetTestCaddr = { 9, 26, -56, -111 }; - - public static int InetTestHashcode = 2130706433; - - public static final String HomeAddress6 = "jcltest6.apache.org"; - - public static String IPv6GlobalAddressJcl4 = "FE80:0000:0000:0000:020D:60FF:FE0F:A776%4"; // this - - public static String ProxyServerTestHostIPv6 = "jcltest6.apache.org"; - - public static String InetTestIP6 = "fe80::20d:60ff:fe24:7410"; - - public static String InetTestIP6LO = "::1"; - - // ip address that resolves to a host that is not present on the local - // network - // this allows us to check the timeouts for connect - public static String ResolvedNotExistingHost = "9.26.194.72"; - - /** - * You can compute the hash code with the following code: try { String name = - * "whatever.xxx.com"; - * System.out.println(InetAddress.getByName(name).hashCode()); } catch - * (UnknownHostException e) {} - */ - - /** - * An address that resolves to more than one IP address so that the - * getAllByName test has something to test. - */ - public static String SpecialInetTestAddress = "jcltestmultiple.apache.org"; - - public static int SpecialInetTestAddressNumber = 4; - - /** - * InetAlias1 and InetAlias2 must be different host names that resolve to - * the same IP address. - */ - public static String InetAlias1 = "alias1.apache.org"; - - public static String InetAlias2 = "alias2.apache.org"; - - public static String FTPTestAddress = "jcltest:jclpass@localhost"; - - public static String URLConnectionLastModifiedString = "Mon, 14 Jun 1999 21:06:22 GMT"; - - public static long URLConnectionLastModified = 929394382000L; - - public static long URLConnectionDate = 929106872000L; - - public static boolean RunCommTests = false; - - public static String Port1 = "COM1"; - - public static String Port2 = "COM2"; - - static Hashtable<String, String> props = null; - static { - loadProperties(); - HomeAddress = WebName + DomainAddress; - TestResources = HomeAddress + TestResourcesDir; - } - - static void loadProperties() { - InputStream in = null; - Hashtable<String, String> props = new Hashtable<String, String>(); - - String iniName = System.getProperty("test.ini.file", "JCLAuto.ini"); - if (System.getProperty("test.comm") != null) { - RunCommTests = true; - } - - try { - in = new FileInputStream(iniName); - } catch (IOException e) { - } catch (Exception e) { - System.out.println("SupportConfiguration.loadProperties()"); - System.out.println(e); - e.printStackTrace(); - } - if (in == null) { - try { - Class<?> cl = Class - .forName("com.ibm.support.Support_Configuration"); - in = cl.getResourceAsStream(iniName); - } catch (ClassNotFoundException e) { - } - } - try { - if (in != null) { - load(in, props); - } - } catch (IOException e) { - } - if (props.size() == 0) { - return; - } - String value; - - value = props.get("DomainAddress"); - if (value != null) { - DomainAddress = value; - } - - value = props.get("WebName"); - if (value != null) { - WebName = value; - } - - value = props.get("TestResourcesDir"); - if (value != null) { - TestResourcesDir = value; - } - value = props.get("HomeAddressResponse"); - if (value != null) { - HomeAddressResponse = value; - } - - value = props.get("HomeAddressSoftware"); - if (value != null) { - HomeAddressSoftware = value; - } - - value = props.get("ProxyServerTestHost"); - if (value != null) { - ProxyServerTestHost = value; - } - - value = props.get("SocksServerTestHost"); - if (value != null) { - SocksServerTestHost = value; - } - - value = props.get("SocksServerTestPort"); - if (value != null) { - SocksServerTestPort = Integer.parseInt(value); - } - - value = props.get("UnresolvedIP"); - if (value != null) { - UnresolvedIP = value; - } - - value = props.get("InetTestAddress"); - if (value != null) { - InetTestAddress = value; - } - - value = props.get("InetTestIP"); - if (value != null) { - InetTestIP = value; - byte[] addr = new byte[4]; - int last = 0; - try { - for (int i = 0; i < 3; i++) { - int dot = InetTestIP.indexOf('.', last); - addr[i] = (byte) Integer.parseInt(InetTestIP.substring( - last, dot)); - last = dot + 1; - } - addr[3] = (byte) Integer.parseInt(InetTestIP.substring(last)); - InetTestCaddr = addr; - } catch (RuntimeException e) { - System.out.println("Error parsing InetTestIP (" + InetTestIP - + ")"); - System.out.println(e); - } - } - - value = props.get("NonLocalAddressBytes"); - if (value != null) { - String nonLocalAddressBytesString = value; - byte[] addr = new byte[4]; - int last = 0; - try { - for (int i = 0; i < 3; i++) { - int dot = nonLocalAddressBytesString.indexOf('.', last); - addr[i] = (byte) Integer - .parseInt(nonLocalAddressBytesString.substring( - last, dot)); - last = dot + 1; - } - addr[3] = (byte) Integer.parseInt(nonLocalAddressBytesString - .substring(last)); - nonLocalAddressBytes = addr; - } catch (RuntimeException e) { - System.out.println("Error parsing NonLocalAddressBytes (" - + nonLocalAddressBytesString + ")"); - System.out.println(e); - } - } - - value = props.get("InetTestAddress2"); - if (value != null) { - InetTestAddress2 = value; - } - - value = props.get("InetTestIP2"); - if (value != null) { - InetTestIP2 = value; - } - - value = props.get("InetTestHashcode"); - if (value != null) { - InetTestHashcode = Integer.parseInt(value); - } - - value = props.get("SpecialInetTestAddress"); - if (value != null) { - SpecialInetTestAddress = value; - } - - value = props.get("SpecialInetTestAddressNumber"); - if (value != null) { - SpecialInetTestAddressNumber = Integer.parseInt(value); - } - - value = props.get("FTPTestAddress"); - if (value != null) { - FTPTestAddress = value; - } - - value = props.get("URLConnectionLastModifiedString"); - if (value != null) { - URLConnectionLastModifiedString = value; - } - - value = props.get("URLConnectionLastModified"); - if (value != null) { - URLConnectionLastModified = Long.parseLong(value); - } - - value = props.get("URLConnectionDate"); - if (value != null) { - URLConnectionDate = Long.parseLong(value); - } - - value = props.get("Port1"); - if (value != null) { - Port1 = value; - } - - value = props.get("Port2"); - if (value != null) { - Port2 = value; - } - - value = props.get("InetTestIP6"); - if (value != null) { - InetTestIP6 = value; - } - - value = props.get("InetTestIP6LO"); - if (value != null) { - InetTestIP6LO = value; - } - - value = props.get("ProxyServerTestHostIPv6"); - if (value != null) { - ProxyServerTestHostIPv6 = value; - } - - value = props.get("ResolvedNotExistingHost"); - if (value != null) { - ResolvedNotExistingHost = value; - } - - value = props.get("InetAlias1"); - if (value != null) { - InetAlias1 = value; - } - - value = props.get("InetAlias2"); - if (value != null) { - InetAlias2 = value; - } - - value = props.get("IPv6GlobalAddressJcl4"); - if (value != null) { - IPv6GlobalAddressJcl4 = value; - } - - } - - static void load(InputStream in, Hashtable<String, String> result) throws IOException { - int NONE = 0, SLASH = 1, UNICODE = 2, CONTINUE = 3, DONE = 4, IGNORE = 5; - int mode = NONE, unicode = 0, count = 0, nextChar; - StringBuffer key = new StringBuffer(), value = new StringBuffer(), buffer = key; - boolean firstChar = true; - - while ((nextChar = in.read()) != -1) { - if (mode == UNICODE) { - int digit = Character.digit((char) nextChar, 16); - if (digit >= 0) { - unicode = (unicode << 4) + digit; - if (++count < 4) { - continue; - } - } - mode = NONE; - buffer.append((char) unicode); - if (nextChar != '\n') { - continue; - } - } - if (mode == SLASH) { - mode = NONE; - switch (nextChar) { - case '\r': - mode = CONTINUE; // Look for a following \n - continue; - case '\n': - mode = IGNORE; // Ignore whitespace on the next line - continue; - case 'b': - nextChar = '\b'; - break; - case 'f': - nextChar = '\f'; - break; - case 'n': - nextChar = '\n'; - break; - case 'r': - nextChar = '\r'; - break; - case 't': - nextChar = '\t'; - break; - case 'u': - mode = UNICODE; - unicode = count = 0; - continue; - } - } else { - switch (nextChar) { - case '#': - case '!': - if (firstChar) { - while ((nextChar = in.read()) != -1) { - if (nextChar == '\r' || nextChar == '\n') { - break; - } - } - continue; - } - break; - case '\n': - if (mode == CONTINUE) { // Part of a \r\n sequence - mode = IGNORE; // Ignore whitespace on the next line - continue; - } - // fall into the next case - case '\r': - mode = NONE; - firstChar = true; - if (key.length() > 0 || buffer == value) { - result.put(key.toString(), value.toString()); - } - key.setLength(0); - value.setLength(0); - buffer = key; - continue; - case '\\': - mode = SLASH; - continue; - case ':': - case '=': - if (buffer == key) { - buffer = value; - continue; - } - break; - } - char c = (char) nextChar; - if ((c >= 0x1c && c <= 0x20) || (c >= 0x9 && c <= 0xd)) { - if (mode == CONTINUE) { - mode = IGNORE; - } - if (buffer.length() == 0 || mode == IGNORE) { - continue; - } - if (buffer == key) { - mode = DONE; - continue; - } - } - if (mode == IGNORE || mode == CONTINUE) { - mode = NONE; - } - } - firstChar = false; - if (mode == DONE) { - buffer = value; - mode = NONE; - } - buffer.append((char) nextChar); - } - if (key.length() > 0 || buffer == value) { - result.put(key.toString(), value.toString()); - } - } - -} diff --git a/support/src/test/java/org/apache/harmony/security/tests/support/TestKeyStoreSpi.java b/support/src/test/java/org/apache/harmony/security/tests/support/TestKeyStoreSpi.java new file mode 100644 index 0000000..757234e --- /dev/null +++ b/support/src/test/java/org/apache/harmony/security/tests/support/TestKeyStoreSpi.java @@ -0,0 +1,260 @@ +package org.apache.harmony.security.tests.support; + +import org.apache.harmony.security.tests.support.cert.MyCertificate; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.security.Key; +import java.security.KeyStoreException; +import java.security.KeyStoreSpi; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.UnrecoverableKeyException; +import java.security.KeyStore.LoadStoreParameter; +import java.security.KeyStore.PasswordProtection; +import java.security.KeyStore.ProtectionParameter; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.util.Collections; +import java.util.Date; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; + +import javax.crypto.SecretKey; + +public class TestKeyStoreSpi extends KeyStoreSpi { + + Map<String, Object> aliases = new HashMap<String, Object>(); + + public static final Certificate CERT = new MyCertificate("certtype", + new byte[] {}); + public static final Certificate[] CERTCHAIN = new Certificate[] { + new MyCertificate("cert1", new byte[] {}), + new MyCertificate("cert2", new byte[] {})}; + + public static final Key KEY = new SecretKey() { + + public String getAlgorithm() { + return "secret"; + } + + public byte[] getEncoded() { + return new byte[] {42}; + } + + public String getFormat() { + return "format"; + } + + }; + + public static final Object DUMMY = new Object(); + + public TestKeyStoreSpi() { + aliases.put("certalias", CERT); + aliases.put("chainalias", CERTCHAIN); + aliases.put("keyalias", KEY); + aliases.put("unknownalias", DUMMY); + } + + @Override + public Enumeration<String> engineAliases() { + return Collections.enumeration(aliases.keySet()); + } + + @Override + public boolean engineContainsAlias(String alias) { + return aliases.containsKey(alias); + } + + @Override + public void engineDeleteEntry(String alias) throws KeyStoreException { + throw new KeyStoreException("entry " + alias + " cannot be deleted"); + } + + @Override + public Certificate engineGetCertificate(String alias) { + return (Certificate) aliases.get(alias); + } + + @Override + public String engineGetCertificateAlias(Certificate cert) { + if (cert == null) { + throw new NullPointerException(); + } + + for (Map.Entry<String, Object> alias : aliases.entrySet()) { + if (alias.getValue() == cert) { + return alias.getKey(); + } + } + + return null; + } + + @Override + public Certificate[] engineGetCertificateChain(String alias) { + return (Certificate[]) aliases.get(alias); + } + + @Override + public Date engineGetCreationDate(String alias) { + return new Date(42 * 1024 * 1024); + } + + @Override + public Key engineGetKey(String alias, char[] password) + throws NoSuchAlgorithmException, UnrecoverableKeyException { + if (engineContainsAlias(alias)) { + if (!engineIsKeyEntry(alias)) { + if (password == null) { + throw new NoSuchAlgorithmException("no such alg"); + } else { + throw new UnrecoverableKeyException(); + } + + } + return (Key) aliases.get(alias); + } + + throw new UnrecoverableKeyException(); + } + + @Override + public boolean engineIsCertificateEntry(String alias) { + try { + Certificate c = (Certificate) aliases.get(alias); + return true; + } catch (ClassCastException e) { + return false; + } + } + + @Override + public boolean engineIsKeyEntry(String alias) { + try { + Key k = (Key) aliases.get(alias); + return true; + } catch (ClassCastException e) { + return false; + } + } + + @Override + public void engineLoad(InputStream stream, char[] password) + throws IOException, NoSuchAlgorithmException, CertificateException { + if (stream != null) { + if (stream.available() == 0) + { + throw new IOException(); + } + } + if (password == null) { + throw new NoSuchAlgorithmException(); + } else if (password.length == 0) { + throw new CertificateException(); + } + } + + @Override + public void engineLoad(LoadStoreParameter param) throws IOException, + NoSuchAlgorithmException, CertificateException { + if (param == null) { + engineLoad(null, null); + return; + } + + ProtectionParameter pParam = param.getProtectionParameter(); + if (pParam == null) { + throw new NoSuchAlgorithmException(); + } + + if (pParam instanceof PasswordProtection) { + char[] password = ((PasswordProtection) pParam).getPassword(); + if (password == null) { + throw new NoSuchAlgorithmException(); + } else { + return; + } + } + throw new CertificateException(); + } + + @Override + public void engineSetCertificateEntry(String alias, Certificate cert) + throws KeyStoreException { + if (engineContainsAlias(alias)) { + if (!engineIsCertificateEntry(alias)) { + throw new KeyStoreException("alias is not a cert entry"); + } + } + aliases.put(alias, cert); + } + + @Override + public void engineSetKeyEntry(String alias, Key key, char[] password, + Certificate[] chain) throws KeyStoreException { + if (engineContainsAlias(alias)) { + if (!engineIsKeyEntry(alias)) { + throw new KeyStoreException("alias is not a key enrty"); + } + } + + if (key instanceof PrivateKey) + { + if (chain == null || chain.length == 0) { + throw new IllegalArgumentException(); + } + } + + aliases.put(alias, key); + } + + @Override + public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) + throws KeyStoreException { + throw new KeyStoreException("set entry failed"); + } + + @Override + public int engineSize() { + return aliases.size(); + } + + @Override + public void engineStore(OutputStream stream, char[] password) + throws IOException, NoSuchAlgorithmException, CertificateException { + if (stream == null) { + throw new IOException("store failed"); + } + + if (password == null) { + throw new NoSuchAlgorithmException(); + } else if (password.length == 0) { + throw new CertificateException(); + } + } + + @Override + public void engineStore(LoadStoreParameter param) throws IOException, + NoSuchAlgorithmException, CertificateException { + if (param == null) { + throw new IOException(); + } + + ProtectionParameter pParam = param.getProtectionParameter(); + if (pParam instanceof PasswordProtection) { + char[] password = ((PasswordProtection) pParam).getPassword(); + if (password == null) { + throw new NoSuchAlgorithmException(); + } else if (password.length == 0) { + throw new CertificateException(); + } + return; + } + throw new UnsupportedOperationException(); + } + +} diff --git a/support/src/test/java/org/apache/harmony/security/tests/support/acl/AclEntryImpl.java b/support/src/test/java/org/apache/harmony/security/tests/support/acl/AclEntryImpl.java new file mode 100644 index 0000000..3d922df --- /dev/null +++ b/support/src/test/java/org/apache/harmony/security/tests/support/acl/AclEntryImpl.java @@ -0,0 +1,118 @@ +/*
+ * 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.security.tests.support.acl;
+
+import java.security.Principal;
+import java.security.acl.*;
+import java.util.Enumeration;
+import java.util.Vector;
+
+/**
+ * Additional class for verification AclEntry interface
+ */
+public class AclEntryImpl implements AclEntry {
+
+ private Principal user;
+ private Vector permissionSet;
+ private boolean negative;
+
+ public AclEntryImpl(Principal principal) {
+ user = null;
+ permissionSet = new Vector(10, 10);
+ negative = false;
+ user = principal;
+ }
+
+ public AclEntryImpl() {
+ user = null;
+ permissionSet = new Vector(10, 10);
+ negative = false;
+ }
+
+ public boolean setPrincipal(Principal principal) {
+ if(user != null) {
+ return false;
+ } else {
+ user = principal;
+ return true;
+ }
+ }
+
+ public void setNegativePermissions() {
+ negative = true;
+ }
+
+ public boolean isNegative() {
+ return negative;
+ }
+
+ public boolean addPermission(Permission permission) {
+ if(permissionSet.contains(permission)) {
+ return false;
+ } else {
+ permissionSet.addElement(permission);
+ return true;
+ }
+ }
+
+ public boolean removePermission(Permission permission) {
+ return permissionSet.removeElement(permission);
+ }
+
+ public boolean checkPermission(Permission permission) {
+ return permissionSet.contains(permission);
+ }
+
+ public Enumeration permissions() {
+ return permissionSet.elements();
+ }
+
+ public String toString() {
+ StringBuffer stringbuffer = new StringBuffer();
+ if(negative)
+ stringbuffer.append("-");
+ else
+ stringbuffer.append("+");
+ if(user instanceof Group)
+ stringbuffer.append("Group.");
+ else
+ stringbuffer.append("User.");
+ stringbuffer.append((new StringBuilder()).append(user).append("=").toString());
+ Enumeration enumeration = permissions();
+ do {
+ if(!enumeration.hasMoreElements())
+ break;
+ Permission permission = (Permission)enumeration.nextElement();
+ stringbuffer.append(permission);
+ if(enumeration.hasMoreElements())
+ stringbuffer.append(",");
+ } while(true);
+ return new String(stringbuffer);
+ }
+
+ public synchronized Object clone() {
+ AclEntryImpl aclentryimpl = new AclEntryImpl(user);
+ aclentryimpl.permissionSet = (Vector)permissionSet.clone();
+ aclentryimpl.negative = negative;
+ return aclentryimpl;
+ }
+
+ public Principal getPrincipal() {
+ return user;
+ }
+}
\ No newline at end of file diff --git a/support/src/test/java/org/apache/harmony/security/tests/support/acl/AclEnumerator.java b/support/src/test/java/org/apache/harmony/security/tests/support/acl/AclEnumerator.java new file mode 100644 index 0000000..df093cd --- /dev/null +++ b/support/src/test/java/org/apache/harmony/security/tests/support/acl/AclEnumerator.java @@ -0,0 +1,51 @@ +/*
+ * 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.security.tests.support.acl;
+
+import java.security.acl.Acl;
+import java.util.*;
+
+final class AclEnumerator implements Enumeration {
+
+ Acl acl;
+ Enumeration u1;
+ Enumeration u2;
+ Enumeration g1;
+ Enumeration g2;
+
+ AclEnumerator(Acl acl1, Hashtable hashtable, Hashtable hashtable1, Hashtable hashtable2, Hashtable hashtable3) {
+ acl = acl1;
+ u1 = hashtable.elements();
+ u2 = hashtable2.elements();
+ g1 = hashtable1.elements();
+ g2 = hashtable3.elements();
+ }
+
+ public boolean hasMoreElements() {
+ return u1.hasMoreElements() || u2.hasMoreElements() || g1.hasMoreElements() || g2.hasMoreElements();
+ }
+
+ public Object nextElement() {
+ Acl acl1 = acl;
+ if(u2.hasMoreElements()) return u2.nextElement();
+ if(g1.hasMoreElements()) return g1.nextElement();
+ if(u1.hasMoreElements()) return u1.nextElement();
+ if(g2.hasMoreElements()) return g2.nextElement();
+ return acl1;
+ }
+}
\ No newline at end of file diff --git a/support/src/test/java/org/apache/harmony/security/tests/support/acl/AclImpl.java b/support/src/test/java/org/apache/harmony/security/tests/support/acl/AclImpl.java new file mode 100644 index 0000000..17c20f9 --- /dev/null +++ b/support/src/test/java/org/apache/harmony/security/tests/support/acl/AclImpl.java @@ -0,0 +1,211 @@ +/*
+ * 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.security.tests.support.acl;
+
+import java.security.Principal;
+import java.security.acl.*;
+import java.util.*;
+
+/**
+ * Additional class for verification Acl interface
+ */
+public class AclImpl extends OwnerImpl implements Acl {
+
+ private Hashtable allowedUsersTable;
+ private Hashtable allowedGroupsTable;
+ private Hashtable deniedUsersTable;
+ private Hashtable deniedGroupsTable;
+ private String aclName;
+ private Vector zeroSet;
+
+ public AclImpl(Principal principal, String s) {
+ super(principal);
+ allowedUsersTable = new Hashtable(23);
+ allowedGroupsTable = new Hashtable(23);
+ deniedUsersTable = new Hashtable(23);
+ deniedGroupsTable = new Hashtable(23);
+ aclName = null;
+ zeroSet = new Vector(1, 1);
+ try {
+ setName(principal, s);
+ } catch(Exception exception) { }
+ }
+
+ public void setName(Principal principal, String s)
+ throws NotOwnerException {
+ if(!isOwner(principal)) {
+ throw new NotOwnerException();
+ } else {
+ aclName = s;
+ return;
+ }
+ }
+
+ public String getName() {
+ return aclName;
+ }
+
+ public synchronized boolean addEntry(Principal principal, AclEntry aclentry)
+ throws NotOwnerException {
+ if(!isOwner(principal)) throw new NotOwnerException();
+ Hashtable hashtable = findTable(aclentry);
+ Principal principal1 = aclentry.getPrincipal();
+ if(hashtable.get(principal1) != null) {
+ return false;
+ } else {
+ hashtable.put(principal1, aclentry);
+ return true;
+ }
+ }
+
+ public synchronized boolean removeEntry(Principal principal, AclEntry aclentry)
+ throws NotOwnerException {
+ if(!isOwner(principal)) {
+ throw new NotOwnerException();
+ } else {
+ Hashtable hashtable = findTable(aclentry);
+ Principal principal1 = aclentry.getPrincipal();
+ Object obj = hashtable.remove(principal1);
+ return obj != null;
+ }
+ }
+
+ public synchronized Enumeration getPermissions(Principal principal) {
+ Enumeration enumeration2 = subtract(getGroupPositive(principal), getGroupNegative(principal));
+ Enumeration enumeration3 = subtract(getGroupNegative(principal), getGroupPositive(principal));
+ Enumeration enumeration = subtract(getIndividualPositive(principal), getIndividualNegative(principal));
+ Enumeration enumeration1 = subtract(getIndividualNegative(principal), getIndividualPositive(principal));
+ Enumeration enumeration4 = subtract(enumeration2, enumeration1);
+ Enumeration enumeration5 = union(enumeration, enumeration4);
+ enumeration = subtract(getIndividualPositive(principal), getIndividualNegative(principal));
+ enumeration1 = subtract(getIndividualNegative(principal), getIndividualPositive(principal));
+ enumeration4 = subtract(enumeration3, enumeration);
+ Enumeration enumeration6 = union(enumeration1, enumeration4);
+ return subtract(enumeration5, enumeration6);
+ }
+
+ public boolean checkPermission(Principal principal, Permission permission) {
+ for(Enumeration enumeration = getPermissions(principal); enumeration.hasMoreElements();) {
+ Permission permission1 = (Permission)enumeration.nextElement();
+ if(permission1.equals(permission))
+ return true;
+ }
+ return false;
+ }
+
+ public synchronized Enumeration entries() {
+ return new AclEnumerator(this, allowedUsersTable, allowedGroupsTable, deniedUsersTable, deniedGroupsTable);
+ }
+
+ public String toString() {
+ StringBuffer stringbuffer = new StringBuffer();
+ for(Enumeration enumeration = entries(); enumeration.hasMoreElements(); stringbuffer.append("\n")) {
+ AclEntry aclentry = (AclEntry)enumeration.nextElement();
+ stringbuffer.append(aclentry.toString().trim());
+ }
+ return stringbuffer.toString();
+ }
+
+ private Hashtable findTable(AclEntry aclentry) {
+ Hashtable hashtable = null;
+ Principal principal = aclentry.getPrincipal();
+ if(principal instanceof Group) {
+ if(aclentry.isNegative())
+ hashtable = deniedGroupsTable;
+ else
+ hashtable = allowedGroupsTable;
+ } else
+ if(aclentry.isNegative())
+ hashtable = deniedUsersTable;
+ else
+ hashtable = allowedUsersTable;
+ return hashtable;
+ }
+
+ private static Enumeration union(Enumeration enumeration, Enumeration enumeration1) {
+ Vector vector = new Vector(20, 20);
+ for(; enumeration.hasMoreElements(); vector.addElement(enumeration.nextElement()));
+ do {
+ if(!enumeration1.hasMoreElements())
+ break;
+ Object obj = enumeration1.nextElement();
+ if(!vector.contains(obj))
+ vector.addElement(obj);
+ } while(true);
+ return vector.elements();
+ }
+
+ private Enumeration subtract(Enumeration enumeration, Enumeration enumeration1) {
+ Vector vector = new Vector(20, 20);
+ for(; enumeration.hasMoreElements(); vector.addElement(enumeration.nextElement()));
+ do {
+ if(!enumeration1.hasMoreElements())
+ break;
+ Object obj = enumeration1.nextElement();
+ if(vector.contains(obj))
+ vector.removeElement(obj);
+ } while(true);
+ return vector.elements();
+ }
+
+ private Enumeration getGroupPositive(Principal principal) {
+ Enumeration enumeration = zeroSet.elements();
+ Enumeration enumeration1 = allowedGroupsTable.keys();
+ do {
+ if(!enumeration1.hasMoreElements())
+ break;
+ Group group = (Group)enumeration1.nextElement();
+ if(group.isMember(principal)) {
+ AclEntry aclentry = (AclEntry)allowedGroupsTable.get(group);
+ enumeration = union(aclentry.permissions(), enumeration);
+ }
+ } while(true);
+ return enumeration;
+ }
+
+ private Enumeration getGroupNegative(Principal principal) {
+ Enumeration enumeration = zeroSet.elements();
+ Enumeration enumeration1 = deniedGroupsTable.keys();
+ do {
+ if(!enumeration1.hasMoreElements())
+ break;
+ Group group = (Group)enumeration1.nextElement();
+ if(group.isMember(principal)) {
+ AclEntry aclentry = (AclEntry)deniedGroupsTable.get(group);
+ enumeration = union(aclentry.permissions(), enumeration);
+ }
+ } while(true);
+ return enumeration;
+ }
+
+ private Enumeration getIndividualPositive(Principal principal) {
+ Enumeration enumeration = zeroSet.elements();
+ AclEntry aclentry = (AclEntry)allowedUsersTable.get(principal);
+ if(aclentry != null)
+ enumeration = aclentry.permissions();
+ return enumeration;
+ }
+
+ private Enumeration getIndividualNegative(Principal principal) {
+ Enumeration enumeration = zeroSet.elements();
+ AclEntry aclentry = (AclEntry)deniedUsersTable.get(principal);
+ if(aclentry != null)
+ enumeration = aclentry.permissions();
+ return enumeration;
+ }
+}
\ No newline at end of file diff --git a/support/src/test/java/org/apache/harmony/security/tests/support/acl/GroupImpl.java b/support/src/test/java/org/apache/harmony/security/tests/support/acl/GroupImpl.java new file mode 100644 index 0000000..fe910fb --- /dev/null +++ b/support/src/test/java/org/apache/harmony/security/tests/support/acl/GroupImpl.java @@ -0,0 +1,112 @@ +/*
+ * 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.security.tests.support.acl;
+
+import java.security.Principal;
+import java.security.acl.Group;
+import java.util.Enumeration;
+import java.util.Vector;
+
+/**
+ * Additional class for verification Group interface
+ */
+public class GroupImpl implements Group {
+
+ private Vector groupMembers;
+ private String group;
+
+ public GroupImpl(String s) {
+ groupMembers = new Vector(50, 100);
+ group = s;
+ }
+
+ public boolean addMember(Principal principal) {
+ if(groupMembers.contains(principal))
+ return false;
+ if(group.equals(principal.toString())) {
+ throw new IllegalArgumentException();
+ } else {
+ groupMembers.addElement(principal);
+ return true;
+ }
+ }
+
+ public boolean removeMember(Principal principal) {
+ return groupMembers.removeElement(principal);
+ }
+
+ public Enumeration members() {
+ return groupMembers.elements();
+ }
+
+ public boolean equals(Object obj) {
+ if(this == obj)
+ return true;
+ if(!(obj instanceof Group)) {
+ return false;
+ } else {
+ Group group1 = (Group)obj;
+ return group.equals(group1.toString());
+ }
+ }
+
+ public boolean equals(Group group1) {
+ return equals(group1);
+ }
+
+ public String toString() {
+ return group;
+ }
+
+ public int hashCode() {
+ return group.hashCode();
+ }
+
+ public boolean isMember(Principal principal) {
+ if(groupMembers.contains(principal)) {
+ return true;
+ } else {
+ Vector vector = new Vector(10);
+ return isMemberRecurse(principal, vector);
+ }
+ }
+
+ public String getName() {
+ return group;
+ }
+
+ boolean isMemberRecurse(Principal principal, Vector vector) {
+ for(Enumeration enumeration = members(); enumeration.hasMoreElements();) {
+ boolean flag = false;
+ Principal principal1 = (Principal)enumeration.nextElement();
+ if(principal1.equals(principal))
+ return true;
+ if(principal1 instanceof GroupImpl) {
+ GroupImpl groupimpl = (GroupImpl)principal1;
+ vector.addElement(this);
+ if(!vector.contains(groupimpl))
+ flag = groupimpl.isMemberRecurse(principal, vector);
+ } else if(principal1 instanceof Group) {
+ Group group1 = (Group)principal1;
+ if(!vector.contains(group1)) flag = group1.isMember(principal);
+ }
+ if(flag) return flag;
+ }
+ return false;
+ }
+}
\ No newline at end of file diff --git a/support/src/test/java/org/apache/harmony/security/tests/support/acl/OwnerImpl.java b/support/src/test/java/org/apache/harmony/security/tests/support/acl/OwnerImpl.java new file mode 100644 index 0000000..c3012b6 --- /dev/null +++ b/support/src/test/java/org/apache/harmony/security/tests/support/acl/OwnerImpl.java @@ -0,0 +1,69 @@ +/*
+ * 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.security.tests.support.acl;
+
+import java.security.Principal;
+import java.security.acl.*;
+import java.util.Enumeration;
+
+/**
+ * Additional class for verification Owner interface
+ */
+public class OwnerImpl implements Owner {
+
+ private Group ownerGroup;
+
+ public OwnerImpl(Principal principal) {
+ ownerGroup = new GroupImpl("AclOwners");
+ ownerGroup.addMember(principal);
+ }
+
+ public synchronized boolean addOwner(Principal principal, Principal principal1)
+ throws NotOwnerException {
+
+ if(!isOwner(principal))
+ {
+ throw new NotOwnerException();
+ } else {
+ if (ownerGroup.isMember(principal1)) return false;
+ if (!ownerGroup.isMember(principal1)) {
+ ownerGroup.addMember(principal1);
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public synchronized boolean deleteOwner(Principal principal, Principal principal1)
+ throws NotOwnerException, LastOwnerException {
+
+ if(!isOwner(principal)) throw new NotOwnerException();
+ Enumeration enumeration = ownerGroup.members();
+ Object obj = enumeration.nextElement();
+ if(enumeration.hasMoreElements()) {
+ return ownerGroup.removeMember(principal1);
+ } else {
+ throw new LastOwnerException();
+ }
+ }
+
+ public synchronized boolean isOwner(Principal principal)
+ {
+ return ownerGroup.isMember(principal);
+ }
+}
diff --git a/support/src/test/java/org/apache/harmony/security/tests/support/acl/PermissionImpl.java b/support/src/test/java/org/apache/harmony/security/tests/support/acl/PermissionImpl.java new file mode 100644 index 0000000..2d355f9 --- /dev/null +++ b/support/src/test/java/org/apache/harmony/security/tests/support/acl/PermissionImpl.java @@ -0,0 +1,49 @@ +/*
+ * 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.security.tests.support.acl;
+
+import java.security.acl.Permission;
+
+/**
+ * Additional class for verification Permission interface
+ */
+public class PermissionImpl implements Permission {
+
+ private String permission;
+
+ public PermissionImpl(String s) {
+ permission = s;
+ }
+
+ public boolean equals(Object obj) {
+ if(obj instanceof Permission) {
+ Permission permission1 = (Permission)obj;
+ return permission.equals(permission1.toString());
+ } else {
+ return false;
+ }
+ }
+
+ public String toString() {
+ return permission;
+ }
+
+/* public int hashCode() {
+ return toString().hashCode();
+ }*/
+}
\ No newline at end of file diff --git a/support/src/test/java/org/apache/harmony/security/tests/support/acl/PrincipalImpl.java b/support/src/test/java/org/apache/harmony/security/tests/support/acl/PrincipalImpl.java new file mode 100644 index 0000000..f7dcba5 --- /dev/null +++ b/support/src/test/java/org/apache/harmony/security/tests/support/acl/PrincipalImpl.java @@ -0,0 +1,53 @@ +/*
+ * 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.security.tests.support.acl;
+
+import java.security.Principal;
+
+/**
+ * Additional class for verification Principal interface
+ */
+public class PrincipalImpl implements Principal {
+
+ private String user;
+
+ public PrincipalImpl(String s) {
+ user = s;
+ }
+
+ public boolean equals(Object obj) {
+ if(obj instanceof PrincipalImpl) {
+ PrincipalImpl principalimpl = (PrincipalImpl)obj;
+ return user.equals(principalimpl.toString());
+ } else {
+ return false;
+ }
+ }
+
+ public String toString() {
+ return user;
+ }
+
+ public int hashCode() {
+ return user.hashCode();
+ }
+
+ public String getName() {
+ return user;
+ }
+}
diff --git a/support/src/test/java/org/apache/harmony/security/tests/support/cert/MyCertPath.java b/support/src/test/java/org/apache/harmony/security/tests/support/cert/MyCertPath.java index 06c2716..ae1db87 100644 --- a/support/src/test/java/org/apache/harmony/security/tests/support/cert/MyCertPath.java +++ b/support/src/test/java/org/apache/harmony/security/tests/support/cert/MyCertPath.java @@ -54,8 +54,6 @@ public class MyCertPath extends CertPath { /** * Constructs new instance of <code>MyCertPath</code> * - * @param type - * @param encoding */ public MyCertPath(byte[] encoding) { super("MyEncoding"); @@ -76,6 +74,7 @@ public class MyCertPath extends CertPath { /** * @return default encoded form of this cert path + * @throws CertificateEncodingException * @see java.security.cert.CertPath#getEncoded() */ public byte[] getEncoded() throws CertificateEncodingException { diff --git a/support/src/test/java/org/apache/harmony/security/tests/support/cert/MyCertificate.java b/support/src/test/java/org/apache/harmony/security/tests/support/cert/MyCertificate.java index e6d6034..34ad957 100644 --- a/support/src/test/java/org/apache/harmony/security/tests/support/cert/MyCertificate.java +++ b/support/src/test/java/org/apache/harmony/security/tests/support/cert/MyCertificate.java @@ -31,11 +31,13 @@ import java.security.SignatureException; import java.security.cert.Certificate; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; +import java.security.cert.X509Extension; +import java.util.Set; /** * Stub class for <code>java.security.cert.Certificate</code> tests */ -public class MyCertificate extends Certificate { +public class MyCertificate extends Certificate implements X509Extension { private static final long serialVersionUID = -1835303280727190066L; // MyCertificate encoding @@ -140,4 +142,19 @@ public class MyCertificate extends Certificate { return data; } } + public Set<String> getNonCriticalExtensionOIDs() { + return null; + } + + public Set<String> getCriticalExtensionOIDs() { + return null; + } + + public byte[] getExtensionValue(String oid) { + return null; + } + + public boolean hasUnsupportedCriticalExtension() { + return false; + } } diff --git a/support/src/test/java/org/apache/harmony/security/tests/support/cert/MyCertificateFactorySpi.java b/support/src/test/java/org/apache/harmony/security/tests/support/cert/MyCertificateFactorySpi.java index ea38e72..f0c444c 100644 --- a/support/src/test/java/org/apache/harmony/security/tests/support/cert/MyCertificateFactorySpi.java +++ b/support/src/test/java/org/apache/harmony/security/tests/support/cert/MyCertificateFactorySpi.java @@ -101,11 +101,11 @@ public class MyCertificateFactorySpi extends CertificateFactorySpi { if (!(inStream instanceof DataInputStream)) { throw new CertificateException("Incorrect inputstream"); } - Iterator it = engineGetCertPathEncodings(); + Iterator<String> it = engineGetCertPathEncodings(); if (!it.hasNext()) { throw new CertificateException("There are no CertPath encodings"); } - return engineGenerateCertPath(inStream, (String) it.next()); + return engineGenerateCertPath(inStream, it.next()); } public CertPath engineGenerateCertPath(InputStream inStream, String encoding) @@ -121,8 +121,7 @@ public class MyCertificateFactorySpi extends CertificateFactorySpi { return null; } - public CertPath engineGenerateCertPath(List certificates) - throws CertificateException { + public CertPath engineGenerateCertPath(List<? extends Certificate> certificates) { if (certificates == null) { if (mode) { throw new NullPointerException("certificates is null"); diff --git a/support/src/test/java/org/apache/harmony/security/tests/support/cert/MyFailingCertPath.java b/support/src/test/java/org/apache/harmony/security/tests/support/cert/MyFailingCertPath.java new file mode 100644 index 0000000..40966dd --- /dev/null +++ b/support/src/test/java/org/apache/harmony/security/tests/support/cert/MyFailingCertPath.java @@ -0,0 +1,16 @@ +package org.apache.harmony.security.tests.support.cert; + +import java.security.cert.CertificateEncodingException; + +public class MyFailingCertPath extends MyCertPath { + + public MyFailingCertPath(byte[] encoding) { + super(encoding); + } + + @Override + public byte[] getEncoded() throws CertificateEncodingException { + throw new CertificateEncodingException("testing purpose"); + } + +} diff --git a/support/src/test/java/org/apache/harmony/security/tests/support/cert/MyFailingCertificate.java b/support/src/test/java/org/apache/harmony/security/tests/support/cert/MyFailingCertificate.java new file mode 100644 index 0000000..c443a5f --- /dev/null +++ b/support/src/test/java/org/apache/harmony/security/tests/support/cert/MyFailingCertificate.java @@ -0,0 +1,16 @@ +package org.apache.harmony.security.tests.support.cert; + +import java.security.cert.CertificateEncodingException; + +public class MyFailingCertificate extends MyCertificate { + + public MyFailingCertificate(String type, byte[] encoding) { + super(type, encoding); + } + + @Override + public byte[] getEncoded() throws CertificateEncodingException { + throw new CertificateEncodingException("testing purpose"); + } + +} diff --git a/support/src/test/java/org/apache/harmony/security/tests/support/cert/PolicyNodeImpl.java b/support/src/test/java/org/apache/harmony/security/tests/support/cert/PolicyNodeImpl.java new file mode 100644 index 0000000..cfe2a43 --- /dev/null +++ b/support/src/test/java/org/apache/harmony/security/tests/support/cert/PolicyNodeImpl.java @@ -0,0 +1,256 @@ +/*
+ * 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.security.tests.support.cert;
+
+import java.security.cert.PolicyNode;
+import java.util.*;
+
+public class PolicyNodeImpl implements PolicyNode {
+
+ private static final String ANY_POLICY = "2.5.29.32.0";
+ private PolicyNodeImpl mParent;
+ private HashSet mChildren;
+ private String mValidPolicy;
+ private HashSet mQualifierSet;
+ private boolean mCriticalityIndicator;
+ private HashSet mExpectedPolicySet;
+ private boolean mOriginalExpectedPolicySet;
+ private int mDepth;
+ private boolean isImmutable;
+
+ public PolicyNodeImpl(PolicyNodeImpl policynodeimpl, String s, Set set,
+ boolean flag, Set set1, boolean flag1) {
+ isImmutable = false;
+ mParent = policynodeimpl;
+ mChildren = new HashSet();
+ if(s != null) {
+ mValidPolicy = s;
+ } else {
+ mValidPolicy = "";
+ }
+ if(set != null) {
+ mQualifierSet = new HashSet(set);
+ } else {
+ mQualifierSet = new HashSet();
+ }
+ mCriticalityIndicator = flag;
+ if(set1 != null) {
+ mExpectedPolicySet = new HashSet(set1);
+ } else {
+ mExpectedPolicySet = new HashSet();
+ }
+ mOriginalExpectedPolicySet = !flag1;
+ if(mParent != null) {
+ mDepth = mParent.getDepth() + 1;
+ mParent.addChild(this);
+ } else {
+ mDepth = 0;
+ }
+ }
+
+ PolicyNodeImpl(PolicyNodeImpl policynodeimpl,
+ PolicyNodeImpl policynodeimpl1) {
+ this(policynodeimpl, policynodeimpl1.mValidPolicy, ((Set) (policynodeimpl1.mQualifierSet)), policynodeimpl1.mCriticalityIndicator, ((Set) (policynodeimpl1.mExpectedPolicySet)), false);
+ }
+
+ public PolicyNode getParent() {
+ return mParent;
+ }
+
+ public Iterator getChildren() {
+ return Collections.unmodifiableSet(mChildren).iterator();
+ }
+
+ public int getDepth() {
+ return mDepth;
+ }
+
+ public String getValidPolicy() {
+ return mValidPolicy;
+ }
+
+ public Set getPolicyQualifiers() {
+ return Collections.unmodifiableSet(mQualifierSet);
+ }
+
+ public Set getExpectedPolicies() {
+ return Collections.unmodifiableSet(mExpectedPolicySet);
+ }
+
+ public boolean isCritical() {
+ return mCriticalityIndicator;
+ }
+
+ public String toString() {
+ StringBuffer stringbuffer = new StringBuffer(asString());
+ for(Iterator iterator = getChildren(); iterator.hasNext(); stringbuffer.append((PolicyNodeImpl)iterator.next()));
+ return stringbuffer.toString();
+ }
+
+ boolean isImmutable() {
+ return isImmutable;
+ }
+
+ void setImmutable() {
+ if(isImmutable) return;
+ PolicyNodeImpl policynodeimpl;
+ for(Iterator iterator = mChildren.iterator(); iterator.hasNext(); policynodeimpl.setImmutable())
+ policynodeimpl = (PolicyNodeImpl)iterator.next();
+
+ isImmutable = true;
+ }
+
+ private void addChild(PolicyNodeImpl policynodeimpl) {
+ if(isImmutable) {
+ throw new IllegalStateException("PolicyNode is immutable");
+ } else {
+ mChildren.add(policynodeimpl);
+ return;
+ }
+ }
+
+ void addExpectedPolicy(String s) {
+ if(isImmutable)
+ throw new IllegalStateException("PolicyNode is immutable");
+ if(mOriginalExpectedPolicySet) {
+ mExpectedPolicySet.clear();
+ mOriginalExpectedPolicySet = false;
+ }
+ mExpectedPolicySet.add(s);
+ }
+
+ void prune(int i) {
+ if(isImmutable)
+ throw new IllegalStateException("PolicyNode is immutable");
+ if(mChildren.size() == 0)
+ return;
+ Iterator iterator = mChildren.iterator();
+ do {
+ if(!iterator.hasNext()) break;
+ PolicyNodeImpl policynodeimpl = (PolicyNodeImpl)iterator.next();
+ policynodeimpl.prune(i);
+ if(policynodeimpl.mChildren.size() == 0 && i > mDepth + 1)
+ iterator.remove();
+ } while(true);
+ }
+
+ void deleteChild(PolicyNode policynode) {
+ if(isImmutable) {
+ throw new IllegalStateException("PolicyNode is immutable");
+ } else {
+ mChildren.remove(policynode);
+ return;
+ }
+ }
+
+ PolicyNodeImpl copyTree() {
+ return copyTree(null);
+ }
+
+ private PolicyNodeImpl copyTree(PolicyNodeImpl policynodeimpl) {
+ PolicyNodeImpl policynodeimpl1 = new PolicyNodeImpl(policynodeimpl, this);
+ PolicyNodeImpl policynodeimpl2;
+ for(Iterator iterator = mChildren.iterator(); iterator.hasNext(); policynodeimpl2.copyTree(policynodeimpl1))
+ policynodeimpl2 = (PolicyNodeImpl)iterator.next();
+
+ return policynodeimpl1;
+ }
+
+ Set getPolicyNodes(int i) {
+ HashSet hashset = new HashSet();
+ getPolicyNodes(i, ((Set) (hashset)));
+ return hashset;
+ }
+
+ private void getPolicyNodes(int i, Set set) {
+ if(mDepth == i) {
+ set.add(this);
+ } else {
+ PolicyNodeImpl policynodeimpl;
+ for(Iterator iterator = mChildren.iterator(); iterator.hasNext(); policynodeimpl.getPolicyNodes(i, set))
+ policynodeimpl = (PolicyNodeImpl)iterator.next();
+ }
+ }
+
+ Set getPolicyNodesExpected(int i, String s, boolean flag) {
+ if(s.equals("2.5.29.32.0"))
+ return getPolicyNodes(i);
+ else
+ return getPolicyNodesExpectedHelper(i, s, flag);
+ }
+
+ private Set getPolicyNodesExpectedHelper(int i, String s, boolean flag) {
+ HashSet hashset = new HashSet();
+ if(mDepth < i) {
+ PolicyNodeImpl policynodeimpl;
+ for(Iterator iterator = mChildren.iterator(); iterator.hasNext(); hashset.addAll(policynodeimpl.getPolicyNodesExpectedHelper(i, s, flag)))
+ policynodeimpl = (PolicyNodeImpl)iterator.next();
+
+ } else if(flag) {
+ if(mExpectedPolicySet.contains("2.5.29.32.0"))
+ hashset.add(this);
+ } else if(mExpectedPolicySet.contains(s)) {
+ hashset.add(this);
+ }
+ return hashset;
+ }
+
+ Set getPolicyNodesValid(int i, String s) {
+ HashSet hashset = new HashSet();
+ if(mDepth < i) {
+ PolicyNodeImpl policynodeimpl;
+ for(Iterator iterator = mChildren.iterator(); iterator.hasNext(); hashset.addAll(policynodeimpl.getPolicyNodesValid(i, s)))
+ policynodeimpl = (PolicyNodeImpl)iterator.next();
+
+ } else if(mValidPolicy.equals(s)) {
+ hashset.add(this);
+ }
+ return hashset;
+ }
+
+ private static String policyToString(String s) {
+ if(s.equals("2.5.29.32.0")) {
+ return "anyPolicy";
+ } else {
+ return s;
+ }
+ }
+
+ String asString() {
+ if(mParent == null)
+ return "anyPolicy ROOT\n";
+ StringBuffer stringbuffer = new StringBuffer();
+ int i = 0;
+ for(int j = getDepth(); i < j; i++)
+ stringbuffer.append(" ");
+
+ stringbuffer.append(policyToString(getValidPolicy()));
+ stringbuffer.append(" CRIT: ");
+ stringbuffer.append(isCritical());
+ stringbuffer.append(" EP: ");
+ for(Iterator iterator = getExpectedPolicies().iterator(); iterator.hasNext(); stringbuffer.append(" ")) {
+ String s = (String)iterator.next();
+ stringbuffer.append(policyToString(s));
+ }
+
+ stringbuffer.append(" (");
+ stringbuffer.append(getDepth());
+ stringbuffer.append(")\n");
+ return stringbuffer.toString();
+ }
+}
diff --git a/support/src/test/java/org/apache/harmony/security/tests/support/cert/TestUtils.java b/support/src/test/java/org/apache/harmony/security/tests/support/cert/TestUtils.java index a9e565b..5d9a6bd 100644 --- a/support/src/test/java/org/apache/harmony/security/tests/support/cert/TestUtils.java +++ b/support/src/test/java/org/apache/harmony/security/tests/support/cert/TestUtils.java @@ -22,32 +22,42 @@ package org.apache.harmony.security.tests.support.cert; +import tests.support.resource.Support_Resources; + import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; -import java.io.FileNotFoundException; import java.io.IOException; +import java.math.BigInteger; import java.security.InvalidAlgorithmParameterException; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; +import java.security.cert.CertPath; +import java.security.cert.CertPathBuilder; +import java.security.cert.CertPathBuilderException; +import java.security.cert.CertPathBuilderResult; +import java.security.cert.CertPathParameters; import java.security.cert.CertPathValidatorException; import java.security.cert.CertStore; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.CollectionCertStoreParameters; +import java.security.cert.PKIXBuilderParameters; +import java.security.cert.PKIXCertPathBuilderResult; import java.security.cert.PKIXCertPathChecker; import java.security.cert.PolicyNode; +import java.security.cert.PolicyQualifierInfo; import java.security.cert.TrustAnchor; +import java.security.cert.X509CertSelector; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; -import tests.support.resource.Support_Resources; - /** * java.security.cert test utilities * @@ -80,8 +90,6 @@ public class TestUtils { * constructed using self signed test certificate * * @return <code>TrustAnchor</code> instance - * @throws CertificateException - * @throws FileNotFoundException */ public static TrustAnchor getTrustAnchor() { CertificateFactory cf = null; @@ -117,7 +125,7 @@ public class TestUtils { * containing single element (self signed test certificate). * @return Returns <code>Set</code> of <code>TrustAnchor</code>s */ - public static Set getTrustAnchorSet() { + public static Set<TrustAnchor> getTrustAnchorSet() { TrustAnchor ta = getTrustAnchor(); if (ta == null) { return null; @@ -174,7 +182,7 @@ public class TestUtils { * @throws InvalidAlgorithmParameterException * @throws NoSuchAlgorithmException */ - public static List getCollectionCertStoresList() + public static List<CertStore> getCollectionCertStoresList() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException { CertStore cs = CertStore.getInstance("Collection", @@ -196,14 +204,17 @@ public class TestUtils { return new PKIXCertPathChecker() { private boolean forward = false; + + @SuppressWarnings({"unused", "unchecked"}) public void check(Certificate arg0, Collection arg1) throws CertPathValidatorException { } - public Set getSupportedExtensions() { + public Set<String> getSupportedExtensions() { return null; } + @SuppressWarnings("unused") public void init(boolean arg0) throws CertPathValidatorException { forward = arg0; } @@ -241,7 +252,7 @@ public class TestUtils { return null; } - public Iterator getChildren() { + public Iterator<PolicyNode> getChildren() { PolicyNode child = new PolicyNode() { public int getDepth() { // child @@ -260,15 +271,15 @@ public class TestUtils { return parent; } - public Iterator getChildren() { + public Iterator<PolicyNode> getChildren() { return null; } - public Set getExpectedPolicies() { + public Set<String> getExpectedPolicies() { return null; } - public Set getPolicyQualifiers() { + public Set<? extends PolicyQualifierInfo> getPolicyQualifiers() { return null; } }; @@ -277,11 +288,11 @@ public class TestUtils { return s.iterator(); } - public Set getExpectedPolicies() { + public Set<String> getExpectedPolicies() { return null; } - public Set getPolicyQualifiers() { + public Set<? extends PolicyQualifierInfo> getPolicyQualifiers() { return null; } }; @@ -529,4 +540,267 @@ public class TestUtils { // signature: BIT STRING 0x03, 0x02, 0x00, 0x01 }; } + //-------------------------------------------------------------------------- + + // Second example + /** + * 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 + Validity + Not Before: Dec 9 16:35:30 2008 GMT + Not After : Dec 9 16:35:30 2011 GMT + Subject: C=AN, ST=Android, O=Android, OU=Android, CN=Android/emailAddress=android + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + RSA Public Key: (1024 bit) + Modulus (1024 bit): + 00:c5:fb:5e:68:37:82:1d:58:ed:cb:31:8c:08:7f: + 51:31:4c:68:40:8c:4d:07:a1:0e:18:36:02:6b:89: + 92:c1:cf:88:1e:cf:00:22:00:8c:37:e8:6a:76:94: + 71:53:81:78:e1:48:94:fa:16:61:93:eb:a0:ee:62: + 9d:6a:d2:2c:b8:77:9d:c9:36:d5:d9:1c:eb:26:3c: + 43:66:4d:7b:1c:1d:c7:a1:37:66:e2:84:54:d3:ed: + 21:dd:01:1c:ec:9b:0c:1e:35:e9:37:15:9d:2b:78: + a8:3b:11:3a:ee:c2:de:55:44:4c:bd:40:8d:e5:52: + b0:fc:53:33:73:4a:e5:d0:df + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Subject Key Identifier: + 4B:E3:22:14:AD:0A:14:46:B7:52:31:8B:AB:9E:5A:62:F3:98:37:80 + X509v3 Authority Key Identifier: + keyid:4B:E3:22:14:AD:0A:14:46:B7:52:31:8B:AB:9E:5A:62:F3:98:37:80 + DirName:/C=AN/ST=Android/O=Android/OU=Android/CN=Android/emailAddress=android + serial:00 + + X509v3 Basic Constraints: + CA:TRUE + Signature Algorithm: sha1WithRSAEncryption + 72:4f:12:8a:4e:61:b2:9a:ba:58:17:0b:55:96:f5:66:1c:a8: + ba:d1:0f:8b:9b:2d:ab:a8:00:ac:7f:99:7d:f6:0f:d7:85:eb: + 75:4b:e5:42:37:71:46:b1:4a:b0:1b:17:e4:f9:7c:9f:bd:20: + 75:35:9f:27:8e:07:95:e8:34:bd:ab:e4:10:5f:a3:7b:4c:56: + 69:d4:d0:f1:e9:74:15:2d:7f:77:f0:38:77:eb:8a:99:f3:a9: + 88:f0:63:58:07:b9:5a:61:f8:ff:11:e7:06:a1:d1:f8:85:fb: + 99:1c:f5:cb:77:86:36:cd:43:37:99:09:c2:9a:d8:f2:28:05: + 06:0c + + */ + public static final String rootCert = "-----BEGIN CERTIFICATE-----\n" + + "MIIDGzCCAoSgAwIBAgIBADANBgkqhkiG9w0BAQUFADBtMQswCQYDVQQGEwJBTjEQ\n" + + "MA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5k\n" + + "cm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEWMBQGCSqGSIb3DQEJARYHYW5kcm9pZDAe\n" + + "Fw0wODEyMDkxNjM1MzBaFw0xMTEyMDkxNjM1MzBaMG0xCzAJBgNVBAYTAkFOMRAw\n" + + "DgYDVQQIEwdBbmRyb2lkMRAwDgYDVQQKEwdBbmRyb2lkMRAwDgYDVQQLEwdBbmRy\n" + + "b2lkMRAwDgYDVQQDEwdBbmRyb2lkMRYwFAYJKoZIhvcNAQkBFgdhbmRyb2lkMIGf\n" + + "MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDF+15oN4IdWO3LMYwIf1ExTGhAjE0H\n" + + "oQ4YNgJriZLBz4gezwAiAIw36Gp2lHFTgXjhSJT6FmGT66DuYp1q0iy4d53JNtXZ\n" + + "HOsmPENmTXscHcehN2bihFTT7SHdARzsmwweNek3FZ0reKg7ETruwt5VREy9QI3l\n" + + "UrD8UzNzSuXQ3wIDAQABo4HKMIHHMB0GA1UdDgQWBBRL4yIUrQoURrdSMYurnlpi\n" + + "85g3gDCBlwYDVR0jBIGPMIGMgBRL4yIUrQoURrdSMYurnlpi85g3gKFxpG8wbTEL\n" + + "MAkGA1UEBhMCQU4xEDAOBgNVBAgTB0FuZHJvaWQxEDAOBgNVBAoTB0FuZHJvaWQx\n" + + "EDAOBgNVBAsTB0FuZHJvaWQxEDAOBgNVBAMTB0FuZHJvaWQxFjAUBgkqhkiG9w0B\n" + + "CQEWB2FuZHJvaWSCAQAwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOBgQBy\n" + + "TxKKTmGymrpYFwtVlvVmHKi60Q+Lmy2rqACsf5l99g/Xhet1S+VCN3FGsUqwGxfk\n" + + "+XyfvSB1NZ8njgeV6DS9q+QQX6N7TFZp1NDx6XQVLX938Dh364qZ86mI8GNYB7la\n" + + "Yfj/EecGodH4hfuZHPXLd4Y2zUM3mQnCmtjyKAUGDA==\n" + + "-----END CERTIFICATE-----"; + + public static final String rootPrivateKey = + "-----BEGIN RSA PRIVATE KEY-----\n" + + "Proc-Type: 4,ENCRYPTED\n" + + "DEK-Info: DES-EDE3-CBC,D9682F66FDA316E5\n" + + "\n" + + "8lGaQPlUZ/iHhdldB//xfNUrZ3RAkBthzKg+n9HBJsjztXXAZ40NGYZmgvpgnfmr\n" + + "7ZJxHxYHFc3GAmBBk9v+/dA8E5yWJa71roffWMQUuFNfGzHhGTOxvNC04W7yAajs\n" + + "CPuyI+xnAAo73F7NVTiqX3NVgu4bB8RVxJyToMe4M289oh93YvxWQ4buVTf0ErJ8\n" + + "Yc8+0ugpfXjGfRhL36qj6B1CcV7NMdXAVExrGlTf0TWT9wVbiROk4XaoaFuWh17h\n" + + "11NEDjsKQ8T4M9kRdC+tKfST8sLik1Pq6jRLIKeX8GQd7tV1IWVZ3KcQBJwu9zLq\n" + + "Hi0GTSF7IWCdwXjDyniMQiSbkmHNP+OnVyhaqew5Ooh0uOEQq/KWFewXg7B3VMr0\n" + + "l6U8sBX9ODGeW0wVdNopvl17udCkV0xm3S+MRZDnZiTlAXwKx/a/gyf5R5XYp3S0\n" + + "0eqrfy2o6Ax4hRkwcNJ2KMeLQNIiYYWKABQj5/i4TYZV6npCIXOnQEkXa9DmqyUE\n" + + "qB7eFj5FcXeqQ8ERmsLveWArsLDn2NNPdv5EaKIs2lrvwoKYeYF7hrKNpifq+QqS\n" + + "u1kN+KHjibcF42EAUozNVmkHsW8VqlywAs4MsMwxU0D57cVGWycuSedraKhc0D6j\n" + + "a4pQOWWY3ZMLoAA1ZmHG9cjDPqcJt0rqk5AhSBRmGVUccfkP7dk9KyJQizro87LI\n" + + "u7zWwMIqTfmlhyfAP0AWjrt/bMN9heGByVA55xkyCdSEVaC5gsIfmGpNy4u+wbZ9\n" + + "rSWVuTfAbjW0n0FW+CDS1LgdjXNkeAP2Uvc1QgVRCPdA23WniLFFJQ==\n" + + "-----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 + Validity + Not Before: Dec 9 16:40:35 2008 GMT + Not After : Dec 9 16:40:35 2009 GMT + Subject: C=AN, ST=Android, L=Android, O=Android, OU=Android, CN=Android Certificate/emailAddress=android + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + RSA Public Key: (1024 bit) + Modulus (1024 bit): + 00:b8:e3:de:c7:a9:40:47:2c:2a:6f:f5:2a:f4:cd: + f2:2d:40:fa:15:3f:1c:37:66:73:a5:67:4d:5b:a0: + b6:b1:dd:dc:bf:01:c7:e2:c1:48:1a:8f:1c:ce:ec: + b0:a2:55:29:9a:1b:3a:6e:cc:7b:d7:65:ae:0b:05: + 34:03:8a:af:db:f0:dc:01:80:92:03:b4:13:e5:d6: + fd:79:66:7f:c3:1a:62:d5:5e:3d:c0:19:a4:42:15: + 47:19:e6:f0:c8:b7:e2:7b:82:a2:c7:3d:df:ac:8c: + d5:bc:39:b8:e5:93:ac:3f:af:30:b7:cc:00:a8:00: + f3:38:23:b0:97:0e:92:b1:1b + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Basic Constraints: + CA:FALSE + Netscape Comment: + OpenSSL Generated Certificate + X509v3 Subject Key Identifier: + 88:4D:EC:16:26:A7:76:F5:26:43:BC:34:99:DF:D5:EA:7B:F8:5F:DE + X509v3 Authority Key Identifier: + keyid:4B:E3:22:14:AD:0A:14:46:B7:52:31:8B:AB:9E:5A:62:F3:98:37:80 + + Signature Algorithm: sha1WithRSAEncryption + 55:73:95:e6:4c:40:fc:fd:52:8a:5f:83:15:49:73:ca:f3:d8: + 5f:bb:d6:f5:2e:90:e6:7f:c3:7d:4d:27:d3:45:c6:53:9b:aa: + e3:32:99:40:b3:a9:d3:14:7d:d5:e6:a7:70:95:30:6e:dc:8c: + 7b:48:e1:98:d1:65:7a:eb:bf:b0:5c:cd:c2:eb:31:5e:b6:e9: + df:56:95:bc:eb:79:74:27:5b:6d:c8:55:63:09:d3:f9:e2:40: + ba:b4:a2:c7:2c:cb:b1:3a:c2:d8:0c:21:31:ee:68:7e:97:ce: + 98:22:2e:c6:cf:f0:1a:11:04:ca:9a:06:de:98:48:85:ac:6c: + 6f:98 + */ + public static final String endCert = + "-----BEGIN CERTIFICATE-----\n" + + "MIIC6jCCAlOgAwIBAgIBATANBgkqhkiG9w0BAQUFADBtMQswCQYDVQQGEwJBTjEQ\n" + + "MA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5k\n" + + "cm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEWMBQGCSqGSIb3DQEJARYHYW5kcm9pZDAe\n" + + "Fw0wODEyMDkxNjQwMzVaFw0wOTEyMDkxNjQwMzVaMIGLMQswCQYDVQQGEwJBTjEQ\n" + + "MA4GA1UECBMHQW5kcm9pZDEQMA4GA1UEBxMHQW5kcm9pZDEQMA4GA1UEChMHQW5k\n" + + "cm9pZDEQMA4GA1UECxMHQW5kcm9pZDEcMBoGA1UEAxMTQW5kcm9pZCBDZXJ0aWZp\n" + + "Y2F0ZTEWMBQGCSqGSIb3DQEJARYHYW5kcm9pZDCBnzANBgkqhkiG9w0BAQEFAAOB\n" + + "jQAwgYkCgYEAuOPex6lARywqb/Uq9M3yLUD6FT8cN2ZzpWdNW6C2sd3cvwHH4sFI\n" + + "Go8czuywolUpmhs6bsx712WuCwU0A4qv2/DcAYCSA7QT5db9eWZ/wxpi1V49wBmk\n" + + "QhVHGebwyLfie4Kixz3frIzVvDm45ZOsP68wt8wAqADzOCOwlw6SsRsCAwEAAaN7\n" + + "MHkwCQYDVR0TBAIwADAsBglghkgBhvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQg\n" + + "Q2VydGlmaWNhdGUwHQYDVR0OBBYEFIhN7BYmp3b1JkO8NJnf1ep7+F/eMB8GA1Ud\n" + + "IwQYMBaAFEvjIhStChRGt1Ixi6ueWmLzmDeAMA0GCSqGSIb3DQEBBQUAA4GBAFVz\n" + + "leZMQPz9UopfgxVJc8rz2F+71vUukOZ/w31NJ9NFxlObquMymUCzqdMUfdXmp3CV\n" + + "MG7cjHtI4ZjRZXrrv7BczcLrMV626d9WlbzreXQnW23IVWMJ0/niQLq0oscsy7E6\n" + + "wtgMITHuaH6XzpgiLsbP8BoRBMqaBt6YSIWsbG+Y\n" + + "-----END CERTIFICATE-----"; + + public static final String endPrivateKey = + "-----BEGIN RSA PRIVATE KEY-----\n" + + "Proc-Type: 4,ENCRYPTED\n" + + "DEK-Info: DES-EDE3-CBC,E20AAB000D1D90B1\n" + + "\n" + + "cWrCb6eHuwb6/gnbX12Va47qSpFW0j99Lq2eEj0fqLdlwA6+KvD3/U+Nj4ldaAQ4\n" + + "rYryQv0MJu/kT9z/mJbBI4NwunX/9vXttyuh8s07sv8AqdHCylYR9miz61Q0LkLR\n" + + "9H9D8NWMgMnuVhlj+NUXlkF+Jfriu5xkIqeYDhN8c3/AMawQoNdW/pWmgz0BfFIP\n" + + "DUxszfXHx5mfSMoRdC2YZGlFdsONSO7s14Ayz8+pKD0PzSARXtTEJ5+mELCnhFsw\n" + + "R7zYYwD+9WjL702bjYQxwRS5Sk1Z/VAxLFfjdtlUFSi6VLGIG+jUnM1RF91KtJY1\n" + + "bJOQrlHw9/wyH75y9sXUrVpil4qH9shILHgu4A0VaL7IpIFjWS9vPY7SvwqRlbk7\n" + + "QPhxoIpiNzjzjEa7PG6nSqy8mRzJP0OLWzRUoMWJn6ntf+oj7CzaaIgFrrwRGOCQ\n" + + "BYibTTMZ/paxKDvZ9Lcl8a6uRvi2II2/F63bPcTcILsKDsBdQp93Evanw1QKXdGi\n" + + "jb4b0Y1LYZM0jl7z2TSBZ27HyHKp4jMQP9q9mujEKInjzSB+gsRGfP6++OilrR2U\n" + + "Y7kN2o/ufnPHltel0pUWOHr45IyK8zowgXWtKVl9U+VRwr2thGbdqkRGk55KjJK4\n" + + "Q+OfwvIKHgvn/4cN/BGIA/52eyY//bTFk6ePGY2vlQK4mvB7MeSxtxoCGxdCYQru\n" + + "wI28rOHyQ1cdx141yxlKVSIcxBVZHm8sfh9PHeKMKuaOgc8kfx+Qh8IghFHyJ+yg\n" + + "PboNF9/PiM/glaaBzY2OKTYQKY6LiTetZiI6RdLE7Y+SFwG7Wwo5dg==\n" + + "-----END RSA PRIVATE KEY-----"; + + /** + * a self signed certificate + */ + public static X509Certificate rootCertificateSS; + + public static X509Certificate endCertificate; + + public static MyCRL crl; + + public static X509CertSelector theCertSelector; + + public static CertPathBuilder builder; + private static CertStore store; + + public static void initCertPathSSCertChain() throws CertificateException, + InvalidAlgorithmParameterException, NoSuchAlgorithmException, + IOException { + // create certificates and CRLs + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + ByteArrayInputStream bi = new ByteArrayInputStream(rootCert.getBytes()); + rootCertificateSS = (X509Certificate) cf.generateCertificate(bi); + bi = new ByteArrayInputStream(endCert.getBytes()); + endCertificate = (X509Certificate) cf.generateCertificate(bi); + + BigInteger revokedSerialNumber = BigInteger.valueOf(1); + crl = new MyCRL("X.509"); +// X509CRL rootCRL = X509CRL; +// X509CRL interCRL = X509CRLExample.createCRL(interCert, interPair +// .getPrivate(), revokedSerialNumber); + + // create CertStore to support path building + List<Object> list = new ArrayList<Object>(); + + list.add(rootCertificateSS); + list.add(endCertificate); + + CollectionCertStoreParameters params = new CollectionCertStoreParameters( + list); + store = CertStore.getInstance("Collection", params); + + theCertSelector = new X509CertSelector(); + theCertSelector.setCertificate(endCertificate); + theCertSelector.setIssuer(endCertificate.getIssuerX500Principal() + .getEncoded()); + + // build the path + builder = CertPathBuilder.getInstance("PKIX"); + + } + + public static CertPathBuilder getCertPathBuilder() { + if (builder == null) { + throw new RuntimeException( + "Call initCertPathSSCertChain prior to buildCertPath"); + } + return builder; + } + + public static CertPath buildCertPathSSCertChain() + throws InvalidAlgorithmParameterException { + + CertPathBuilderResult result; + CertPathParameters buildParams = getCertPathParameters(); + try { + result = builder.build(buildParams); + } catch (CertPathBuilderException e) { + return null; + } + return result.getCertPath(); + } + + public static CertPathParameters getCertPathParameters() + throws InvalidAlgorithmParameterException { + if ((rootCertificateSS == null) || (theCertSelector == null) + || (builder == null)) { + throw new RuntimeException( + "Call initCertPathSSCertChain prior to buildCertPath"); + } + PKIXCertPathBuilderResult result = null; + PKIXBuilderParameters buildParams = new PKIXBuilderParameters( + Collections.singleton(new TrustAnchor(rootCertificateSS, null)), + theCertSelector); + + buildParams.addCertStore(store); + buildParams.setRevocationEnabled(false); + + return buildParams; + + } } diff --git a/support/src/test/java/org/apache/harmony/security/tests/support/interfaces/DSAKeyPairGeneratorImpl.java b/support/src/test/java/org/apache/harmony/security/tests/support/interfaces/DSAKeyPairGeneratorImpl.java new file mode 100644 index 0000000..51c2fcc --- /dev/null +++ b/support/src/test/java/org/apache/harmony/security/tests/support/interfaces/DSAKeyPairGeneratorImpl.java @@ -0,0 +1,84 @@ +/* + * 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.security.tests.support.interfaces; + +import java.security.interfaces.DSAKeyPairGenerator; +import java.security.KeyPairGenerator; +import java.security.SecureRandom; +import java.security.interfaces.DSAParams; +import java.security.InvalidParameterException; + +/** + * Additional class for verification DSAKeyPairGenerator interface + */ +public class DSAKeyPairGeneratorImpl implements DSAKeyPairGenerator { + + private KeyPairGenerator dsaKeyPairGenerator = null; + private SecureRandom secureRandom = null; + private DSAParams dsaParams = null; + private int lengthModulus = 0; + + public DSAKeyPairGeneratorImpl(DSAParams dsap) { + dsaKeyPairGenerator = null; + try { + dsaKeyPairGenerator = KeyPairGenerator.getInstance("DSA"); + } catch (Exception e) { + dsaKeyPairGenerator = null; + } + dsaParams = dsap; + } + + public void initialize(DSAParams params, SecureRandom random) + throws InvalidParameterException { + if (random == null) { + throw new InvalidParameterException("Incorrect random"); + } + if (params == null) { + throw new InvalidParameterException("Incorrect params"); + } + secureRandom = random; + dsaParams = params; + + } + + public void initialize(int modlen, boolean genParams, SecureRandom random) + throws InvalidParameterException { + int len = 512; + while (len <= 1024) { + if (len == modlen) { + lengthModulus = modlen; + break; + } else { + len = len + 8; + if (len == 1032) { + throw new InvalidParameterException("Incorrect modlen"); + } + } + } + if (modlen < 512 || modlen > 1024) { + throw new InvalidParameterException("Incorrect modlen"); + } + if (random == null) { + throw new InvalidParameterException("Incorrect random"); + } + if (genParams == false && dsaParams == null) { + throw new InvalidParameterException("there are not precomputed parameters"); + } + secureRandom = random; + } +} diff --git a/support/src/test/java/org/apache/harmony/security/tests/support/interfaces/RSAMultiPrimePrivateCrtKeyImpl.java b/support/src/test/java/org/apache/harmony/security/tests/support/interfaces/RSAMultiPrimePrivateCrtKeyImpl.java new file mode 100644 index 0000000..f3a8543 --- /dev/null +++ b/support/src/test/java/org/apache/harmony/security/tests/support/interfaces/RSAMultiPrimePrivateCrtKeyImpl.java @@ -0,0 +1,92 @@ +/* + * 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.security.tests.support.interfaces; + +import java.security.interfaces.RSAMultiPrimePrivateCrtKey; +import java.math.BigInteger; +import java.security.spec.RSAOtherPrimeInfo; + +/** + * Additional class for verification RSAMultiPrimePrivateCrtKey interface + */ +public class RSAMultiPrimePrivateCrtKeyImpl implements RSAMultiPrimePrivateCrtKey { + + static final long serialVersionUID = 123; + + private BigInteger crtCoefficient = null; + private BigInteger publicExponent = null; + private BigInteger primeExponentP = null; + private BigInteger primeExponentQ = null; + private BigInteger primeP = null; + private BigInteger primeQ = null; + private RSAOtherPrimeInfo[] otherPrimeInfo = null; + + public RSAMultiPrimePrivateCrtKeyImpl(BigInteger publicExp, + BigInteger primeExpP, + BigInteger primeExpQ, + BigInteger prP, + BigInteger prQ, + BigInteger crtCft, + RSAOtherPrimeInfo[] otherPrmInfo) { + publicExponent = publicExp; + primeExponentP = primeExpP; + primeExponentQ = primeExpQ; + primeP = prP; + primeQ = prQ; + crtCoefficient = crtCft; + otherPrimeInfo = otherPrmInfo; + } + + public BigInteger getCrtCoefficient() { + return crtCoefficient; + } + public RSAOtherPrimeInfo[] getOtherPrimeInfo() { + return otherPrimeInfo; + } + public BigInteger getPrimeExponentP() { + return primeExponentP; + } + public BigInteger getPrimeExponentQ() { + return primeExponentQ; + } + public BigInteger getPrimeP() { + return primeP; + } + public BigInteger getPrimeQ() { + return primeQ; + } + public BigInteger getPublicExponent() { + return publicExponent; + } + + public BigInteger getPrivateExponent() { + return null; + } + public String getFormat() { + return null; + } + public byte[] getEncoded() { + return null; + } + public String getAlgorithm() { + return null; + } + public BigInteger getModulus() { + return null; + } +}
\ No newline at end of file diff --git a/support/src/test/java/org/apache/harmony/security/tests/support/resource/Support_Resources.java b/support/src/test/java/org/apache/harmony/security/tests/support/resource/Support_Resources.java deleted file mode 100644 index 112b9e9..0000000 --- a/support/src/test/java/org/apache/harmony/security/tests/support/resource/Support_Resources.java +++ /dev/null @@ -1,177 +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.security.tests.support.resource; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URISyntaxException; -import java.net.URL; - -import org.apache.harmony.security.tests.support.Support_Configuration; - -public class Support_Resources { - - public static final String RESOURCE_PACKAGE = "/tests/resources/"; - - public static final String RESOURCE_PACKAGE_NAME = "tests.resources"; - - public static InputStream getStream(String name) { - return Support_Resources.class.getResourceAsStream(RESOURCE_PACKAGE - + name); - } - - public static String getURL(String name) { - String folder = null; - String fileName = name; - File resources = createTempFolder(); - int index = name.lastIndexOf("/"); - if (index != -1) { - folder = name.substring(0, index); - name = name.substring(index + 1); - } - copyFile(resources, folder, name); - URL url = null; - String resPath = resources.toString(); - if (resPath.charAt(0) == '/' || resPath.charAt(0) == '\\') { - resPath = resPath.substring(1); - } - try { - url = new URL("file:/" + resPath + "/" + fileName); - } catch (MalformedURLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return url.toString(); - } - - public static File createTempFolder() { - - File folder = null; - try { - folder = File.createTempFile("hyts_resources", "", null); - folder.delete(); - folder.mkdirs(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - folder.deleteOnExit(); - return folder; - } - - public static void copyFile(File root, String folder, String file) { - File f; - if (folder != null) { - f = new File(root.toString() + "/" + folder); - if (!f.exists()) { - f.mkdirs(); - f.deleteOnExit(); - } - } else { - f = root; - } - - File dest = new File(f.toString() + "/" + file); - - InputStream in = Support_Resources.getStream(folder == null ? file - : folder + "/" + file); - try { - copyLocalFileto(dest, in); - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - public static File createTempFile(String suffix) throws IOException { - return File.createTempFile("hyts_", suffix, null); - } - - public static void copyLocalFileto(File dest, InputStream in) - throws FileNotFoundException, IOException { - if (!dest.exists()) { - FileOutputStream out = new FileOutputStream(dest); - int result; - byte[] buf = new byte[4096]; - while ((result = in.read(buf)) != -1) { - out.write(buf, 0, result); - } - in.close(); - out.close(); - dest.deleteOnExit(); - } - } - - public static File getExternalLocalFile(String url) throws IOException, - MalformedURLException { - File resources = createTempFolder(); - InputStream in = new URL(url).openStream(); - File temp = new File(resources.toString() + "/local.tmp"); - copyLocalFileto(temp, in); - return temp; - } - - public static String getResourceURL(String resource) { - return "http://" + Support_Configuration.TestResources + resource; - } - - /** - * Util method to load resource files - * - * @param name - name of resource file - * @return - resource input stream - */ - public static InputStream getResourceStream(String name) { - - InputStream is = ClassLoader.getSystemClassLoader() - .getResourceAsStream(name); - - if (is == null) { - throw new RuntimeException("Failed to load resource: " + name); - } - - return is; - } - - /** - * Util method to get absolute path to resource file - * - * @param name - name of resource file - * @return - path to resource - */ - public static String getAbsoluteResourcePath(String name) { - - URL url = ClassLoader.getSystemClassLoader().getResource(name); - if (url == null) { - throw new RuntimeException("Failed to load resource: " + name); - } - - try { - return new File(url.toURI()).getAbsolutePath(); - } catch (URISyntaxException e) { - throw new RuntimeException("Failed to load resource: " + name); - } - } -} diff --git a/support/src/test/java/org/apache/harmony/testframework/serialization/SerializationTest.java b/support/src/test/java/org/apache/harmony/testframework/serialization/SerializationTest.java index 7e4797d..9db5382 100644 --- a/support/src/test/java/org/apache/harmony/testframework/serialization/SerializationTest.java +++ b/support/src/test/java/org/apache/harmony/testframework/serialization/SerializationTest.java @@ -22,7 +22,10 @@ package org.apache.harmony.testframework.serialization; +import dalvik.annotation.BrokenTest; +import dalvik.annotation.TestLevel; import dalvik.annotation.TestTargetClass; +import dalvik.annotation.TestTargetNew; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -130,6 +133,12 @@ public abstract class SerializationTest extends TestCase { * exceptions, and that deserialization really produces deeply cloned * objects. */ + @TestTargetNew( + level = TestLevel.ADDITIONAL, + notes = "", + method = "!Serialization", + args = {} + ) public void testSelf() throws Throwable { if (this instanceof SerializableAssert) { @@ -142,8 +151,15 @@ public abstract class SerializationTest extends TestCase { /** * Tests that data objects can be deserialized from golden files, to verify - * compartibility with Reference Implementation. + * compatibility with Reference Implementation. */ + + @TestTargetNew( + level = TestLevel.ADDITIONAL, + notes = "", + method = "!Serialization", + args = {} + ) public void testGolden() throws Throwable { verifyGolden(this, getData()); diff --git a/support/src/test/java/org/apache/harmony/xnet/tests/support/KeyManagerFactorySpiImpl.java b/support/src/test/java/org/apache/harmony/xnet/tests/support/KeyManagerFactorySpiImpl.java new file mode 100644 index 0000000..b8e3ee0 --- /dev/null +++ b/support/src/test/java/org/apache/harmony/xnet/tests/support/KeyManagerFactorySpiImpl.java @@ -0,0 +1,49 @@ +package org.apache.harmony.xnet.tests.support; + +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.ManagerFactoryParameters; + +public class KeyManagerFactorySpiImpl extends MyKeyManagerFactorySpi { + + private boolean isInitialized = false; + + public void engineInit(KeyStore ks, char[] password) + throws KeyStoreException, NoSuchAlgorithmException, + UnrecoverableKeyException { + + if (ks == null && password == null) { + throw new NoSuchAlgorithmException(); + } + + if (ks == null) { + throw new KeyStoreException(); + } + + if (password == null) { + throw new UnrecoverableKeyException(); + } + + isInitialized = true; + } + + public void engineInit(ManagerFactoryParameters spec) + throws InvalidAlgorithmParameterException { + if (spec == null) { + throw new InvalidAlgorithmParameterException("Incorrect parameter"); + } + isInitialized = true; + } + + public KeyManager[] engineGetKeyManagers() { + if(!isInitialized) + throw new IllegalStateException("KeyManagerFactoryImpl is not initialized"); + else + return null; + } +} diff --git a/support/src/test/java/org/apache/harmony/xnet/tests/support/MySSLContextSpi.java b/support/src/test/java/org/apache/harmony/xnet/tests/support/MySSLContextSpi.java index fcf1d92..a87e75d 100644 --- a/support/src/test/java/org/apache/harmony/xnet/tests/support/MySSLContextSpi.java +++ b/support/src/test/java/org/apache/harmony/xnet/tests/support/MySSLContextSpi.java @@ -52,7 +52,7 @@ public class MySSLContextSpi extends SSLContextSpi { protected SSLSocketFactory engineGetSocketFactory() { if (!init) { throw new RuntimeException("Not initialiazed"); - }; + } return null; } @@ -118,7 +118,7 @@ public class MySSLContextSpi extends SSLContextSpi { public String[] getEnabledCipherSuites() { return null; } public String[] getEnabledProtocols() {return null; } public boolean getEnableSessionCreation() { return true; } - public SSLEngineResult.HandshakeStatus getHandshakeStatus() { return null; }; + public SSLEngineResult.HandshakeStatus getHandshakeStatus() { return null; } public boolean getNeedClientAuth() { return true; } public SSLSession getSession() { return null; } public String[] getSupportedCipherSuites() { return null; } diff --git a/support/src/test/java/org/apache/harmony/xnet/tests/support/SSLContextSpiImpl.java b/support/src/test/java/org/apache/harmony/xnet/tests/support/SSLContextSpiImpl.java new file mode 100644 index 0000000..fa463d5 --- /dev/null +++ b/support/src/test/java/org/apache/harmony/xnet/tests/support/SSLContextSpiImpl.java @@ -0,0 +1,81 @@ +package org.apache.harmony.xnet.tests.support; + +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.SSLEngineResult; +import javax.net.ssl.SSLException; +import javax.net.ssl.SSLSession;*/ +import javax.net.ssl.SSLSessionContext; +import javax.net.ssl.SSLServerSocketFactory; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; + +public class SSLContextSpiImpl extends MySSLContextSpi { + + private boolean init = false; + + public void engineInit(KeyManager[] km, TrustManager[] tm, + SecureRandom sr) throws KeyManagementException { + if (sr == null) { + throw new KeyManagementException( + "secureRandom is null"); + } + init = true; + } + + public SSLSocketFactory engineGetSocketFactory() { + if (!init) { + throw new RuntimeException("Not initialiazed"); + } + return null; + } + + public SSLServerSocketFactory engineGetServerSocketFactory() { + if (!init) { + throw new RuntimeException("Not initialiazed"); + } + return null; + } + + public SSLSessionContext engineGetServerSessionContext() { + if (!init) { + throw new RuntimeException("Not initialiazed"); + } + return null; + } + + public SSLSessionContext engineGetClientSessionContext() { + if (!init) { + throw new RuntimeException("Not initialiazed"); + } + return null; + } + + /* + * FIXME: add these methods + */ + public SSLEngine engineCreateSSLEngine(String host, int port) { + int max = 65535; + + if (port < 0 || port > max) { + throw new IllegalArgumentException("Illegal port"); + } + + if (!init) { + throw new RuntimeException("Not initialiazed"); + } + return new tmpSSLEngine(host, port); + } + + public SSLEngine engineCreateSSLEngine() { + if (!init) { + throw new RuntimeException("Not initialiazed"); + } + return new tmpSSLEngine(); + } +} + diff --git a/support/src/test/java/org/apache/harmony/xnet/tests/support/SSLSessionContextImpl.java b/support/src/test/java/org/apache/harmony/xnet/tests/support/SSLSessionContextImpl.java new file mode 100644 index 0000000..c8d35e4 --- /dev/null +++ b/support/src/test/java/org/apache/harmony/xnet/tests/support/SSLSessionContextImpl.java @@ -0,0 +1,52 @@ +package org.apache.harmony.xnet.tests.support; + +import java.util.*; +import javax.net.ssl.SSLSession; +import javax.net.ssl.SSLSessionContext; + +public class SSLSessionContextImpl implements SSLSessionContext { + + private int cashSize; + private long sessionTimeout; + + public SSLSessionContextImpl() { + cashSize = 0; + sessionTimeout = 0; + } + + public int getSessionCacheSize() { + return cashSize; + } + + public void setSessionCacheSize(int newSize) throws IllegalArgumentException { + if(newSize < 0) throw new IllegalArgumentException(); + if (newSize < cashSize) { + System.out.println("<--- Number of sessions will be changed"); + } + cashSize = newSize; + } + + public int getSessionTimeout() + { + return (int)(sessionTimeout / 1000L); + } + + public void setSessionTimeout(int seconds) throws IllegalArgumentException { + if(seconds < 0) { + throw new IllegalArgumentException(); + } else { + sessionTimeout = (long)seconds * 1000L; + } + } + + public SSLSession getSession(byte abyte0[]) + { + return null; + } + + public Enumeration getIds() + { + return null; + } + +} diff --git a/support/src/test/java/org/apache/harmony/xnet/tests/support/SSLSocketFactoryImpl.java b/support/src/test/java/org/apache/harmony/xnet/tests/support/SSLSocketFactoryImpl.java new file mode 100644 index 0000000..18a9c96 --- /dev/null +++ b/support/src/test/java/org/apache/harmony/xnet/tests/support/SSLSocketFactoryImpl.java @@ -0,0 +1,81 @@ +package org.apache.harmony.xnet.tests.support; + +import javax.net.ssl.SSLSocketFactory; + +import java.net.InetAddress; +import java.net.Socket; +import java.io.IOException; +import java.net.UnknownHostException; + + +public class SSLSocketFactoryImpl extends SSLSocketFactory { + + public SSLSocketFactoryImpl() { + super(); + } + + public Socket createSocket(Socket socket, String s, int i, boolean flag) + throws IOException { + if (socket == null) { + throw new IOException("incorrect socket"); + } + if (i < 0 || i > 65535) { + throw new IOException("incorrect port"); + } + if (s == null || s.equals("")) { + throw new UnknownHostException("incorrect host"); + } + + if (!flag) { + socket = new Socket(s, i); + } else { + socket = new Socket(s, i); + socket.close(); + } + return socket; + } + + public String[] getDefaultCipherSuites() { + return null; + } + + public String[] getSupportedCipherSuites() { + return null; + } + + /** + * @see javax.net.SocketFactory#createSocket(java.lang.String, int) + */ + @Override + public Socket createSocket(String arg0, int arg1) throws IOException, UnknownHostException { + // it is a fake + return null; + } + + /** + * @see javax.net.SocketFactory#createSocket(java.net.InetAddress, int) + */ + @Override + public Socket createSocket(InetAddress arg0, int arg1) throws IOException { + // it is a fake + return null; + } + + /** + * @see javax.net.SocketFactory#createSocket(java.lang.String, int, java.net.InetAddress, int) + */ + @Override + public Socket createSocket(String arg0, int arg1, InetAddress arg2, int arg3) throws IOException, UnknownHostException { + // it is a fake + return null; + } + + /** + * @see javax.net.SocketFactory#createSocket(java.net.InetAddress, int, java.net.InetAddress, int) + */ + @Override + public Socket createSocket(InetAddress arg0, int arg1, InetAddress arg2, int arg3) throws IOException { + // it is a fake + return null; + } +} diff --git a/support/src/test/java/org/apache/harmony/xnet/tests/support/TrustManagerFactorySpiImpl.java b/support/src/test/java/org/apache/harmony/xnet/tests/support/TrustManagerFactorySpiImpl.java new file mode 100644 index 0000000..068440d --- /dev/null +++ b/support/src/test/java/org/apache/harmony/xnet/tests/support/TrustManagerFactorySpiImpl.java @@ -0,0 +1,44 @@ +package org.apache.harmony.xnet.tests.support; + +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyStore; +import java.security.KeyStoreException; + +import javax.net.ssl.ManagerFactoryParameters; +import javax.net.ssl.TrustManager; + +public class TrustManagerFactorySpiImpl extends MyTrustManagerFactorySpi { + + private boolean isInitialized = false; + + public void engineInit(KeyStore ks) throws KeyStoreException { + if (ks == null) { + throw new KeyStoreException("Not supported operation for null KeyStore"); + } + isInitialized = true; + } + + public void engineInit(ManagerFactoryParameters spec) throws InvalidAlgorithmParameterException { + if (spec == null) { + throw new InvalidAlgorithmParameterException("Null parameter"); + } + if (spec instanceof Parameters) { + try { + engineInit(((Parameters)spec).getKeyStore()); + } catch (KeyStoreException e) { + throw new RuntimeException(e); + } + } else { + throw new InvalidAlgorithmParameterException("Invalid parameter"); + } + isInitialized = true; + } + + public TrustManager[] engineGetTrustManagers() { + if(!isInitialized) + throw new IllegalStateException("TrustManagerFactorySpi is not initialized"); + else + return null; + } + +} diff --git a/support/src/test/java/org/apache/harmony/xnet/tests/support/X509KeyManagerImpl.java b/support/src/test/java/org/apache/harmony/xnet/tests/support/X509KeyManagerImpl.java new file mode 100644 index 0000000..c679b01 --- /dev/null +++ b/support/src/test/java/org/apache/harmony/xnet/tests/support/X509KeyManagerImpl.java @@ -0,0 +1,223 @@ +package org.apache.harmony.xnet.tests.support; + +import java.io.ByteArrayInputStream; +import java.security.KeyStore; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.security.cert.Certificate; +import java.util.Enumeration; +import java.util.Vector; +import java.security.Principal; +import java.security.PrivateKey; +import java.net.Socket; + +import javax.net.ssl.X509KeyManager; + +public class X509KeyManagerImpl implements X509KeyManager { + + private String keyType; + private String client = "CLIENT"; + private String server = "SERVER"; + private KeyStore keyTest; + private X509Certificate[] cert = null; + + // creating a certificate + 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"; + + ByteArrayInputStream certArray = new ByteArrayInputStream(certificate + .getBytes()); + + String certificate2 = "-----BEGIN CERTIFICATE-----\n" + + "MIICZzCCAdCgAwIBAgIBGzANBgkqhkiG9w0BAQUFADBhMQswCQYDVQQGEwJVUzEY\n" + + "MBYGA1UEChMPVS5TLiBHb3Zlcm5tZW50MQwwCgYDVQQLEwNEb0QxDDAKBgNVBAsT\n" + + "A1BLSTEcMBoGA1UEAxMTRG9EIFBLSSBNZWQgUm9vdCBDQTAeFw05ODA4MDMyMjAy\n" + + "MjlaFw0wODA4MDQyMjAyMjlaMGExCzAJBgNVBAYTAlVTMRgwFgYDVQQKEw9VLlMu\n" + + "IEdvdmVybm1lbnQxDDAKBgNVBAsTA0RvRDEMMAoGA1UECxMDUEtJMRwwGgYDVQQD\n" + + "ExNEb0QgUEtJIE1lZCBSb290IENBMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB\n" + + "gQDbrM/J9FrJSX+zxFUbsI9Vw5QbguVBIa95rwW/0M8+sM0r5gd+DY6iubm6wnXk\n" + + "CSvbfQlFEDSKr4WYeeGp+d9WlDnQdtDFLdA45tCi5SHjnW+hGAmZnld0rz6wQekF\n" + + "5xQaa5A6wjhMlLOjbh27zyscrorMJ1O5FBOWnEHcRv6xqQIDAQABoy8wLTAdBgNV\n" + + "HQ4EFgQUVrmYR6m9701cHQ3r5kXyG7zsCN0wDAYDVR0TBAUwAwEB/zANBgkqhkiG\n" + + "9w0BAQUFAAOBgQDVX1Y0YqC7vekeZjVxtyuC8Mnxbrz6D109AX07LEIRzNYzwZ0w\n" + + "MTImSp9sEzWW+3FueBIU7AxGys2O7X0qmN3zgszPfSiocBuQuXIYQctJhKjF5KVc\n" + + "VGQRYYlt+myhl2vy6yPzEVCjiKwMEb1Spu0irCf+lFW2hsdjvmSQMtZvOw==\n" + + "-----END CERTIFICATE-----\n"; + + ByteArrayInputStream certArray2 = new ByteArrayInputStream(certificate2 + .getBytes()); + + String certificate3 = "-----BEGIN CERTIFICATE-----\n" + + "MIIDXDCCAsWgAwIBAgIBSjANBgkqhkiG9w0BAQUFADBWMQswCQYDVQQGEwJVUzEY\n" + + "MBYGA1UEChMPVS5TLiBHb3Zlcm5tZW50MQwwCgYDVQQLEwNEb0QxDDAKBgNVBAsT\n" + + "A1BLSTERMA8GA1UEAxMITWVkIENBLTEwHhcNOTgwODAyMTgwMjQwWhcNMDEwODAy\n" + + "MTgwMjQwWjB0MQswCQYDVQQGEwJVUzEYMBYGA1UEChMPVS5TLiBHb3Zlcm5tZW50\n" + + "MQwwCgYDVQQLEwNEb0QxDDAKBgNVBAsTA1BLSTENMAsGA1UECxMEVVNBRjEgMB4G\n" + + "A1UEAxMXR3VtYnkuSm9zZXBoLjAwMDAwMDUwNDQwgZ8wDQYJKoZIhvcNAQEBBQAD\n" + + "gY0AMIGJAoGBALT/R7bPqs1c1YqXAg5HNpZLgW2HuAc7RCaP06cE4R44GBLw/fQc\n" + + "VRNLn5pgbTXsDnjiZVd8qEgYqjKFQka4/tNhaF7No2tBZB+oYL/eP0IWtP+h/W6D\n" + + "KR5+UvIIdgmx7k3t9jp2Q51JpHhhKEb9WN54trCO9Yu7PYU+LI85jEIBAgMBAAGj\n" + + "ggEaMIIBFjAWBgNVHSAEDzANMAsGCWCGSAFlAgELAzAfBgNVHSMEGDAWgBQzOhTo\n" + + "CWdhiGUkIOx5cELXppMe9jAdBgNVHQ4EFgQUkLBJl+ayKgzOp/wwBX9M1lSkCg4w\n" + + "DgYDVR0PAQH/BAQDAgbAMAwGA1UdEwEB/wQCMAAwgZ0GA1UdHwSBlTCBkjCBj6CB\n" + + "jKCBiYaBhmxkYXA6Ly9kcy0xLmNoYW1iLmRpc2EubWlsL2NuJTNkTWVkJTIwQ0El\n" + + "MmQxJTJjb3UlM2RQS0klMmNvdSUzZERvRCUyY28lM2RVLlMuJTIwR292ZXJubWVu\n" + + "dCUyY2MlM2RVUz9jZXJ0aWZpY2F0ZVJldm9jYXRpb25MaXN0JTNiYmluYXJ5MA0G\n" + + "CSqGSIb3DQEBBQUAA4GBAFjapuDHMvIdUeYRyEYdShBR1JZC20tJ3MQnyBQveddz\n" + + "LGFDGpIkRAQU7T/5/ne8lMexyxViC21xOlK9LdbJCbVyywvb9uEm/1je9wieQQtr\n" + + "kjykuB+WB6qTCIslAO/eUmgzfzIENvnH8O+fH7QTr2PdkFkiPIqBJYHvw7F3XDqy\n" + + "-----END CERTIFICATE-----\n"; + + ByteArrayInputStream certArray3 = new ByteArrayInputStream(certificate3 + .getBytes()); + + + public X509KeyManagerImpl(String name) { + keyType = name; + try { + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + keyTest = KeyStore.getInstance(KeyStore.getDefaultType()); + keyTest.load(null, null); + if (keyType.equals(client)) { + cert = new X509Certificate[2]; + cert[0] = (X509Certificate) cf.generateCertificate(certArray); + cert[1] = (X509Certificate) cf.generateCertificate(certArray2); + //keyTest = KeyStore.getInstance(KeyStore.getDefaultType()); + //keyTest.load(null, null); + keyTest.setCertificateEntry("clientAlias_01", cert[0]); + keyTest.setCertificateEntry("clientAlias_02", cert[0]); + keyTest.setCertificateEntry("clientAlias_03", cert[1]); + } else if (keyType.equals(server)) { + //CertificateFactory cf = CertificateFactory.getInstance("X.509"); + cert = new X509Certificate[1]; + cert[0] = (X509Certificate) cf.generateCertificate(certArray3); + //keyTest = KeyStore.getInstance(KeyStore.getDefaultType()); + //keyTest.load(null, null); + keyTest.setCertificateEntry("serverAlias_00", cert[0]); + } + } catch (Exception ex) { + throw new IllegalArgumentException(ex.getMessage()); + } + } + + public String[] getClientAliases(String s, Principal[] aprincipal) { + if (s == null || s.equals("")) { + return null; + } + try { + if (s.equals(client)) { + Enumeration<String> aliase = keyTest.aliases(); + Vector vec = new Vector(); + int i = 0; + while (aliase.hasMoreElements()) { + vec.addElement(aliase.nextElement()); + i++; + } + String[] res = new String[vec.size()]; + for (i = 0; i < vec.size(); i++) { + res[i] = vec.elementAt(i).toString(); + } + return res; + } else return null; + } catch (Exception ex) { + throw new IllegalArgumentException(ex.getMessage()); + } + } + + public String chooseClientAlias(String[] as, Principal[] aprincipal, Socket socket) { + String alias = null; + if (as == null || as.length == 0) { + return null; + } + try { + if (as.length == 1 && as[0].equals(client)) { + if (socket == null) { + alias = keyTest.getCertificateAlias(cert[0]); + } else { + alias = keyTest.getCertificateAlias(cert[1]); + } + return alias; + } + } catch (Exception ex) { + throw new IllegalArgumentException(ex.getMessage()); + } + return null; + } + + public String[] getServerAliases(String s, Principal aprincipal[]) { + if (s == null || s.equals("")) { + return null; + } + try { + if (s.equals(server)) { + Enumeration<String> aliase = keyTest.aliases(); + Vector vec = new Vector(); + int i = 0; + while (aliase.hasMoreElements()) { + vec.addElement(aliase.nextElement()); + i++; + } + String[] res = new String[vec.size()]; + for (i = 0; i < vec.size(); i++) { + res[i] = vec.elementAt(i).toString(); + } + return res; + } else return null; + } catch (Exception ex) { + throw new IllegalArgumentException(ex.getMessage()); + } + } + + public String chooseServerAlias(String as, Principal[] aprincipal, Socket socket) { + String alias = null; + if (as == null || as.equals("")) { + return null; + } + try { + if (as.equals(server) && socket != null) { + return alias = keyTest.getCertificateAlias(cert[0]); + } else return null; + } catch (Exception ex) { + throw new IllegalArgumentException(ex.getMessage()); + } + } + + public X509Certificate[] getCertificateChain(String s) { + /*try { + if (s != null && !s.equals("")) { + X509Certificate[] cert = (X509Certificate[]) keyTest.getCertificateChain(s); + return cert; + } else return null; + } catch (Exception ex) { + throw new IllegalArgumentException(ex.getMessage()); + }*/ + return null; + } + + public PrivateKey getPrivateKey(String s) { + /*try { + if (s != null && !s.equals("")) { + Certificate[] cert = keyTest.getCertificateChain(s); + PrivateKey pk = (PrivateKey) keyTest.getKey(s, null); + return pk; + } else return null; + } catch (Exception ex) { + throw new IllegalArgumentException(ex.getMessage()); + }*/ + return null; + } + +} diff --git a/support/src/test/java/org/apache/harmony/xnet/tests/support/X509TrustManagerImpl.java b/support/src/test/java/org/apache/harmony/xnet/tests/support/X509TrustManagerImpl.java new file mode 100644 index 0000000..47fe92f --- /dev/null +++ b/support/src/test/java/org/apache/harmony/xnet/tests/support/X509TrustManagerImpl.java @@ -0,0 +1,43 @@ +package org.apache.harmony.xnet.tests.support; + +import javax.net.ssl.X509TrustManager; +import java.security.cert.X509Certificate; +import java.security.cert.CertificateException; + +public class X509TrustManagerImpl implements X509TrustManager { + + public void checkClientTrusted(X509Certificate[] ax509certificate, String s) + throws CertificateException { + + if(ax509certificate == null || ax509certificate.length == 0) + throw new IllegalArgumentException("null or zero-length certificate chain"); + if(s == null || s.length() == 0) + throw new IllegalArgumentException("null or zero-length authentication type"); + + for (int i = 0; i < ax509certificate.length; i++) { + if (ax509certificate[i].getVersion() != 3) { + throw new CertificateException(); + } + } + } + + public void checkServerTrusted(X509Certificate[] ax509certificate, String s) + throws CertificateException { + + if(ax509certificate == null || ax509certificate.length == 0) + throw new IllegalArgumentException("null or zero-length certificate chain"); + if(s == null || s.length() == 0) + throw new IllegalArgumentException("null or zero-length authentication type"); + + for (int i = 0; i < ax509certificate.length; i++) { + if (ax509certificate[i].getVersion() != 3) { + throw new CertificateException(); + } + } + } + + public X509Certificate[] getAcceptedIssuers() { + X509Certificate[] cert = new X509Certificate[0]; + return cert; + } +} diff --git a/support/src/test/java/org/apache/harmony/xnet/tests/support/mySSLSession.java b/support/src/test/java/org/apache/harmony/xnet/tests/support/mySSLSession.java new file mode 100644 index 0000000..9d318fc --- /dev/null +++ b/support/src/test/java/org/apache/harmony/xnet/tests/support/mySSLSession.java @@ -0,0 +1,162 @@ +package org.apache.harmony.xnet.tests.support; + +import java.security.Principal; +import java.security.cert.Certificate; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Vector; + +import javax.net.ssl.SSLPeerUnverifiedException; +import javax.net.ssl.SSLSessionBindingEvent; +import javax.net.ssl.SSLSessionBindingListener; +import javax.net.ssl.SSLSessionContext; +import javax.security.cert.X509Certificate; + +import javax.net.ssl.SSLSession; + +import org.apache.harmony.security.tests.support.TestCertUtils; + +public class mySSLSession implements SSLSession { + + private byte[] idData; + private String nameHost = null; + private int namePort = -1; + private Hashtable table; + private boolean invalidateDone = false; + private Certificate[] certs = null; + private X509Certificate[] xCerts = null; + + public mySSLSession(String host, int port, byte[] id) { + certs = null; + xCerts = null; + nameHost = host; + namePort = port; + idData = id; + table = new Hashtable(); + } + + public mySSLSession(X509Certificate[] xc) { + certs = TestCertUtils.getCertChain(); + xCerts = xc; + } + + public int getApplicationBufferSize() { + return 1234567; + } + + public String getCipherSuite() { + return "SuiteName"; + } + + public long getCreationTime() { + return 1000l; + } + + public byte[] getId() { + return idData; + } + + public long getLastAccessedTime() { + return 2000l; + } + + public Certificate[] getLocalCertificates() { + return null; + } + + public Principal getLocalPrincipal() { + return null; + } + + public int getPacketBufferSize() { + return 12345; + } + + public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException { + if (certs == null) { + throw new SSLPeerUnverifiedException("peer not authenticated"); + } else { + return certs; + } + } + + public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException { + if(xCerts == null) { + throw new SSLPeerUnverifiedException("peer not authenticated"); + } else { + return xCerts; + } + } + + public String getPeerHost() { + return nameHost; + } + + public int getPeerPort() { + return namePort; + } + + public Principal getPeerPrincipal() throws SSLPeerUnverifiedException { + return null; + } + + public String getProtocol() { + return "ProtocolName"; + } + + public SSLSessionContext getSessionContext() { + return null; + } + + public void putValue(String s, Object obj) { + if(s == null || obj == null) + throw new IllegalArgumentException("arguments can not be null"); + Object obj1 = table.put(s, obj); + if(obj1 instanceof SSLSessionBindingListener) { + SSLSessionBindingEvent sslsessionbindingevent = new SSLSessionBindingEvent(this, s); + ((SSLSessionBindingListener)obj1).valueUnbound(sslsessionbindingevent); + } + if(obj instanceof SSLSessionBindingListener) { + SSLSessionBindingEvent sslsessionbindingevent1 = new SSLSessionBindingEvent(this, s); + ((SSLSessionBindingListener)obj).valueBound(sslsessionbindingevent1); + } + } + + public void removeValue(String s) { + if(s == null) + throw new IllegalArgumentException("argument can not be null"); + Object obj = table.remove(s); + if(obj instanceof SSLSessionBindingListener) { + SSLSessionBindingEvent sslsessionbindingevent = new SSLSessionBindingEvent(this, s); + ((SSLSessionBindingListener)obj).valueUnbound(sslsessionbindingevent); + } + } + + public Object getValue(String s) { + if(s == null) { + throw new IllegalArgumentException("argument can not be null"); + } else { + return table.get(s); + } + } + + public String[] getValueNames() { + Vector vector = new Vector(); + Enumeration enumeration = table.keys(); + while (enumeration.hasMoreElements()) { + vector.addElement(enumeration.nextElement()); + } + String as[] = new String[vector.size()]; + vector.copyInto(as); + return as; + } + + public void invalidate() { + invalidateDone = true; + } + + public boolean isValid() { + return invalidateDone; + } + +} diff --git a/support/src/test/java/org/apache/harmony/xnet/tests/support/mySSLSocket.java b/support/src/test/java/org/apache/harmony/xnet/tests/support/mySSLSocket.java new file mode 100644 index 0000000..c4664f0 --- /dev/null +++ b/support/src/test/java/org/apache/harmony/xnet/tests/support/mySSLSocket.java @@ -0,0 +1,159 @@ +package org.apache.harmony.xnet.tests.support; + +import javax.net.ssl.SSLSession; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.HandshakeCompletedListener; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; + +/** + * Additional class for SSLSocket constructor verification + */ +public class mySSLSocket extends SSLSocket { + + private boolean init = false; + private boolean sslFlag = true; + private boolean sslNeed = false; + private boolean sslWant = false; + private int sslMode; + private String[] supportProtocol = null; + private String[] supportSuites = null; + + public mySSLSocket(int mode){ + super(); + sslMode = mode; + } + public mySSLSocket(String[] protocol, String[] suites){ + super(); + supportProtocol = protocol; + supportSuites = suites; + } + public mySSLSocket(int mode, String[] protocol, String[] suites){ + super(); + sslMode = mode; + supportProtocol = protocol; + supportSuites = suites; + } + public mySSLSocket(){ + super(); + } + public mySSLSocket(InetAddress address, int port) throws IOException{ + super(address, port); + } + public mySSLSocket(InetAddress address, int port, + InetAddress clientAddress, int clientPort) throws IOException{ + super(address, port, clientAddress, clientPort); + } + public mySSLSocket(String host, int port) throws IOException, UnknownHostException{ + super(host, port); + } + public mySSLSocket(String host, int port, InetAddress clientAddress, + int clientPort) throws IOException, UnknownHostException{ + super(host, port, clientAddress, clientPort); + } + + public void addHandshakeCompletedListener(HandshakeCompletedListener listener) { + if(listener == null) throw new IllegalArgumentException("listener is null"); + } + public String[] getEnabledCipherSuites() { + return supportSuites; + } + public String[] getEnabledProtocols() { + return supportProtocol; + } + public boolean getEnableSessionCreation() { + return sslFlag; + } + public boolean getNeedClientAuth() { + if (sslMode == 1) { + throw new IllegalStateException("Incorrect mode"); + } else return sslNeed; + } + public SSLSession getSession() { + return null; + } + public String[] getSupportedCipherSuites() { + if (supportSuites == null) { + throw new NullPointerException(); + } + if (supportSuites.length == 0) { + return null; + } else return supportSuites; + } + public String[] getSupportedProtocols() { + if (supportProtocol == null) { + throw new NullPointerException(); + } + if (supportProtocol.length == 0) { + return null; + } else return supportProtocol; + } + public boolean getUseClientMode() { + if (sslMode == 1) { + return true; + } else return false; + } + public boolean getWantClientAuth() { + if (sslMode == 1) { + throw new IllegalStateException("Incorrect mode"); + } else return sslWant; + } + public void removeHandshakeCompletedListener(HandshakeCompletedListener listener) { + if(listener == null) throw new IllegalArgumentException("listener is null"); + } + public void setEnabledCipherSuites(String[] suites) { + if (suites == null) { + throw new IllegalArgumentException("null parameter"); + } + if (!suites.equals(supportSuites)) { + throw new IllegalArgumentException("incorrect suite"); + } + } + public void setEnabledProtocols(String[] protocols) { + if (protocols == null) { + throw new IllegalArgumentException("null protocol"); + } + if (!protocols.equals(supportProtocol)) { + throw new IllegalArgumentException("incorrect protocol"); + } + } + public void setEnableSessionCreation(boolean flag) { + sslFlag = flag; + } + public void setNeedClientAuth(boolean need) { + if (sslMode == 0) { + sslNeed = need; + } else { + throw new IllegalStateException("Incorrect mode"); + } + } + public void setUseClientMode(boolean mode) { + if (!init) { + if (mode && sslMode == 0) { + sslMode = 1; + } else if (!mode && sslMode == 1) { + sslMode = 0; + } + } else { + throw new IllegalArgumentException(); + } + } + public void setWantClientAuth(boolean want) { + if (sslMode == 0) { + sslWant = want; + } else { + throw new IllegalStateException("Incorrect mode"); + } + } + public void startHandshake() throws IOException { + for (int i = 0; i < supportProtocol.length; i++) { + if (supportProtocol[i] == "Protocol_2") { + throw new IOException(); + } + } + init = true; + } +} + |