package com.nms.server.thread.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import org.apache.log4j.Logger;

import com.nms.server.common.Constants;
import com.nms.server.util.DateUtil;
import com.nms.server.util.ExceptionPrintUtils;

public class SSLCertOper {
	private static final String STORE_PASS = "client";
	private static final Integer VALIDITY = Constants.SSL_KEY_VALIDITY;
	private static Logger logger = Logger.getLogger(SSLCertOper.class);
	/**
	 * 创建 密匙对（私钥和公钥）
	 * @time Aug 28, 2011-7:07:02 PM
	 * @param aliasName
	 * @param storePath
	 * @param localIp
	 * @param keyPass
	 * @param certName
	 * @return
	 */
	public static String createKeyAndCert(String aliasName,
			String storePath, String localIp, String keyPass, String certName) {
		BufferedReader bReader = null;
		try {
			Process process = Runtime
					.getRuntime()
					.exec(
							"keytool -genkey -v -alias "
									+ aliasName
									+ " -keyalg RSA -storetype jceks -keystore "
									+ storePath
									+ " -validity "+VALIDITY+" -dname \"CN="
									+ localIp
									+ ",OU=cn,O=cn,L=cn,ST=cn,C=cn\" -storepass "+STORE_PASS+" -keypass "
									+ keyPass);
			process.getOutputStream().close();
			bReader = new BufferedReader(new InputStreamReader(
					process.getInputStream()));
			String line = null;
			while ((line = bReader.readLine()) != null) {
				System.out.println(line);
			}
			
			process = Runtime.getRuntime().exec(
					"keytool -export -alias " + aliasName
							+ " -storetype jceks -keystore " + storePath
							+ " -file " + certName + " -storepass "+STORE_PASS+"");
			
			bReader = new BufferedReader(new InputStreamReader(
					process.getInputStream()));
			while ((line = bReader.readLine()) != null) {
				System.out.println(line);
			}

			return certName;
		} catch (IOException e) {
			logger.error(ExceptionPrintUtils.printExceptionStack(e));
			return null;
		} finally {
			if(bReader!=null){
				try {
					bReader.close();
				} catch (IOException e) {
					logger.error(ExceptionPrintUtils.printExceptionStack(e));
				}
			}
		}

	}

	/**
	 * 将公钥引入KeyStore
	 * @time Aug 28, 2011-7:07:17 PM
	 * @param aliasName
	 * @param storePath
	 * @param certName
	 * @return
	 */
	public static boolean importCertToStore(String aliasName, String storePath,
			String certName) {
		BufferedReader bReader = null;
		PrintWriter pw = null;
		try {
			Process process = Runtime.getRuntime().exec(
					"keytool -import -v -trustcacerts -alias "
							+ aliasName + " -keystore " + storePath + " -file "
							+ certName + " -storetype jceks -storepass "+STORE_PASS+"");
			
			bReader = new BufferedReader(new InputStreamReader(
					process.getInputStream()));
			pw = new PrintWriter(process.getOutputStream());
			
			pw.write("y");
			pw.flush();
			pw.close();
			
			String line = null;
			while ((line = bReader.readLine()) != null) {
				System.out.println(line);
			}

			return true;
		} catch (IOException e) {
			logger.error(ExceptionPrintUtils.printExceptionStack(e));
			return false;
		}finally {
			if(pw!=null){
				pw.close();
			}
			if(bReader!=null){
				try {
					bReader.close();
				} catch (IOException e) {
					logger.error(ExceptionPrintUtils.printExceptionStack(e));
				}
			}
		}

	}
	/**
	 * 将公钥引入KeyStore
	 * @time Aug 28, 2011-7:07:17 PM
	 * @param aliasName
	 * @param storePath
	 * @param certName
	 * @return
	 */
	public static boolean deleteKeyOrCertFromStore(String aliasName, String storePath) {
		BufferedReader bReader = null;
		PrintWriter pw = null;
		try {
			Process process = Runtime.getRuntime().exec(
					"keytool -delete -v -alias "
							+ aliasName + " -keystore " + storePath + " -storetype jceks -storepass "+STORE_PASS+"");
			
			bReader = new BufferedReader(new InputStreamReader(
					process.getInputStream()));
			pw = new PrintWriter(process.getOutputStream());
			
//			pw.write("y");
			pw.flush();
			pw.close();
			
			String line = null;
			while ((line = bReader.readLine()) != null) {
				System.out.println(line);
			}

			return true;
		} catch (IOException e) {
			logger.error(ExceptionPrintUtils.printExceptionStack(e));
			return false;
		}finally {
			if(pw!=null){
				pw.close();
			}
			if(bReader!=null){
				try {
					bReader.close();
				} catch (IOException e) {
					logger.error(ExceptionPrintUtils.printExceptionStack(e));
				}
			}
		}

	}
	/**
	 * test main
	 * @time Aug 28, 2011-12:17:28 PM
	 * @param args
	 */
	public static void main(String args[]) {
		String newServerKeyName = "serverks"+DateUtil.getCurrentDate(DateUtil.YYYYMMDD);
		String newServerKeyPsw = "123456";
		String newClientkeyName = "clientks"+DateUtil.getCurrentDate(DateUtil.YYYYMMDD);
		String newClientkeyPsw = "123456";
		String filepath0 = SSLCertOper.createKeyAndCert(
				newServerKeyName ,
				"D:\\workspace\\nms_server\\cer\\server_ks",
				"10.0.6.113", newServerKeyPsw,
				"D:\\workspace\\nms_server\\cer\\server.cer");
		
		SSLCertOper.importCertToStore(
				newServerKeyName,
				"D:\\workspace\\nms_server\\cer\\client_ts",
				"D:\\workspace\\nms_server\\cer\\server.cer");
		
		String filepath1 = SSLCertOper.createKeyAndCert(
				newClientkeyName,
				"D:\\workspace\\nms_server\\cer\\client_ks",
				"localhost", newClientkeyPsw,
				"D:\\workspace\\nms_server\\cer\\client.cer");
		
		SSLCertOper.importCertToStore(
				newClientkeyName,
				"D:\\workspace\\nms_server\\cer\\server_ts",
				"D:\\workspace\\nms_server\\cer\\client.cer");
		System.out.println(filepath0);
		System.out.println(filepath1);
//		Config.setValueByName("ssl.server.key.old", Constants.SSL_SERVER_KEY_NEW);
//		Config.setValueByName("ssl.server.key.old.psw", Constants.SSL_SERVER_KEY_NEW_PSW);
//		Config.setValueByName("ssl.server.key.new",newServerKeyName);
//		Config.setValueByName("ssl.server.key.new.psw", newServerKeyPsw);
//		Config.setValueByName("ssl.client.key",newClientkeyName);
//		Config.setValueByName("ssl.client.key.psw", newClientkeyPsw);
	}
}
