⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tlsconfig.java

📁 jxme的一些相关程序,主要是手机上程序开发以及手机和计算机通信的一些程序资料,程序编译需要Ant支持
💻 JAVA
字号:
/************************************************************************
 *
 * $Id: TlsConfig.java,v 1.2 2002/03/04 21:42:58 echtcherbina Exp $
 *
 * Copyright (c) 2001 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *       Sun Microsystems, Inc. for Project JXTA."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA"
 *    must not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact Project JXTA at http://www.jxta.org.
 *
 * 5. Products derived from this software may not be called "JXTA",
 *    nor may "JXTA" appear in their name, without prior written
 *    permission of Sun.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL SUN MICROSYSTEMS OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of Project JXTA.  For more
 * information on Project JXTA, please see
 * <http://www.jxta.org/>.
 *
 * This license is based on the BSD license adopted by the Apache Foundation.
 *********************************************************************************/

package net.jxta.impl.endpoint.tls;

import java.io.IOException;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;

import COM.claymoresystems.ptls.SSLDebug;

import org.apache.log4j.Category; import org.apache.log4j.Priority;

public class TlsConfig {

  private static final Category LOG = Category.getInstance(TlsConfig.class.getName());
  private static final boolean wantDH = false;

  static String passitOn = null;

  // Method that configurator can call to see if
  // we will recreate certs
  public static boolean willConfigureTls() {

    try {

      String pce = JTlsUtil.getPCEPath();
      File fpce = new File(pce);

      if (!fpce.exists()) return true;

      // check the children
      if (!allPCEChildrenExist()) return true;

    } catch (Exception s) {

      return true;

    }
    return false;

  }

  public static void init(String principal, String password)
  {

    // Set SSL debugging if requested
    if (LOG.getChainedPriority().equals(Priority.INFO)) {

      // SSLDebug.setDebug(SSLDebug.DEBUG_JXTA);
      // DEBUG_CRYPTO: Watch TLS crypto traces
      //  DEBUG_STATE:  TLS Handshake state changes
      SSLDebug.setDebug(SSLDebug.DEBUG_STATE);

    }

    // SSLDebug.setDebug(SSLDebug.DEBUG_JXTA);
    SSLDebug.debug(SSLDebug.DEBUG_JXTA, "TlsConfig, peer = " + principal +
		   ", password = " + password + "\n");

    // See if the certificate paths are there.
    String pce = JTlsUtil.getPCEPath();// parent directory
    File fpce = new File(pce);

    boolean createPse = false;	// for personal security env.
    try {

      if (!fpce.exists()) {

	// create all required paths
	fpce.mkdir();
	makeChildren();
	createPse = true;

      } else if (!allPCEChildrenExist()) {
	  // remove those that do
	  removeAllChildren();

	  // make all children and password file
	  makeChildren();
	  createPse = true;
      } else {
	// See if principal has changed
	/**
	 * We cannot change certs if the principal changes
	 * because certs are distributed in peer adv, and
	 * these are bound to peer-id.
	 *
	 * CN=principal is in the cert but this is harmless.
	 * For now the code to check for change in principal
	 * is commented out. We need to address binding
	 * root certs to peer-id later because it is not
	 * portable across different peers.
	 */
	boolean principalOK = true;

	// try {
	// principalOK = JTlsUtil.principalIsIssuer(principal);
	// } catch (Exception e) {
	// principal = true;	// Try later. Old cert OK for now.
	// }

	if (!principalOK) {
	  // remove the pse world
	  removeAllChildren();

	  // put back the directories
	  makeChildren();

	  createPse = true;
	}
      }

    } catch (Exception s) {

      if (LOG.isEnabledFor(Priority.FATAL))
	LOG.fatal("Cert generation failed", s);
      return;

    }

    if (createPse) {
      try {

	SSLDebug.debug(SSLDebug.DEBUG_JXTA, "TlsConfig: Generating certs ...");

	System.out.println("\nSecurity initialization in progress.\nThis will take 10 or more seconds ...\n");

	// Generate the certifcates if required.
	PeerCerts.generateCerts(principal, password, wantDH);

	// and the password file
	JTlsUtil.createPasswdFile(password, false);

      } catch (Exception e) {

	if (LOG.isEnabledFor(Priority.FATAL))
	  LOG.fatal("Cert generation failed", e);
	return;
      }
    } else {
      // see if we have gone from the default password to a different
      // password. If so, then recreate the password file, decrypt/encrypt
      // the pass phrase with the new password.
      if ((password.compareTo(JTlsDefs.DEFAULTPWD) != 0) &&
	  JTlsUtil.validPasswd(JTlsDefs.DEFAULTPWD)) {

	try {
	  // Create the new password file
	  JTlsUtil.createPasswdFile(password, true);

	  // Read passphrase file with this with the old password
	  String phraseFile = JTlsUtil.getPCEClientPath() + JTlsDefs.PASSPHRASE;

	  String pfstr64 = JTlsUtil.readPassPhrase(phraseFile, JTlsDefs.DEFAULTPWD);

	  // Write the passphrase back encrypted with passwd
	  PeerCerts.writePassphrase(phraseFile, pfstr64, password);
	} catch (Exception e) {

	  if (LOG.isEnabledFor(Priority.FATAL))
	    LOG.fatal("Cannot create password file:", e);
	  return;
	}

      }
    }

    // Some debugging to check the password's validity
    // We should always have a valid password!
    if (SSLDebug.getDebug(SSLDebug.DEBUG_JXTA)) {
      if (JTlsUtil.validPasswd(password))
	System.out.println(password + " VALID");
      else
	System.out.println(password + " NOT VALID");
    }

    // if (SSLDebug.getDebug(SSLDebug.DEBUG_JXTA)) {
    //  try {
	// A little test code
    // String rc = getRootCert();
    //	System.out.println("\nRootCert:\n" + rc);
    //
    //	// And write it to a file
    //	JTlsUtil.writeRootCert(rc, "test.pem");
    //
    //	// And verify the certificate
    //	if (!JTlsUtil.verifySignedCert("test.pem", "test.pem")) {
    //	  System.out.println("test.pem is not valid");
    //	} else {
    //	  System.out.println("test.pem is valid");
    //	}
    //
    //      } catch (Exception e) {
    //	System.out.println("Exception testing cert: " + e.getMessage());
    //      }
    // }

    if (LOG.isEnabledFor(Priority.INFO)) LOG.info("Cert generation OK");

    SSLDebug.debug(SSLDebug.DEBUG_JXTA, "Cert generation OK");
    passitOn = new String(password);
  }

