not-yet-commons-ssl-0.3.11

;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CRL;
import java.security.cert.CRLException;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.security.cert.X509Extension;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.StringTokenizer;
import javax.net.ssl.HttpsURLConnection;
import javax.security.auth.x500.X500Principal;

public class Certificates
{
  public static final CertificateFactory CF;
  public static final String LINE_ENDING = System.getProperty("line.separator");
  private static final HashMap crl_cache = new HashMap();
  public static final String CRL_EXTENSION = "2.5.29.31";
  public static final String OCSP_EXTENSION = "1.3.6.1.5.5.7.1.1";
  private static final DateFormat DF = new SimpleDateFormat("yyyy/MMM/dd");
  public static final SerializableComparator COMPARE_BY_EXPIRY = new SerializableComparator()
  {
    public int compare(Object o1, Object o2)
    {
      X509Certificate c1 = (X509Certificate)o1;
      X509Certificate c2 = (X509Certificate)o2;
      if (c1 == c2) {
        return 0;
      }
      if (c1 == null) {
        return -1;
      }
      if (c2 == null) {
        return 1;
      }
      if (c1.equals(c2)) {
        return 0;
      }
      Date d1 = c1.getNotAfter();
      Date d2 = c2.getNotAfter();
      int c = d1.compareTo(d2);
      if (c == 0)
      {
        String s1 = JavaImpl.getSubjectX500(c1);
        String s2 = JavaImpl.getSubjectX500(c2);
        c = s1.compareTo(s2);
        if (c == 0)
        {
          s1 = JavaImpl.getIssuerX500(c1);
          s2 = JavaImpl.getIssuerX500(c2);
          c = s1.compareTo(s2);
          if (c == 0)
          {
            BigInteger big1 = c1.getSerialNumber();
            BigInteger big2 = c2.getSerialNumber();
            c = big1.compareTo(big2);
            if (c == 0) {
              try
              {
                byte[] b1 = c1.getEncoded();
                byte[] b2 = c2.getEncoded();
                int len1 = b1.length;
                int len2 = b2.length;
                for (int i = 0; (i < len1) && (i < len2); i++)
                {
                  c = b1[i] - b2[i];
                  if (c != 0) {
                    break;
                  }
                }
                if (c == 0) {
                  c = b1.length - b2.length;
                }
              }
              catch (CertificateEncodingException cee)
              {
                c = 0;
              }
            }
          }
        }
      }
      return c;
    }
  };
  
  static
  {
    CertificateFactory cf = null;
    try
    {
      cf = CertificateFactory.getInstance("X.509");
    }
    catch (CertificateException ce)
    {
      ce.printStackTrace(System.out);
    }
    finally
    {
      CF = cf;
    }
  }
  
  public static String toPEMString(X509Certificate cert)
    throws CertificateEncodingException
  {
    return toString(cert.getEncoded());
  }
  
  public static String toString(byte[] x509Encoded)
  {
    byte[] encoded = Base64.encodeBase64(x509Encoded);
    StringBuffer buf = new StringBuffer(encoded.length + 100);
    buf.append("-----BEGIN CERTIFICATE-----\n");
    for (int i = 0; i < encoded.length; i += 64)
    {
      if (encoded.length - i >= 64) {
        buf.append(new String(encoded, i, 64));
      } else {
        buf.append(new String(encoded, i, encoded.length - i));
      }
      buf.append(LINE_ENDING);
    }
    buf.append("-----END CERTIFICATE-----");
    buf.append(LINE_ENDING);
    return buf.toString();
  }
  
  public static String toString(X509Certificate cert)
  {
    return toString(cert, false);
  }
  
  public static String toString(X509Certificate cert, boolean htmlStyle)
  {
    String cn = getCN(cert);
    String startStart = DF.format(cert.getNotBefore());
    String endDate = DF.format(cert.getNotAfter());
    String subject = JavaImpl.getSubjectX500(cert);
    String issuer = JavaImpl.getIssuerX500(cert);
    Iterator crls = getCRLs(cert).iterator();
    if (subject.equals(issuer)) {
      issuer = "self-signed";
    }
    StringBuffer buf = new StringBuffer(128);
    if (htmlStyle) {
      buf.append("<strong class=\"cn\">");
    }
    buf.append(cn);
    if (htmlStyle) {
      buf.append("</strong>");
    }
    buf.append(LINE_ENDING);
    buf.append("Valid: ");
    buf.append(startStart);
    buf.append(" - ");
    buf.append(endDate);
    buf.append(LINE_ENDING);
    buf.append("s: ");
    buf.append(subject);
    buf.append(LINE_ENDING);
    buf.append("i: ");
    buf.append(issuer);
    while (crls.hasNext())
    {
      buf.append(LINE_ENDING);
      buf.append("CRL: ");
      buf.append((String)crls.next());
    }
    buf.append(LINE_ENDING);
    return buf.toString();
  }
  
  public static List getCRLs(X509Extension cert)
  {
    byte[] bytes = cert.getExtensionValue("2.5.29.31");
    LinkedList httpCRLS = new LinkedList();
    LinkedList ftpCRLS = new LinkedList();
    LinkedList otherCRLS = new LinkedList();
    if (bytes == null) {
      return httpCRLS;
    }
    String s;
    try
    {
      s = new String(bytes, "UTF-8");
    }
    catch (UnsupportedEncodingException uee)
    {
      String s;
      s = new String(bytes);
    }
    int pos = 0;
    while (pos >= 0)
    {
      int x = -1;
      int[] indexes = new int[4];
      indexes[0] = s.indexOf("http", pos);
      indexes[1] = s.indexOf("ldap", pos);
      indexes[2] = s.indexOf("file", pos);
      indexes[3] = s.indexOf("ftp", pos);
      Arrays.sort(indexes);
      for (int i = 0; i < indexes.length; i++) {
        if (indexes[i] >= 0)
        {
          x = indexes[i];
          break;
        }
      }
      if (x >= 0)
      {
        int y = s.indexOf(65533, x);
        String crl = y > x ? s.substring(x, y - 1) : s.substring(x);
        if ((y > x) && (crl.endsWith("0"))) {
          crl = crl.substring(0, crl.length() - 1);
        }
        String crlTest = crl.trim().toLowerCase();
        if (crlTest.startsWith("http")) {
          httpCRLS.add(crl);
        } else if (crlTest.startsWith("ftp")) {
          ftpCRLS.add(crl);
        } else {
          otherCRLS.add(crl);
        }
        pos = y;
      }
      else
      {
        pos = -1;
      }
    }
    httpCRLS.addAll(ftpCRLS);
    httpCRLS.addAll(otherCRLS);
    return httpCRLS;
  }
  
  public static void checkCRL(X509Certificate cert)
    throws CertificateException
  {
    byte[] bytes = cert.getExtensionValue("2.5.29.31");
    if (bytes != null)
    {
      List crlList = getCRLs(cert);
      Iterator it = crlList.iterator();
      while (it.hasNext())
      {
        String url = (String)it.next();
        CRLHolder holder = (CRLHolder)crl_cache.get(url);
        if (holder == null)
        {
          holder = new CRLHolder(url);
          crl_cache.put(url, holder);
        }
        boolean success = holder.checkCRL(cert);
        if (success) {
          break;
        }
      }
    }
  }
  
  public static BigInteger getFingerprint(X509Certificate x509)
    throws CertificateEncodingException
  {
    return getFingerprint(x509.getEncoded());
  }
  
  public static BigInteger getFingerprint(byte[] x509)
    throws CertificateEncodingException
  {
    try
    {
      sha1 = MessageDigest.getInstance("SHA1");
    }
    catch (NoSuchAlgorithmException nsae)
    {
      MessageDigest sha1;
      throw JavaImpl.newRuntimeException(nsae);
    }
    MessageDigest sha1;
    sha1.reset();
    byte[] result = sha1.digest(x509);
    return new BigInteger(result);
  }
  
  private static class CRLHolder
  {
    private final String urlString;
    private File tempCRLFile;
    private long creationTime;
    private Set passedTest = new HashSet();
    private Set failedTest = new HashSet();
    
    CRLHolder(String urlString)
    {
      if (urlString == null) {
        throw new NullPointerException("urlString can't be null");
      }
      this.urlString = urlString;
    }
    
    public synchronized boolean checkCRL(X509Certificate cert)
      throws CertificateException
    {
      CRL crl = null;
      long now = System.currentTimeMillis();
      if (now - creationTime > 86400000L)
      {
        if ((tempCRLFile != null) && (tempCRLFile.exists())) {
          tempCRLFile.delete();
        }
        tempCRLFile = null;
        passedTest.clear();
      }
      BigInteger fingerprint = Certificates.getFingerprint(cert);
      if (failedTest.contains(fingerprint)) {
        throw new CertificateException("Revoked by CRL (cached response)");
      }
      if (passedTest.contains(fingerprint)) {
        return true;
      }
      if (tempCRLFile == null) {
        try
        {
          URL url = new URL(urlString);
          URLConnection urlConn = url.openConnection();
          if ((urlConn instanceof HttpsURLConnection))
          {
            HttpsURLConnection httpsConn = (HttpsURLConnection)urlConn;
            httpsConn.setSSLSocketFactory(CRLSocket.getSecureInstance());
          }
          else if ((urlConn instanceof HttpURLConnection))
          {
            HttpURLConnection httpConn = (HttpURLConnection)urlConn;
            try
            {
              Class c = httpConn.getClass();
              Method setConnTimeOut = c.getDeclaredMethod("setConnectTimeout", new Class[] { Integer.TYPE });
              Method setReadTimeout = c.getDeclaredMethod("setReadTimeout", new Class[] { Integer.TYPE });
              setConnTimeOut.invoke(httpConn, new Integer[] { new Integer(5000) });
              setReadTimeout.invoke(httpConn, new Integer[] { new Integer(5000) });
            }
            catch (NoSuchMethodException nsme) {}catch (Exception e)
            {
              throw new RuntimeException("can't set timeout", e);
            }
          }
          File tempFile = File.createTempFile("crl", ".tmp");
          tempFile.deleteOnExit();
          
          OutputStream out = new FileOutputStream(tempFile);
          out = new BufferedOutputStream(out);
          InputStream in = new BufferedInputStream(urlConn.getInputStream());
          try
          {
            Util.pipeStream(in, out);
          }
          catch (IOException ioe)
          {
            tempFile.delete();
            throw ioe;
          }
          tempCRLFile = tempFile;
          creationTime = System.currentTimeMillis();
        }
        catch (IOException ioe) {}
      }
      if ((tempCRLFile != null) && (tempCRLFile.exists())) {
        try
        {
          InputStream in = new FileInputStream(tempCRLFile);
          in = new BufferedInputStream(in);
          synchronized (Certificates.CF)
          {
            crl = Certificates.CF.generateCRL(in);
          }
          in.close();
          if (crl.isRevoked(cert))
          {
            passedTest.remove(fingerprint);
            failedTest.add(fingerprint);
            throw new CertificateException("Revoked by CRL");
          }
          passedTest.add(fingerprint);
        }
        catch (IOException ioe) {}catch (CRLException crle) {}
      }
      return crl != null;
    }
  }
  
  public static String getCN(X509Certificate cert)
  {
    String[] cns = getCNs(cert);
    boolean foundSomeCNs = (cns != null) && (cns.length >= 1);
    return foundSomeCNs ? cns[0] : null;
  }
  
  public static String[] getCNs(X509Certificate cert)
  {
    LinkedList cnList = new LinkedList();
    
    String subjectPrincipal = cert.getSubjectX500Principal().toString();
    StringTokenizer st = new StringTokenizer(subjectPrincipal, ",");
    while (st.hasMoreTokens())
    {
      String tok = st.nextToken();
      int x = tok.indexOf("CN=");
      if (x >= 0) {
        cnList.add(tok.substring(x + 3));
      }
    }
    if (!cnList.isEmpty())
    {
      String[] cns = new String[cnList.size()];
      cnList.toArray(cns);
      return cns;
    }
    return null;
  }
  
  public static String[] getDNSSubjectAlts(X509Certificate cert)
  {
    LinkedList subjectAltList = new LinkedList();
    Collection c = null;
    try
    {
      c = cert.getSubjectAlternativeNames();
    }
    catch (CertificateParsingException cpe)
    {
      cpe.printStackTrace();
    }
    if (c != null)
    {
      Iterator it = c.iterator();
      while (it.hasNext())
      {
        List list = (List)it.next();
        int type = ((Integer)list.get(0)).intValue();
        if (type == 2)
        {
          String s = (String)list.get(1);
          subjectAltList.add(s);
        }
      }
    }
    if (!subjectAltList.isEmpty())
    {
      String[] subjectAlts = new String[subjectAltList.size()];
      subjectAltList.toArray(subjectAlts);
      return subjectAlts;
    }
    return null;
  }
  
  public static Certificate[] trimChain(Certificate[] chain)
  {
    for (int i = 0; i < chain.length; i++) {
      if (chain[i] == null)
      {
        X509Certificate[] newChain = new X509Certificate[i];
        System.arraycopy(chain, 0, newChain, 0, i);
        return newChain;
      }
    }
    return chain;
  }
  
  public static X509Certificate[] x509ifyChain(Certificate[] chain)
  {
    if ((chain instanceof X509Certificate[])) {
      return (X509Certificate[])chain;
    }
    X509Certificate[] x509Chain = new X509Certificate[chain.length];
    System.arraycopy(chain, 0, x509Chain, 0, chain.length);
    return x509Chain;
  }
  
  public static void main(String[] args)
    throws Exception
  {
    for (int i = 0; i < args.length; i++)
    {
      FileInputStream in = new FileInputStream(args[i]);
      TrustMaterial tm = new TrustMaterial(in);
      Iterator it = tm.getCertificates().iterator();
      while (it.hasNext())
      {
        X509Certificate x509 = (X509Certificate)it.next();
        System.out.println(toString(x509));
      }
    }
  }
  
  public static abstract interface SerializableComparator
    extends Comparator, Serializable
  {}
}

/* Location:
 * Qualified Name:     org.apache.commons.ssl.Certificates
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.commons.ssl;

import java.io.IOException;
import java.io.InputStream;

public class ComboInputStream
  extends InputStream
{
  private boolean headDone;
  private InputStream head;
  private InputStream tail;
  
  public ComboInputStream(InputStream head, InputStream tail)
  {
    this.head = (head != null ? head : tail);
    this.tail = (tail != null ? tail : head);
  }
  
  public int read()
    throws IOException
  {
    int c;
    int c;
    if (headDone)
    {
      c = tail.read();
    }
    else
    {
      c = head.read();
      if (c == -1)
      {
        headDone = true;
        c = tail.read();
      }
    }
    return c;
  }
  
  public int available()
    throws IOException
  {
    return tail.available() + head.available();
  }
  
  public void close()
    throws IOException
  {
    try
    {
      head.close();
    }
    finally
    {
      if (head != tail) {
        tail.close();
      }
    }
  }
  
  public int read(byte[] b, int off, int len)
    throws IOException
  {
    int c;
    int c;
    if (headDone)
    {
      c = tail.read(b, off, len);
    }
    else
    {
      c = head.read(b, off, len);
      if (c == -1)
      {
        headDone = true;
        c = tail.read(b, off, len);
      }
    }
    return c;
  }
}

/* Location:
 * Qualified Name:     org.apache.commons.ssl.ComboInputStream
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.commons.ssl;

public class DerivedKey
{
  public final byte[] key;
  public final byte[] iv;
  
  DerivedKey(byte[] key, byte[] iv)
  {
    this.key = key;
    this.iv = iv;
  }
}

/* Location:
 * Qualified Name:     org.apache.commons.ssl.DerivedKey
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.commons.ssl;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class HostPort
{
  public final String host;
  public final int port;
  public final InetAddress addr;
  
  public HostPort(String host, int port)
    throws UnknownHostException
  {
    this.host = host;
    this.port = port;
    addr = InetAddress.getByName(host);
  }
  
  public String toString()
  {
    return host + ":" + port;
  }
}

/* Location:
 * Qualified Name:     org.apache.commons.ssl.HostPort
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.commons.ssl;

import javax.net.ssl.SSLException;

class HostnameVerifier$1
  extends HostnameVerifier.AbstractVerifier
{
  HostnameVerifier$1()
    throws SSLException
  {}
  
  public final void check(String[] hosts, String[] cns, String[] subjectAlts)
    throws SSLException
  {
    check(hosts, cns, subjectAlts, false, false);
  }
  
  public final String toString()
  {
    return "DEFAULT";
  }
}

/* Location:
 * Qualified Name:     org.apache.commons.ssl.HostnameVerifier.1
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.commons.ssl;

import javax.net.ssl.SSLException;

class HostnameVerifier$2
  extends HostnameVerifier.AbstractVerifier
{
  HostnameVerifier$2()
    throws SSLException
  {}
  
  public final void check(String[] hosts, String[] cns, String[] subjectAlts)
    throws SSLException
  {
    if (isLocalhost(hosts[0])) {
      return;
    }
    check(hosts, cns, subjectAlts, false, false);
  }
  
  public final String toString()
  {
    return "DEFAULT_AND_LOCALHOST";
  }
}

/* Location:
 * Qualified Name:     org.apache.commons.ssl.HostnameVerifier.2
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.commons.ssl;

import javax.net.ssl.SSLException;

class HostnameVerifier$3
  extends HostnameVerifier.AbstractVerifier
{
  HostnameVerifier$3()
    throws SSLException
  {}
  
  public final void check(String[] host, String[] cns, String[] subjectAlts)
    throws SSLException
  {
    check(host, cns, subjectAlts, false, true);
  }
  
  public final String toString()
  {
    return "STRICT";
  }
}

/* Location:
 * Qualified Name:     org.apache.commons.ssl.HostnameVerifier.3
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.commons.ssl;

import javax.net.ssl.SSLException;

class HostnameVerifier$4
  extends HostnameVerifier.AbstractVerifier
{
  HostnameVerifier$4()
    throws SSLException
  {}
  
  public final void check(String[] host, String[] cns, String[] subjectAlts)
    throws SSLException
  {
    check(host, cns, subjectAlts, true, true);
  }
  
  public final String toString()
  {
    return "STRICT_IE6";
  }
}

/* Location:
 * Qualified Name:     org.apache.commons.ssl.HostnameVerifier.4
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.commons.ssl;

class HostnameVerifier$5
  extends HostnameVerifier.AbstractVerifier
{
  public final void check(String[] host, String[] cns, String[] subjectAlts) {}
  
  public final String toString()
  {
    return "ALLOW_ALL";
  }
}

/* Location:
 * Qualified Name:     org.apache.commons.ssl.HostnameVerifier.5
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.commons.ssl;

import java.io.IOException;
import java.io.InputStream;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Iterator;
import java.util.TreeSet;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;

public abstract class HostnameVerifier$AbstractVerifier
  implements HostnameVerifier
{
  private static final String[] BAD_COUNTRY_2LDS = { "ac", "co", "com", "ed", "edu", "go", "gouv", "gov", "info", "lg", "ne", "net", "or", "org" };
  private static final String[] LOCALHOSTS = { "::1", "127.0.0.1", "localhost", "localhost.localdomain" };
  
  static
  {
    Arrays.sort(BAD_COUNTRY_2LDS);
    Arrays.sort(LOCALHOSTS);
  }
  
  public boolean verify(String host, SSLSession session)
  {
    try
    {
      Certificate[] certs = session.getPeerCertificates();
      X509Certificate x509 = (X509Certificate)certs[0];
      check(new String[] { host }, x509);
      return true;
    }
    catch (SSLException e) {}
    return false;
  }
  
  public void check(String host, SSLSocket ssl)
    throws IOException
  {
    check(new String[] { host }, ssl);
  }
  
  public void check(String host, X509Certificate cert)
    throws SSLException
  {
    check(new String[] { host }, cert);
  }
  
  public void check(String host, String[] cns, String[] subjectAlts)
    throws SSLException
  {
    check(new String[] { host }, cns, subjectAlts);
  }
  
  public void check(String[] host, SSLSocket ssl)
    throws IOException
  {
    if (host == null) {
      throw new NullPointerException("host to verify is null");
    }
    SSLSession session = ssl.getSession();
    if (session == null)
    {
      InputStream in = ssl.getInputStream();
      in.available();
      
      session = ssl.getSession();
      if (session == null)
      {
        ssl.startHandshake();
        
        session = ssl.getSession();
      }
    }
    try
    {
      certs = session.getPeerCertificates();
    }
    catch (SSLPeerUnverifiedException spue)
    {
      Certificate[] certs;
      InputStream in = ssl.getInputStream();
      in.available();
      
      throw spue;
    }
    Certificate[] certs;
    X509Certificate x509 = (X509Certificate)certs[0];
    check(host, x509);
  }
  
  public void check(String[] host, X509Certificate cert)
    throws SSLException
  {
    String[] cns = Certificates.getCNs(cert);
    String[] subjectAlts = Certificates.getDNSSubjectAlts(cert);
    check(host, cns, subjectAlts);
  }
  
  public void check(String[] hosts, String[] cns, String[] subjectAlts, boolean ie6, boolean strictWithSubDomains)
    throws SSLException
  {
    StringBuffer buf = new StringBuffer(32);
    buf.append('<');
    for (int i = 0; i < hosts.length; i++)
    {
      String h = hosts[i];
      h = h != null ? h.trim().toLowerCase() : "";
      hosts[i] = h;
      if (i > 0) {
        buf.append('/');
      }
      buf.append(h);
    }
    buf.append('>');
    String hostnames = buf.toString();
    
    TreeSet names = new TreeSet();
    if ((cns != null) && (cns.length > 0) && (cns[0] != null))
    {
      names.add(cns[0]);
      if (ie6) {
        for (int i = 1; i < cns.length; i++) {
          names.add(cns[i]);
        }
      }
    }
    if (subjectAlts != null) {
      for (int i = 0; i < subjectAlts.length; i++) {
        if (subjectAlts[i] != null) {
          names.add(subjectAlts[i]);
        }
      }
    }
    if (names.isEmpty())
    {
      String msg = "Certificate for " + hosts[0] + " doesn't contain CN or DNS subjectAlt";
      throw new SSLException(msg);
    }
    buf = new StringBuffer();
    
    boolean match = false;
    for (Iterator it = names.iterator(); it.hasNext();)
    {
      String cn = (String)it.next();
      cn = cn.toLowerCase();
      
      buf.append(" <");
      buf.append(cn);
      buf.append('>');
      if (it.hasNext()) {
        buf.append(" OR");
      }
      boolean doWildcard = (cn.startsWith("*.")) && (cn.lastIndexOf('.') >= 0) && (!isIP4Address(cn)) && (acceptableCountryWildcard(cn));
      for (int i = 0; i < hosts.length; i++)
      {
        String hostName = hosts[i].trim().toLowerCase();
        if (doWildcard)
        {
          match = hostName.endsWith(cn.substring(1));
          if ((match) && (strictWithSubDomains)) {
            match = countDots(hostName) == countDots(cn);
          }
        }
        else
        {
          match = hostName.equals(cn);
        }
        if (match) {
          break label482;
        }
      }
    }
    label482:
    if (!match) {
      throw new SSLException("hostname in certificate didn't match: " + hostnames + " !=" + buf);
    }
  }
  
  public static boolean isIP4Address(String cn)
  {
    boolean isIP4 = true;
    String tld = cn;
    int x = cn.lastIndexOf('.');
    if ((x >= 0) && (x + 1 < cn.length())) {
      tld = cn.substring(x + 1);
    }
    for (int i = 0; i < tld.length(); i++) {
      if (!Character.isDigit(tld.charAt(0)))
      {
        isIP4 = false;
        break;
      }
    }
    return isIP4;
  }
  
  public static boolean acceptableCountryWildcard(String cn)
  {
    int cnLen = cn.length();
    if ((cnLen >= 7) && (cnLen <= 9)) {
      if (cn.charAt(cnLen - 3) == '.')
      {
        String s = cn.substring(2, cnLen - 3);
        
        int x = Arrays.binarySearch(BAD_COUNTRY_2LDS, s);
        return x < 0;
      }
    }
    return true;
  }
  
  public static boolean isLocalhost(String host)
  {
    host = host != null ? host.trim().toLowerCase() : "";
    if (host.startsWith("::1"))
    {
      int x = host.lastIndexOf('%');
      if (x >= 0) {
        host = host.substring(0, x);
      }
    }
    int x = Arrays.binarySearch(LOCALHOSTS, host);
    return x >= 0;
  }
  
  public static int countDots(String s)
  {
    int count = 0;
    for (int i = 0; i < s.length(); i++) {
      if (s.charAt(i) == '.') {
        count++;
      }
    }
    return count;
  }
}

/* Location:
 * Qualified Name:     org.apache.commons.ssl.HostnameVerifier.AbstractVerifier
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.commons.ssl;

import java.io.IOException;
import java.io.InputStream;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Iterator;
import java.util.TreeSet;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;

public abstract interface HostnameVerifier
  extends javax.net.ssl.HostnameVerifier
{
  public static final HostnameVerifier DEFAULT = new AbstractVerifier()
  {
    public final void check(String[] hosts, String[] cns, String[] subjectAlts)
      throws SSLException
    {
      check(hosts, cns, subjectAlts, false, false);
    }
    
    public final String toString()
    {
      return "DEFAULT";
    }
  };
  public static final HostnameVerifier DEFAULT_AND_LOCALHOST = new AbstractVerifier()
  {
    public final void check(String[] hosts, String[] cns, String[] subjectAlts)
      throws SSLException
    {
      if (isLocalhost(hosts[0])) {
        return;
      }
      check(hosts, cns, subjectAlts, false, false);
    }
    
    public final String toString()
    {
      return "DEFAULT_AND_LOCALHOST";
    }
  };
  public static final HostnameVerifier STRICT = new AbstractVerifier()
  {
    public final void check(String[] host, String[] cns, String[] subjectAlts)
      throws SSLException
    {
      check(host, cns, subjectAlts, false, true);
    }
    
    public final String toString()
    {
      return "STRICT";
    }
  };
  public static final HostnameVerifier STRICT_IE6 = new AbstractVerifier()
  {
    public final void check(String[] host, String[] cns, String[] subjectAlts)
      throws SSLException
    {
      check(host, cns, subjectAlts, true, true);
    }
    
    public final String toString()
    {
      return "STRICT_IE6";
    }
  };
  public static final HostnameVerifier ALLOW_ALL = new AbstractVerifier()
  {
    public final void check(String[] host, String[] cns, String[] subjectAlts) {}
    
    public final String toString()
    {
      return "ALLOW_ALL";
    }
  };
  
  public abstract boolean verify(String paramString, SSLSession paramSSLSession);
  
  public abstract void check(String paramString, SSLSocket paramSSLSocket)
    throws IOException;
  
  public abstract void check(String paramString, X509Certificate paramX509Certificate)
    throws SSLException;
  
  public abstract void check(String paramString, String[] paramArrayOfString1, String[] paramArrayOfString2)
    throws SSLException;
  
  public abstract void check(String[] paramArrayOfString, SSLSocket paramSSLSocket)
    throws IOException;
  
  public abstract void check(String[] paramArrayOfString, X509Certificate paramX509Certificate)
    throws SSLException;
  
  public abstract void check(String[] paramArrayOfString1, String[] paramArrayOfString2, String[] paramArrayOfString3)
    throws SSLException;
  
  public static abstract class AbstractVerifier
    implements HostnameVerifier
  {
    private static final String[] BAD_COUNTRY_2LDS = { "ac", "co", "com", "ed", "edu", "go", "gouv", "gov", "info", "lg", "ne", "net", "or", "org" };
    private static final String[] LOCALHOSTS = { "::1", "127.0.0.1", "localhost", "localhost.localdomain" };
    
    static
    {
      Arrays.sort(BAD_COUNTRY_2LDS);
      Arrays.sort(LOCALHOSTS);
    }
    
    public boolean verify(String host, SSLSession session)
    {
      try
      {
        Certificate[] certs = session.getPeerCertificates();
        X509Certificate x509 = (X509Certificate)certs[0];
        check(new String[] { host }, x509);
        return true;
      }
      catch (SSLException e) {}
      return false;
    }
    
    public void check(String host, SSLSocket ssl)
      throws IOException
    {
      check(new String[] { host }, ssl);
    }
    
    public void check(String host, X509Certificate cert)
      throws SSLException
    {
      check(new String[] { host }, cert);
    }
    
    public void check(String host, String[] cns, String[] subjectAlts)
      throws SSLException
    {
      check(new String[] { host }, cns, subjectAlts);
    }
    
    public void check(String[] host, SSLSocket ssl)
      throws IOException
    {
      if (host == null) {
        throw new NullPointerException("host to verify is null");
      }
      SSLSession session = ssl.getSession();
      if (session == null)
      {
        InputStream in = ssl.getInputStream();
        in.available();
        
        session = ssl.getSession();
        if (session == null)
        {
          ssl.startHandshake();
          
          session = ssl.getSession();
        }
      }
      try
      {
        certs = session.getPeerCertificates();
      }
      catch (SSLPeerUnverifiedException spue)
      {
        Certificate[] certs;
        InputStream in = ssl.getInputStream();
        in.available();
        
        throw spue;
      }
      Certificate[] certs;
      X509Certificate x509 = (X509Certificate)certs[0];
      check(host, x509);
    }
    
    public void check(String[] host, X509Certificate cert)
      throws SSLException
    {
      String[] cns = Certificates.getCNs(cert);
      String[] subjectAlts = Certificates.getDNSSubjectAlts(cert);
      check(host, cns, subjectAlts);
    }
    
    public void check(String[] hosts, String[] cns, String[] subjectAlts, boolean ie6, boolean strictWithSubDomains)
      throws SSLException
    {
      StringBuffer buf = new StringBuffer(32);
      buf.append('<');
      for (int i = 0; i < hosts.length; i++)
      {
        String h = hosts[i];
        h = h != null ? h.trim().toLowerCase() : "";
        hosts[i] = h;
        if (i > 0) {
          buf.append('/');
        }
        buf.append(h);
      }
      buf.append('>');
      String hostnames = buf.toString();
      
      TreeSet names = new TreeSet();
      if ((cns != null) && (cns.length > 0) && (cns[0] != null))
      {
        names.add(cns[0]);
        if (ie6) {
          for (int i = 1; i < cns.length; i++) {
            names.add(cns[i]);
          }
        }
      }
      if (subjectAlts != null) {
        for (int i = 0; i < subjectAlts.length; i++) {
          if (subjectAlts[i] != null) {
            names.add(subjectAlts[i]);
          }
        }
      }
      if (names.isEmpty())
      {
        String msg = "Certificate for " + hosts[0] + " doesn't contain CN or DNS subjectAlt";
        throw new SSLException(msg);
      }
      buf = new StringBuffer();
      
      boolean match = false;
      for (Iterator it = names.iterator(); it.hasNext();)
      {
        String cn = (String)it.next();
        cn = cn.toLowerCase();
        
        buf.append(" <");
        buf.append(cn);
        buf.append('>');
        if (it.hasNext()) {
          buf.append(" OR");
        }
        boolean doWildcard = (cn.startsWith("*.")) && (cn.lastIndexOf('.') >= 0) && (!isIP4Address(cn)) && (acceptableCountryWildcard(cn));
        for (int i = 0; i < hosts.length; i++)
        {
          String hostName = hosts[i].trim().toLowerCase();
          if (doWildcard)
          {
            match = hostName.endsWith(cn.substring(1));
            if ((match) && (strictWithSubDomains)) {
              match = countDots(hostName) == countDots(cn);
            }
          }
          else
          {
            match = hostName.equals(cn);
          }
          if (match) {
            break label482;
          }
        }
      }
      label482:
      if (!match) {
        throw new SSLException("hostname in certificate didn't match: " + hostnames + " !=" + buf);
      }
    }
    
    public static boolean isIP4Address(String cn)
    {
      boolean isIP4 = true;
      String tld = cn;
      int x = cn.lastIndexOf('.');
      if ((x >= 0) && (x + 1 < cn.length())) {
        tld = cn.substring(x + 1);
      }
      for (int i = 0; i < tld.length(); i++) {
        if (!Character.isDigit(tld.charAt(0)))
        {
          isIP4 = false;
          break;
        }
      }
      return isIP4;
    }
    
    public static boolean acceptableCountryWildcard(String cn)
    {
      int cnLen = cn.length();
      if ((cnLen >= 7) && (cnLen <= 9)) {
        if (cn.charAt(cnLen - 3) == '.')
        {
          String s = cn.substring(2, cnLen - 3);
          
          int x = Arrays.binarySearch(BAD_COUNTRY_2LDS, s);
          return x < 0;
        }
      }
      return true;
    }
    
    public static boolean isLocalhost(String host)
    {
      host = host != null ? host.trim().toLowerCase() : "";
      if (host.startsWith("::1"))
      {
        int x = host.lastIndexOf('%');
        if (x >= 0) {
          host = host.substring(0, x);
        }
      }
      int x = Arrays.binarySearch(LOCALHOSTS, host);
      return x >= 0;
    }
    
    public static int countDots(String s)
    {
      int count = 0;
      for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == '.') {
          count++;
        }
      }
      return count;
    }
  }
}

/* Location:
 * Qualified Name:     org.apache.commons.ssl.HostnameVerifier
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.commons.ssl;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.security.GeneralSecurityException;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;

public class HttpSecureProtocol
  extends SSLClient
  implements SecureProtocolSocketFactory
{
  public HttpSecureProtocol()
    throws GeneralSecurityException, IOException
  {}
  
  public Socket createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params)
    throws IOException
  {
    if (params == null) {
      throw new IllegalArgumentException("Parameters may not be null");
    }
    int timeout = params.getConnectionTimeout();
    return super.createSocket(host, port, localAddress, localPort, timeout);
  }
}

/* Location:
 * Qualified Name:     org.apache.commons.ssl.HttpSecureProtocol
 * Java Class Version: 1.2 (46.0)
 * JD-Core Version:    0.7.1
 */
package org.apache.commons.ssl;

import com.sun.net.ssl.KeyManager;
import com.sun.net.ssl.KeyManagerFactory;
import com.sun.net.ssl.SSLContext;
import com.sun.net.ssl.TrustManager;
import com.sun.net.ssl.TrustManagerFactory;
import com.sun.net.ssl.X509KeyManager;
import com.sun.net.ssl.X509TrustManager;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import javax.net.SocketFactory;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

public final class Java13
  extends JavaImpl
{
  private static final Java13 instance = new Java13();
  
  private Java13()
  {
    try
    {
      Class c = Class.forName("javax.crypto.Cipher");
      Class[] sig = { String.class };
      String[] args = { "DES/CBC/PKCS5Padding" };
      Method m = c.getMethod("getInstance", sig);
      m.invoke(null, (Object[])args);
    }
    catch (Exception e)
    {
      try
      {
        Class c = Class.forName("com.sun.crypto.provider.SunJCE");
        Security.addProvider((java.security.Provider)c.newInstance());
      }
      catch (Exception e2)
      {
        System.out.println("com.sun.crypto.provider.SunJCE unavailable: " + e2);
      }
    }
    try
    {
      URL u = new URL("https://vancity.com/");
      u.openConnection();
    }
    catch (Exception e)
    {
      Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
      System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
    }
  }
  
  public static Java13 getInstance()
  {
    return instance;
  }
  
  public final String getVersion()
  {
    return "Java13";
  }
  
  protected final String retrieveSubjectX500(java.security.cert.X509Certificate cert)
  {
    return cert.getSubjectDN().toString();
  }
  
  protected final String retrieveIssuerX500(java.security.cert.X509Certificate cert)
  {
    return cert.getIssuerDN().toString();
  }
  
  protected final Certificate[] retrievePeerCerts(SSLSession sslSession)
    throws SSLPeerUnverifiedException
  {
    javax.security.cert.X509Certificate[] chain = sslSession.getPeerCertificateChain();
    java.security.cert.X509Certificate[] newChain = new java.security.cert.X509Certificate[chain.length];
    try
    {
      for (int i = 0; i < chain.length; i++)
      {
        javax.security.cert.X509Certificate javaxCert = chain[i];
        byte[] encoded = javaxCert.getEncoded();
        ByteArrayInputStream in = new ByteArrayInputStream(encoded);
        synchronized (Certificates.CF)
        {
          Certificate c = Certificates.CF.generateCertificate(in);
          newChain[i] = ((java.security.cert.X509Certificate)c);
        }
      }
    }
    catch (Exception e)
    {
      throw buildRuntimeExc
1 2 3 4 5 6 7 8 9 10 11 12 13

Further reading...

For more information on Java 1.5 Tiger, you may find Java 1.5 Tiger, A developer's Notebook by D. Flanagan and B. McLaughlin from O'Reilly of interest.

New!JAR listings


Copyright 2006-2017. Infinite Loop Ltd