not-yet-commons-ssl-0.3.11

sword);
    BuildResult br2 = null;
    KeyStore jks = null;
    if (jks != null)
    {
      jks = jks;
    }
    else if ((privateKey != null) && (privateKey.length > 0))
    {
      br2 = parse(privateKey, jksPassword, keyPassword);
      if (jks != null) {
        jks = jks;
      }
    }
    if (jks != null)
    {
      br1 = validate(jks, keyPassword);
      if (br1 == null) {
        return jks;
      }
    }
    List keys = keys;
    List chains = chains;
    boolean atLeastOneNotSet = (keys == null) || (chains == null) || (keys.isEmpty()) || (chains.isEmpty());
    if ((atLeastOneNotSet) && (br2 != null))
    {
      if ((keys != null) && (!keys.isEmpty())) {
        keys = keys;
      }
      if ((chains == null) || (chains.isEmpty())) {
        chains = chains;
      }
    }
    atLeastOneNotSet = (keys == null) || (chains == null) || (keys.isEmpty()) || (chains.isEmpty());
    if (atLeastOneNotSet)
    {
      String missing = "";
      if (keys == null) {
        missing = " [Private key missing (bad password?)]";
      }
      if (chains == null) {
        missing = missing + " [Certificate chain missing]";
      }
      throw new KeyStoreException("Can't build keystore:" + missing);
    }
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null, jksPassword);
    Iterator keysIt = keys.iterator();
    Iterator chainsIt = chains.iterator();
    int i = 1;
    while ((keysIt.hasNext()) && (chainsIt.hasNext()))
    {
      Key key = (Key)keysIt.next();
      Certificate[] c = (Certificate[])chainsIt.next();
      X509Certificate theOne = buildChain(key, c);
      String alias = "alias_" + i++;
      if (theOne != null)
      {
        c = Certificates.trimChain(c);
        alias = Certificates.getCN(theOne);
        alias = alias.replace(' ', '_');
      }
      ks.setKeyEntry(alias, key, keyPassword, c);
    }
    return ks;
  }
  
  public static X509Certificate buildChain(Key key, Certificate[] chain)
    throws CertificateException, KeyStoreException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException
  {
    X509Certificate theOne = null;
    if ((key instanceof RSAPrivateCrtKey))
    {
      RSAPrivateCrtKey rsa = (RSAPrivateCrtKey)key;
      BigInteger publicExponent = rsa.getPublicExponent();
      BigInteger modulus = rsa.getModulus();
      for (int i = 0; i < chain.length; i++)
      {
        X509Certificate c = (X509Certificate)chain[i];
        PublicKey pub = c.getPublicKey();
        if ((pub instanceof RSAPublicKey))
        {
          RSAPublicKey certKey = (RSAPublicKey)pub;
          BigInteger pe = certKey.getPublicExponent();
          BigInteger mod = certKey.getModulus();
          if ((publicExponent.equals(pe)) && (modulus.equals(mod))) {
            theOne = c;
          }
        }
      }
      if (theOne == null) {
        throw new KeyStoreException("Can't build keystore: [No certificates belong to the private-key]");
      }
      X509Certificate[] newChain = X509CertificateChainBuilder.buildPath(theOne, chain);
      Arrays.fill(chain, null);
      System.arraycopy(newChain, 0, chain, 0, newChain.length);
    }
    return theOne;
  }
  
  public static BuildResult validate(KeyStore jks, char[] keyPass)
    throws CertificateException, KeyStoreException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, UnrecoverableKeyException
  {
    Enumeration en = jks.aliases();
    boolean atLeastOneSuccess = false;
    boolean atLeastOneFailure = false;
    
    List keys = new LinkedList();
    List chains = new LinkedList();
    while (en.hasMoreElements())
    {
      String alias = (String)en.nextElement();
      if (jks.isKeyEntry(alias)) {
        try
        {
          PrivateKey key = (PrivateKey)jks.getKey(alias, keyPass);
          
          atLeastOneSuccess = true;
          Certificate[] chain = jks.getCertificateChain(alias);
          if (chain != null)
          {
            X509Certificate[] c = Certificates.x509ifyChain(chain);
            X509Certificate theOne = buildChain(key, c);
            if (theOne != null)
            {
              c = (X509Certificate[])Certificates.trimChain(c);
              jks.deleteEntry(alias);
              jks.setKeyEntry(alias, key, keyPass, c);
            }
            keys.add(key);
            chains.add(c);
          }
        }
        catch (GeneralSecurityException gse)
        {
          atLeastOneFailure = true;
        }
      }
    }
    if (!atLeastOneSuccess) {
      throw new KeyStoreException("No private keys found in keystore!");
    }
    return atLeastOneFailure ? new BuildResult(keys, chains, null) : null;
  }
  
  public static class BuildResult
  {
    protected final List keys;
    protected final List chains;
    protected final KeyStore jks;
    
    protected BuildResult(List keys, List chains, KeyStore jks)
    {
      if ((keys == null) || (keys.isEmpty())) {
        this.keys = null;
      } else {
        this.keys = Collections.unmodifiableList(keys);
      }
      this.jks = jks;
      List x509Chains = new LinkedList();
      if (chains != null)
      {
        Iterator it = chains.iterator();
        while (it.hasNext())
        {
          Certificate[] chain = (Certificate[])it.next();
          if ((chain != null) && (chain.length > 0))
          {
            int len = chain.length;
            X509Certificate[] x509 = new X509Certificate[len];
            for (int i = 0; i < x509.length; i++) {
              x509[i] = ((X509Certificate)chain[i]);
            }
            x509Chains.add(x509);
          }
        }
      }
      if ((x509Chains == null) || (x509Chains.isEmpty())) {
        this.chains = null;
      } else {
        this.chains = Collections.unmodifiableList(x509Chains);
      }
    }
  }
  
  public static BuildResult parse(byte[] stuff, char[] jksPass, char[] keyPass)
    throws IOException, CertificateException, KeyStoreException, ProbablyBadPasswordException
  {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Key key = null;
    Certificate[] chain = null;
    try
    {
      PKCS8Key pkcs8Key = new PKCS8Key(stuff, jksPass);
      key = pkcs8Key.getPrivateKey();
    }
    catch (ProbablyBadPasswordException pbpe)
    {
      throw pbpe;
    }
    catch (GeneralSecurityException gse) {}
    List pemItems = PEMUtil.decode(stuff);
    Iterator it = pemItems.iterator();
    LinkedList certificates = new LinkedList();
    while (it.hasNext())
    {
      PEMItem item = (PEMItem)it.next();
      byte[] derBytes = item.getDerBytes();
      String type = pemType.trim().toUpperCase();
      if ((type.startsWith("CERT")) || (type.startsWith("X509")) || (type.startsWith("PKCS7")))
      {
        ByteArrayInputStream in = new ByteArrayInputStream(derBytes);
        X509Certificate c = (X509Certificate)cf.generateCertificate(in);
        certificates.add(c);
      }
      chain = toChain(certificates);
    }
    if ((chain != null) || (key != null))
    {
      List chains = chain != null ? Collections.singletonList(chain) : null;
      List keys = key != null ? Collections.singletonList(key) : null;
      return new BuildResult(keys, chains, null);
    }
    boolean isProbablyPKCS12 = false;
    boolean isASN = false;
    ASN1Structure asn1 = null;
    try
    {
      asn1 = ASN1Util.analyze(stuff);
      isASN = true;
      isProbablyPKCS12 = oids.contains("1.2.840.113549.1.7.6");
      if ((!isProbablyPKCS12) && (bigPayload != null))
      {
        asn1 = ASN1Util.analyze(bigPayload);
        isProbablyPKCS12 = oids.contains("1.2.840.113549.1.7.6");
      }
    }
    catch (Exception e) {}
    ByteArrayInputStream stuffStream = new ByteArrayInputStream(stuff);
    
    BuildResult br = tryJKS(KeyStore.getDefaultType(), stuffStream, jksPass, keyPass);
    if (br == null)
    {
      br = tryJKS("jks", stuffStream, jksPass, keyPass);
      if (br == null)
      {
        br = tryJKS("jceks", stuffStream, jksPass, keyPass);
        if (br == null)
        {
          br = tryJKS("BKS", stuffStream, jksPass, keyPass);
          if (br == null) {
            br = tryJKS("UBER", stuffStream, jksPass, keyPass);
          }
        }
      }
    }
    if (br != null) {
      return br;
    }
    if (isASN)
    {
      if (isProbablyPKCS12) {
        return tryJKS("pkcs12", stuffStream, jksPass, null);
      }
    }
    else
    {
      stuffStream.reset();
      try
      {
        certificates = new LinkedList();
        Collection certs = cf.generateCertificates(stuffStream);
        it = certs.iterator();
        while (it.hasNext())
        {
          X509Certificate x509 = (X509Certificate)it.next();
          certificates.add(x509);
        }
        chain = toChain(certificates);
        if ((chain != null) && (chain.length > 0))
        {
          List chains = Collections.singletonList(chain);
          return new BuildResult(null, chains, null);
        }
      }
      catch (CertificateException ce) {}
      stuffStream.reset();
      try
      {
        Certificate c = cf.generateCertificate(stuffStream);
        X509Certificate x509 = (X509Certificate)c;
        chain = toChain(Collections.singleton(x509));
        if ((chain != null) && (chain.length > 0))
        {
          List chains = Collections.singletonList(chain);
          return new BuildResult(null, chains, null);
        }
      }
      catch (CertificateException ce) {}
    }
    br = tryJKS("pkcs12", stuffStream, jksPass, null);
    if (br != null)
    {
      System.out.println("Please report bug!");
      System.out.println("PKCS12 detection failed to realize this was PKCS12!");
      System.out.println(asn1);
      return br;
    }
    throw new KeyStoreException("failed to extract any certificates or private keys - maybe bad password?");
  }
  
  private static BuildResult tryJKS(String keystoreType, ByteArrayInputStream in, char[] jksPassword, char[] keyPassword)
    throws ProbablyBadPasswordException
  {
    in.reset();
    if ((keyPassword == null) || (keyPassword.length <= 0)) {
      keyPassword = jksPassword;
    }
    keystoreType = keystoreType.trim().toLowerCase();
    boolean isPKCS12 = "pkcs12".equalsIgnoreCase(keystoreType);
    try
    {
      Key key = null;
      Certificate[] chain = null;
      UnrecoverableKeyException uke = null;
      KeyStore jksKeyStore = KeyStore.getInstance(keystoreType);
      jksKeyStore.load(in, jksPassword);
      Enumeration en = jksKeyStore.aliases();
      while (en.hasMoreElements())
      {
        String alias = (String)en.nextElement();
        if (jksKeyStore.isKeyEntry(alias)) {
          try
          {
            key = jksKeyStore.getKey(alias, keyPassword);
            if ((key != null) && ((key instanceof PrivateKey)))
            {
              chain = jksKeyStore.getCertificateChain(alias);
              break;
            }
          }
          catch (UnrecoverableKeyException e)
          {
            uke = e;
          }
          catch (GeneralSecurityException gse) {}
        }
        if ((isPKCS12) && (en.hasMoreElements())) {
          System.out.println("what kind of weird pkcs12 file has more than one alias?");
        }
      }
      if ((key == null) && (uke != null)) {
        throw new ProbablyBadPasswordException("Probably bad JKS-Key password: " + uke);
      }
      if (isPKCS12) {
        jksKeyStore = null;
      }
      List keys = Collections.singletonList(key);
      List chains = Collections.singletonList(chain);
      return new BuildResult(keys, chains, jksKeyStore);
    }
    catch (ProbablyBadPasswordException pbpe)
    {
      throw pbpe;
    }
    catch (GeneralSecurityException gse)
    {
      return null;
    }
    catch (IOException ioe)
    {
      String msg = ioe.getMessage();
      msg = msg != null ? msg.trim().toLowerCase() : "";
      if (isPKCS12)
      {
        int x = msg.indexOf("failed to decrypt");
        int y = msg.indexOf("verify mac");
        x = Math.max(x, y);
        if (x >= 0) {
          throw new ProbablyBadPasswordException("Probably bad PKCS12 password: " + ioe);
        }
      }
      else
      {
        int x = msg.indexOf("password");
        if (x >= 0) {
          throw new ProbablyBadPasswordException("Probably bad JKS password: " + ioe);
        }
      }
    }
    return null;
  }
  
  private static X509Certificate[] toChain(Collection certs)
  {
    if ((certs != null) && (!certs.isEmpty()))
    {
      X509Certificate[] x509Chain = new X509Certificate[certs.size()];
      certs.toArray(x509Chain);
      return x509Chain;
    }
    return null;
  }
  
  public static void main(String[] args)
    throws Exception
  {
    if (args.length < 2)
    {
      System.out.println("KeyStoreBuilder:  creates '[alias].jks' (Java Key Store)");
      System.out.println("    -topk8 mode:  creates '[alias].pem' (x509 chain + unencrypted pkcs8)");
      System.out.println("[alias] will be set to the first CN value of the X509 certificate.");
      System.out.println("-------------------------------------------------------------------");
      System.out.println("Usage1: [password] [file:pkcs12]");
      System.out.println("Usage2: [password] [file:private-key] [file:certificate-chain]");
      System.out.println("Usage3: -topk8 [password] [file:jks]");
      System.out.println("-------------------------------------------------------------------");
      System.out.println("[private-key] can be openssl format, or pkcs8.");
      System.out.println("[password] decrypts [private-key], and also encrypts outputted JKS file.");
      System.out.println("All files can be PEM or DER.");
      System.exit(1);
    }
    char[] password = args[0].toCharArray();
    boolean toPKCS8 = false;
    if ("-topk8".equalsIgnoreCase(args[0]))
    {
      toPKCS8 = true;
      password = args[1].toCharArray();
      args[1] = args[2];
      args[2] = null;
    }
    FileInputStream fin1 = new FileInputStream(args[1]);
    byte[] bytes1 = Util.streamToBytes(fin1);
    byte[] bytes2 = null;
    if ((args.length > 2) && (args[2] != null))
    {
      FileInputStream fin2 = new FileInputStream(args[2]);
      bytes2 = Util.streamToBytes(fin2);
    }
    KeyStore ks = build(bytes1, bytes2, password);
    Enumeration en = ks.aliases();
    String alias = "keystorebuilder";
    
    int biggestKey = 0;
    while (en.hasMoreElements())
    {
      String s = (String)en.nextElement();
      try
      {
        PrivateKey pk = (PrivateKey)ks.getKey(s, password);
        byte[] encoded = pk.getEncoded();
        int len = encoded != null ? encoded.length : 0;
        if (len >= biggestKey)
        {
          biggestKey = len;
          alias = s;
        }
      }
      catch (Exception e) {}
    }
    String suffix = toPKCS8 ? ".pem" : ".jks";
    String fileName = alias;
    Certificate[] chain = ks.getCertificateChain(alias);
    if ((chain != null) && (chain[0] != null))
    {
      String cn = Certificates.getCN((X509Certificate)chain[0]);
      cn = cn != null ? cn.trim() : "";
      if (!"".equals(cn)) {
        fileName = cn;
      }
    }
    File f = new File(fileName + suffix);
    int count = 1;
    while (f.exists())
    {
      f = new File(alias + "_" + count + suffix);
      count++;
    }
    FileOutputStream fout = new FileOutputStream(f);
    if (toPKCS8)
    {
      List pemItems = new LinkedList();
      PrivateKey key = (PrivateKey)ks.getKey(alias, password);
      chain = ks.getCertificateChain(alias);
      byte[] pkcs8DerBytes = null;
      if ((key instanceof RSAPrivateCrtKey))
      {
        RSAPrivateCrtKey rsa = (RSAPrivateCrtKey)key;
        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(new DERInteger(BigInteger.ZERO));
        vec.add(new DERInteger(rsa.getModulus()));
        vec.add(new DERInteger(rsa.getPublicExponent()));
        vec.add(new DERInteger(rsa.getPrivateExponent()));
        vec.add(new DERInteger(rsa.getPrimeP()));
        vec.add(new DERInteger(rsa.getPrimeQ()));
        vec.add(new DERInteger(rsa.getPrimeExponentP()));
        vec.add(new DERInteger(rsa.getPrimeExponentQ()));
        vec.add(new DERInteger(rsa.getCrtCoefficient()));
        DERSequence seq = new DERSequence(vec);
        byte[] derBytes = PKCS8Key.encode(seq);
        PKCS8Key pkcs8 = new PKCS8Key(derBytes, null);
        pkcs8DerBytes = pkcs8.getDecryptedBytes();
      }
      else if ((key instanceof DSAPrivateKey))
      {
        DSAPrivateKey dsa = (DSAPrivateKey)key;
        DSAParams params = dsa.getParams();
        BigInteger g = params.getG();
        BigInteger p = params.getP();
        BigInteger q = params.getQ();
        BigInteger x = dsa.getX();
        BigInteger y = q.modPow(x, p);
        
        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(new DERInteger(BigInteger.ZERO));
        vec.add(new DERInteger(p));
        vec.add(new DERInteger(q));
        vec.add(new DERInteger(g));
        vec.add(new DERInteger(y));
        vec.add(new DERInteger(x));
        DERSequence seq = new DERSequence(vec);
        byte[] derBytes = PKCS8Key.encode(seq);
        PKCS8Key pkcs8 = new PKCS8Key(derBytes, null);
        pkcs8DerBytes = pkcs8.getDecryptedBytes();
      }
      if ((chain != null) && (chain.length > 0)) {
        for (int i = 0; i < chain.length; i++)
        {
          X509Certificate x509 = (X509Certificate)chain[i];
          byte[] derBytes = x509.getEncoded();
          PEMItem item = new PEMItem(derBytes, "CERTIFICATE");
          pemItems.add(item);
        }
      }
      if (pkcs8DerBytes != null)
      {
        PEMItem item = new PEMItem(pkcs8DerBytes, "PRIVATE KEY");
        pemItems.add(item);
      }
      byte[] pem = PEMUtil.encode(pemItems);
      fout.write(pem);
    }
    else
    {
      KeyStore jks = KeyStore.getInstance(KeyStore.getDefaultType());
      jks.load(null, password);
      jks.setKeyEntry(alias, ks.getKey(alias, password), password, ks.getCertificateChain(alias));
      jks.store(fout, password);
    }
    fout.flush();
    fout.close();
    System.out.println("Successfuly wrote: [" + f.getPath() + "]");
  }
}

/* Location:
 * Qualified Name:     org.apache.commons.ssl.KeyStoreBuilder
 * 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.PrintStream;
import java.security.GeneralSecurityException;
import javax.net.SocketFactory;

public class LDAPSocket
  extends SSLClient
{
  private static final LDAPSocket instance;
  
  static
  {
    LDAPSocket sf = null;
    try
    {
      sf = new LDAPSocket();
    }
    catch (Exception e)
    {
      System.out.println("could not create LDAPSocket: " + e);
      e.printStackTrace();
    }
    finally
    {
      instance = sf;
    }
  }
  
  private LDAPSocket()
    throws GeneralSecurityException, IOException
  {
    if (TrustMaterial.JSSE_CACERTS != null) {
      setTrustMaterial(TrustMaterial.JSSE_CACERTS);
    } else {
      setTrustMaterial(TrustMaterial.CACERTS);
    }
  }
  
  public static SocketFactory getDefault()
  {
    return getInstance();
  }
  
  public static LDAPSocket getInstance()
  {
    return instance;
  }
}

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

import org.apache.log4j.Logger;

final class LogHelper
{
  private final Logger l;
  
  LogHelper(Class c)
  {
    l = Logger.getLogger(c);
  }
  
  LogHelper(String s)
  {
    l = Logger.getLogger(s);
  }
  
  void debug(Object o)
  {
    l.debug(o);
  }
  
  void debug(Object o, Throwable t)
  {
    l.debug(o, t);
  }
  
  void info(Object o)
  {
    l.info(o);
  }
  
  void info(Object o, Throwable t)
  {
    l.info(o, t);
  }
  
  void warn(Object o)
  {
    l.warn(o);
  }
  
  void warn(Object o, Throwable t)
  {
    l.warn(o, t);
  }
  
  void error(Object o)
  {
    l.error(o);
  }
  
  void error(Object o, Throwable t)
  {
    l.error(o, t);
  }
  
  void fatal(Object o)
  {
    l.fatal(o);
  }
  
  void fatal(Object o, Throwable t)
  {
    l.fatal(o, t);
  }
  
  boolean isDebugEnabled()
  {
    return l.isDebugEnabled();
  }
  
  boolean isInfoEnabled()
  {
    return l.isInfoEnabled();
  }
  
  Object getLog4jLogger()
  {
    return l;
  }
}

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

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class LogWrapper
{
  static final String[] LEVELS = { "+", " ", "!", "*", "#" };
  static final String TIMESTAMP_PATTERN = "zzz:yyyy-MM-dd/HH:mm:ss.SSS";
  static final int TIMESTAMP_LENGTH = "zzz:yyyy-MM-dd/HH:mm:ss.SSS".length();
  static final String LINE_SEPARATOR = System.getProperty("line.separator");
  static final DateFormat DF = new SimpleDateFormat("zzz:yyyy-MM-dd/HH:mm:ss.SSS");
  private static final LogWrapper NOOP = new LogWrapper();
  private static final boolean DEBUG = true;
  public static final boolean log4j;
  private static volatile OutputStream backup = System.out;
  private static volatile PrintStream wrappingPrintStream = null;
  private final LogHelper h;
  
  static
  {
    boolean avail = false;
    try
    {
      LogHelper lh = new LogHelper(LogWrapper.class);
      lh.hashCode();
      avail = true;
    }
    catch (Throwable t)
    {
      avail = false;
    }
    finally
    {
      log4j = avail;
    }
  }
  
  public static boolean isLog4jAvailable()
  {
    return log4j;
  }
  
  public static LogWrapper getLogger(Class c)
  {
    return log4j ? new LogWrapper(c) : NOOP;
  }
  
  public static LogWrapper getLogger(String s)
  {
    return log4j ? new LogWrapper(s) : NOOP;
  }
  
  private LogWrapper()
  {
    h = null;
  }
  
  private LogWrapper(Class c)
  {
    h = new LogHelper(c);
  }
  
  private LogWrapper(String s)
  {
    h = new LogHelper(s);
  }
  
  public void debug(Object o)
  {
    if (t(0, o, null)) {
      h.debug(o);
    }
  }
  
  public void debug(Object o, Throwable t)
  {
    if (t(0, o, t)) {
      h.debug(o, t);
    }
  }
  
  public void info(Object o)
  {
    if (t(1, o, null)) {
      h.info(o);
    }
  }
  
  public void info(Object o, Throwable t)
  {
    if (t(1, o, t)) {
      h.info(o, t);
    }
  }
  
  public void warn(Object o)
  {
    if (t(2, o, null)) {
      h.warn(o);
    }
  }
  
  public void warn(Object o, Throwable t)
  {
    if (t(2, o, t)) {
      h.warn(o, t);
    }
  }
  
  public void error(Object o)
  {
    if (t(3, o, null)) {
      h.error(o);
    }
  }
  
  public void error(Object o, Throwable t)
  {
    if (t(3, o, t)) {
      h.error(o, t);
    }
  }
  
  public void fatal(Object o)
  {
    if (t(4, o, null)) {
      h.fatal(o);
    }
  }
  
  public void fatal(Object o, Throwable t)
  {
    if (t(4, o, t)) {
      h.fatal(o, t);
    }
  }
  
  public boolean isDebugEnabled()
  {
    return log4j ? h.isDebugEnabled() : true;
  }
  
  public boolean isInfoEnabled()
  {
    return (!log4j) || (h.isInfoEnabled());
  }
  
  public Object getLog4jLogger()
  {
    return log4j ? h.getLog4jLogger() : null;
  }
  
  private boolean t(int level, Object o, Throwable t)
  {
    if (log4j) {
      return true;
    }
    if (backup != null)
    {
      String s = "";
      if (o != null) {
        try
        {
          s = (String)o;
        }
        catch (ClassCastException cce)
        {
          s = o.toString();
        }
      }
      int len = s.length() + TIMESTAMP_LENGTH + 9;
      String timestamp = DF.format(new Date());
      StringBuffer buf = new StringBuffer(len);
      buf.append(timestamp);
      if (LEVELS[level].length() == 1)
      {
        buf.append(LEVELS[level]);
      }
      else
      {
        buf.append(' ');
        buf.append(LEVELS[level]);
        buf.append(' ');
      }
      buf.append(s);
      buf.append(LINE_SEPARATOR);
      s = buf.toString();
      byte[] logBytes = s.getBytes();
      try
      {
        if (t == null) {
          backup.write(logBytes);
        } else {
          synchronized (backup)
          {
            backup.write(logBytes);
            if (t != null)
            {
              if (wrappingPrintStream == null) {
                wrappingPrintStream = new PrintStream(backup, false);
              }
              t.printStackTrace(wrappingPrintStream);
              wrappingPrintStream.flush();
            }
          }
        }
        backup.flush();
      }
      catch (IOException ioe)
      {
        throw new RuntimeException(ioe.toString());
      }
    }
    return false;
  }
  
  public static void setBackupLogFile(String f)
    throws IOException
  {
    if (!log4j)
    {
      OutputStream out = new FileOutputStream(f, true);
      out = new BufferedOutputStream(out);
      setBackupStream(out);
    }
  }
  
  public static void setBackupStream(OutputStream os)
  {
    if (backup != null) {
      synchronized (backup)
      {
        wrappingPrintStream = null;
        backup = os;
      }
    }
    wrappingPrintStream = null;
    backup = os;
  }
  
  public static OutputStream getBackupStream()
  {
    return backup;
  }
}

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

public class OpenSSL$CipherInfo
{
  public final String javaCipher;
  public final String blockMode;
  public final int keySize;
  public final int ivSize;
  public final boolean des2;
  
  public OpenSSL$CipherInfo(String javaCipher, String blockMode, int keySize, int ivSize, boolean des2)
  {
    this.javaCipher = javaCipher;
    this.blockMode = blockMode;
    this.keySize = keySize;
    this.ivSize = ivSize;
    this.des2 = des2;
  }
  
  public String toString()
  {
    return javaCipher + "/" + blockMode + " " + keySize + "bit  des2=" + des2;
  }
}

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

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.StringTokenizer;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import org.apache.commons.ssl.util.Hex;

public class OpenSSL
{
  public static byte[] decrypt(String cipher, char[] pwd, byte[] encrypted)
    throws IOException, GeneralSecurityException
  {
    ByteArrayInputStream in = new ByteArrayInputStream(encrypted);
    InputStream decrypted = decrypt(cipher, pwd, in);
    return Util.streamToBytes(decrypted);
  }
  
  public static InputStream decrypt(String cipher, char[] pwd, InputStream encrypted)
    throws IOException, GeneralSecurityException
  {
    CipherInfo cipherInfo = lookup(cipher);
    boolean salted = false;
    
    byte[] saltLine = Util.streamToBytes(encrypted, 16);
    if (saltLine.length <= 0) {
      throw new IOException("encrypted InputStream is empty");
    }
    String firstEightBytes = "";
    if (saltLine.length >= 8) {
      firstEightBytes = new String(saltLine, 0, 8);
    }
    if ("SALTED__".equalsIgnoreCase(firstEightBytes))
    {
      salted = true;
    }
    else if (Base64.isArrayByteBase64(saltLine))
    {
      InputStream head = new ByteArrayInputStream(saltLine);
      
      encrypted = new ComboInputStream(head, encrypted);
      encrypted = new Base64InputStream(encrypted);
      saltLine = Util.streamToBytes(encrypted, 16);
      if (saltLine.length >= 8) {
        firstEightBytes = new String(saltLine, 0, 8);
      }
      if ("SALTED__".equalsIgnoreCase(firstEightBytes)) {
        salted = true;
      }
    }
    byte[] salt = null;
    if (salted)
    {
      salt = new byte[8];
      System.arraycopy(saltLine, 8, salt, 0, 8);
    }
    else
    {
      InputStream head = new ByteArrayInputStream(saltLine);
      encrypted = new ComboInputStream(head, encrypted);
    }
    int keySize = keySize;
    int ivSize = ivSize;
    boolean des2 = des2;
    DerivedKey dk = deriveKey(pwd, salt, keySize, ivSize, des2);
    Cipher c = PKCS8Key.generateCipher(javaCipher, blockMode, dk, des2, null, true);
    
    return new CipherInputStream(encrypted, c);
  }
  
  public static byte[] encrypt(String cipher, char[] pwd, byte[] data)
    throws IOException, GeneralSecurityException
  {
    return encrypt(cipher, pwd, data, true);
  }
  
  public static InputStream encrypt(String cipher, char[] pwd, InputStream data)
    throws IOException, GeneralSecurityException
  {
    return encrypt(cipher, pwd, data, true);
  }
  
  public static byte[] encrypt(String cipher, char[] pwd, byte[] data, boolean toBase64)
    throws IOException, GeneralSecurityException
  {
    return encrypt(cipher, pwd, data, toBase64, true);
  }
  
  public static InputStream encrypt(String cipher, char[] pwd, InputStream data, boolean toBase64)
    throws IOException, GeneralSecurityException
  {
    return encrypt(cipher, pwd, data, toBase64, true);
  }
  
  public static byte[] encrypt(String cipher, char[] pwd, byte[] data, boolean toBase64, boolean useSalt)
    throws IOException, GeneralSecurityException
  {
    ByteArrayInputStream in = new ByteArrayInputStream(data);
    InputStream encrypted = encrypt(cipher, pwd, in, toBase64, useSalt);
    return Util.streamToBytes(encrypted);
  }
  
  public static InputStream encrypt(String cipher, char[] pwd, InputStream data, boolean toBase64, boolean useSalt)
    throws IOException, GeneralSecurityException
  {
    CipherInfo cipherInfo = lookup(cipher);
    byte[] salt = null;
    if (useSalt)
    {
      SecureRandom rand = SecureRandom.getInstance("SHA1PRNG");
      salt = new byte[8];
      rand.nextBytes(salt);
    }
    int keySize = keySize;
    int ivSize = ivSize;
    boolean des2 = des2;
    DerivedKey dk = deriveKey(pwd, salt, keySize, ivSize, des2);
    Cipher c = PKCS8Key.generateCipher(javaCipher, blockMode, dk, des2, null, false);
    
    InputStream cipherStream = new CipherInputStream(data, c);
    if (useSalt)
    {
      byte[] saltLine = new byte[16];
      byte[] salted = "Salted__".getBytes();
      System.arraycopy(salted, 0, saltLine, 0, salted.length);
      System.arraycopy(salt, 0, saltLine, salted.length, salt.length);
      InputStream head = new ByteArrayInputStream(saltLine);
      cipherStream = new ComboInputStream(head, cipherStream);
    }
    if (toBase64) {
      cipherStream = new Base64InputStream(cipherStream, true);
    }
    return cipherStream;
  }
  
  public static byte[] decrypt(String cipher, byte[] key, byte[] iv, byte[] encrypted)
    throws IOException, GeneralSecurityException
  {
    ByteArrayInputStream in = new ByteArrayInputStream(encrypted);
    InputStream decrypted = decrypt(cipher, key, iv, in);
    return Util.streamToBytes(decrypted);
  }
  
  public static InputStream decrypt(String cipher, byte[] key, byte[] iv, InputStream encrypted)
    throws IOException, GeneralSecurityException
  {
    CipherInfo cipherInfo = lookup(cipher);
    byte[] firstLine = Util.streamToBytes(encrypted, 16);
    if (Base64.isArrayByteBase64(firstLine))
    {
      InputStream head = new ByteArrayInputStream(firstLine);
      
      encrypted = new ComboInputStream(head, encrypted);
      encrypted = new Base64InputStream(encrypted);
    }
    else
    {
      InputStream head = new ByteArrayInputStream(firstLine);
      encrypted = new ComboInputStream(head, encrypted);
    }
    int keySize = keySize;
    int ivSize = ivSize;
    if (key.length == keySize / 4) {
      key = Hex.decode(key);
    }
    if (iv.length == ivSize / 4) {
      iv = Hex.decode(iv);
    }
    DerivedKey dk = new DerivedKey(key, iv);
    Cipher c = PKCS8Key.generateCipher(javaCipher, blockMode, dk, des2, null, true);
    
    return new CipherInputStream(encrypted, c);
  }
  
  public static byte[] encrypt(String cipher, byte[] key, byte[] iv, byte[] data)
    throws IOException, GeneralSecurityException
  {
    return encrypt(cipher, key, iv, data, true);
  }
  
  public static byte[] encrypt(String cipher, byte[] key, byte[] iv, byte[] data, boolean toBase64)
    throws IOException, GeneralSecurityException
  {
    ByteArrayInputStream in = new ByteArrayInputStream(data);
    InputStream encrypted = encrypt(cipher, key, iv, in, toBase64);
    return Util.streamToBytes(encrypted);
  }
  
  public static InputStream encrypt(String cipher, byte[] key, byte[] iv, InputStream data)
    throws IOException, GeneralSecurityException
  {
    return encrypt(cipher, key, iv, data, true);
  }
  
  public static InputStream encrypt(String cipher, byte[] key, byte[] iv, InputStream data, boolean toBase64)
    throws IOException, GeneralSecurityException
  {
    CipherInfo cipherInfo = lookup(cipher);
    int keySize = keySize;
    int ivSize = ivSize;
    if (key.length == keySize / 4) {
      key = Hex.decode(key);
    }
    if (iv.length == ivSize / 4) {
      iv = Hex.decode(iv);
    }
    DerivedKey dk = new DerivedKey(key, iv);
    Cipher c = PKCS8Key.generateCipher(javaCipher, blockMode, dk, des2, null, false);
    
    InputStream cipherStream = new CipherInputStream(data, c);
    if (toBase64) {
      cipherStream = new Base64InputStream(cipherStream, true);
    }
    return cipherStream;
  }
  
  public static DerivedKey deriveKey(char[] password, byte[] salt, int keySize, boolean des2)
    throws NoSuchAlgorithmException
  {
    return deriveKey(password, salt, keySize, 0, des2);
  }
  
  public static DerivedKey deriveKey(char[] password, byte[] salt, int keySize, int ivSize, boolean des2)
    throws NoSuchAlgorithmException
  {
    if (des2) {
      keySize = 128;
    }
    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] pwdAsBytes = new byte[password.length];
    for (int i = 0; i < password.length; i++) {
      pwdAsBytes[i] = ((byte)password[i]);
    }
    md.reset();
    byte[] keyAndIv = new byte[keySize / 8 + ivSize / 8];
    if ((salt == null) || (salt.length == 0)) {
      salt = null;
    }
    int currentPos = 0;
    while (currentPos < keyAndIv.length)
    {
      md.update(pwdAsBytes);
      if (salt != null) {
        md.update(salt, 0, 8);
      }
      byte[] result = md.digest();
      int stillNeed = keyAndIv.length - currentPos;
      if (result.length > stillNeed)
      {
        byte[] b = new byte[stillNeed];
        System.arraycopy(result, 0, b, 0, b.length);
        result = b;
      }
      System.arraycopy(result, 0, keyAndIv, currentPos, result.length);
      currentPos += result.length;
      if (currentPos < keyAndIv.length)
      {
        md.reset();
        md.update(result);
      }
    }
    if (des2)
    {
      keySize = 192;
      byte[] buf = new byte[keyAndIv.length + 8];
      
      System.arraycopy(keyAndIv, 0, buf, 0, 16);
      if (ivSize > 0) {
        System.arraycopy(keyAndIv, 16, buf, 24, keyAndIv.length - 16);
      }
      keyAndIv = buf;
      
      System.arraycopy(keyAndIv, 0, keyAndIv, 16, 8);
    }
    if (ivSize == 0) {
      return new DerivedKey(keyAndIv, salt);
    }
    byte[] key = new byte[keySize / 8];
    byte[] iv = new byte[ivSize / 8];
    System.arraycopy(keyAndIv, 0, key, 0, key.length);
    System.arraycopy(keyAndIv, key.length, iv, 0, iv.length);
    return new DerivedKey(key, iv);
  }
  
  public static class CipherInfo
  {
    public final String javaCipher;
    public final String blockMode;
    public final int keySize;
    public final int ivSize;
    public final boolean des2;
    
    public CipherInfo(String javaCipher, String blockMode, int keySize, int ivSize, boolean des2)
    {
      this.javaCipher = javaCipher;
      this.blockMode = blockMode;
      this.keySize = keySize;
      this.ivSize = ivSize;
      this.des2 = des2;
    }
    
    public String toString()
    {
      return javaCipher + "/" + blockMode + " " + keySize + "bit  des2=" + des2;
    }
  }
  
  public static CipherInfo lookup(String openSSLCipher)
  {
    openSSLCipher = openSSLCipher.trim();
    if (openSSLCipher.charAt(0) == '-') {
      openSSLCipher = openSSLCipher.substring(1);
    }
    String javaCipher = openSSLCipher.toUpperCase();
    String blockMode = "CBC";
    int keySize = -1;
    int ivSize = 64;
    boolean des2 = false;
    
    StringTokenizer st = new StringTokenizer(openSSLCipher, "-");
    if (st.hasMoreTokens())
    {
      javaCipher = st.nextToken().toUpperCase();
      if (st.hasMoreTokens())
      {
        String tok = st.nextToken();
        if (st.hasMoreTokens())
        {
          try
          {
            keySize = Integer.parseInt(tok);
          }
          catch (NumberFormatException nfe)
          {
            String upper = tok.toUpperCase();
            if (upper.startsWith("EDE3"))
            {
              javaCipher = "DESede";
            }
            else if (upper.startsWith("EDE"))
            {
              javaCipher = "DESede";
              des2 = true;
            }
          }
          blockMode = st.nextToken().toUpperCase();
        }
        else
        {
          try
          {
            keySize = Integer.parseInt(tok);
          }
          catch (NumberFormatException nfe)
          {
            blockMode = tok.toUpperCase();
            if (blockMode.startsWith("EDE3"))
            {
              javaCipher = "DESede";
              blockMode = "ECB";
            }
            else if (blockMode.startsWith("EDE"))
            {
              javaCipher = "DESede";
              blockMode = "ECB";
              des2 = true;
            }
          }
        }
      }
    }
    if (javaCipher.startsWith("BF"))
    {
      javaCipher = "Blowfish";
    }
    else if (javaCipher.startsWith("TWOFISH"))
    {
      javaCipher = "Twofish";
      ivSize = 128;
    }
    else if (javaCipher.startsWith("IDEA"))
    {
      javaCipher = "IDEA";
    }
    else if (javaCipher.startsWith("CAST6"))
    {
      javaCipher = "CAST6";
      ivSize = 128;
    }
    else if (javaCipher.startsWith("CAST"))
    {
      javaCipher = "CAST5";
    }
    else if (javaCipher.startsWith("GOST"))
    {
      keySize = 256;
    }
    else if (javaCipher.startsWith("DESX"))
    {
      javaCipher = "DESX";
    }
    else if ("DES3".equals(javaCipher))
    {
      javaCipher = "DESede";
    }
    else if ("DES2".equals(javaCipher))
    {
      javaCipher = "DESede";
      des2 = true;
    }
    else if (javaCipher.startsWith("RIJNDAEL"))
    {
      javaCipher = "Rijndael";
      ivSize = 128;
    }
    else if (javaCipher.startsWith("SEED"))
    {
      javaCipher = "SEED";
      ivSize = 128;
    }
    else if (javaCipher.startsWith("SERPENT"))
    {
      javaCipher = "Serpent";
      ivSize = 128;
    }
    else if (javaCipher.startsWith("Skipjack"))
    {
      javaCipher = "Skipjack";
      ivSize = 128;
    }
    else if (javaCipher.startsWith("RC6"))
    {
      javaCipher = "RC6";
      ivSize = 128;
    }
    else if (javaCipher.startsWith("TEA"))
    {
      javaCipher = "TEA";
    }
    else if (javaCipher.startsWith("XTEA"))
    {
      javaCipher = "XTEA";
    }
    else if (javaCipher.startsWith("AES"))
    {
      if (javaCipher.startsWith("AES128")) {
        keySize = 128;
      } else if (javaCipher.startsWith("AES192")) {
        keySize = 192;
      } else if (javaCipher.startsWith("AES256")) {
        keySize = 25
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