  // Create root, client and password subdirectories
  static void makeChildren()
    throws SecurityException, IOException {

      String client = JTlsUtil.getPCEClientPath();
      String root = JTlsUtil.getPCERootPath();
      String pwd = JTlsUtil.getPCEPasswdPath();

      File fc = new File(client);
      fc.mkdir();

      File fr = new File(root);
      fr.mkdir();

      File fp = new File(pwd);
      fr.mkdir();

  }

  // The current directory hierarchy is one level.
  // Keep the code simple here.
  static void removeAllChildren()
    throws SecurityException {

      String client = JTlsUtil.getPCEClientPath();
      String root = JTlsUtil.getPCERootPath();
      String pwd = JTlsUtil.getPCEPasswdPath();

      File fc = new File(client);
      File fr = new File(root);
      File fp = new File(pwd);

      String[] clientChildren = fc.list();
      String[] rootChildren = fr.list();
      String[] pwdChildren = fp.list();

      SSLDebug.debug(SSLDebug.DEBUG_JXTA, "Removing child files");

      removeDir(fc, clientChildren);
      removeDir(fr, rootChildren);
      removeDir(fp, pwdChildren);

  }

  // Remove a directory and its children.
  static void removeDir(File dir, String[] children)
    throws SecurityException
  {
    if (children != null) {
      int n = children.length;

      if (children != null && n > 0) {
	for (int i = 0; i < n; i++) {

	  File rm = new File(children[i]);
	  rm.delete();

	  SSLDebug.debug(SSLDebug.DEBUG_JXTA, " " + children[i]);

	}
      }
    }
    // remove parent
    if (dir.exists()) dir.delete();
  }

  // See if all PCE child directories exist
  // There are only two.
  static boolean allPCEChildrenExist()
    throws SecurityException {
      String client = JTlsUtil.getPCEClientPath();
      String root = JTlsUtil.getPCERootPath();
      String pwd = JTlsUtil.getPCEPasswdPath();

      File fc = new File(client);
      File fr = new File(root);
      File fp = new File(pwd);

      if (!fc.exists() || !fr.exists() || !fp.exists()) {
	return false;
      }

      // verify certs are there and valid
      if (wantDH) {

	String dhfile = JTlsUtil.getPCEPath() + JTlsDefs.DHFILE;
	File f = new File(dhfile);

	if (!f.exists()) {
	  SSLDebug.debug(SSLDebug.DEBUG_JXTA, "DH file does not exist!");
	  return false;
	}
      }

      // check for service and root certs, phrase file, and passwd file
      String rootFile = root + JTlsDefs.CLIENTROOT;
      String clientFile = client + JTlsDefs.CLIENTSERVICE;
      String phraseFile = client + JTlsDefs.PASSPHRASE;
      String pwdFile = pwd + JTlsDefs.PASSWORDFILE;

      // Celebrate Fortran variable name lengths!
      File f = new File(rootFile);
      File g = new File(clientFile);
      File h = new File(phraseFile);
      File i = new File(pwdFile);

      if (!f.exists() || !g.exists() || !h.exists() || !i.exists()) {

	SSLDebug.debug(SSLDebug.DEBUG_JXTA,
		       "Missing certificate, passphrase, or password file.");

	return false;
      }

      // Let's verify the signature
      if (JTlsUtil.verifySignedCert(rootFile, clientFile)) {
	return true;
      } else {

	// SSLDebug.debug(SSLDebug.DEBUG_JXTA, "Cert signature not valid!");
	// return false;
	// NOTE: Verify cert needs to be fixed in pureTLS
	//       Fixed on 5 Nov 2001. BY.

	return false;
      }
  }

  // Called after we have been configured by the Configurator
  // to get our base64 encoded root certificate.
  static public String getRootCert()
  throws IOException {
    String rootFile = JTlsUtil.getPCERootPath() + JTlsDefs.CLIENTROOT;

    // load the wrapped object (unwrap it).
    FileReader fr = new FileReader(rootFile);
    BufferedReader br = new BufferedReader(fr);

    // We read a base64 encoded string
    String rc64 = JTlsUtil.loadObject(br,"CERTIFICATE");

    return rc64;
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -