package cn.security.tool;

import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.security.license.core.creator.LicenseCreatorManager;
import cn.security.license.core.creator.LicenseCreatorParam;
import cn.security.license.core.verify.LicenseVerifyManager;
import cn.security.license.core.verify.LicenseVerifyParam;
import cn.util.string.JsonKit;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.util.Base64;

/**
 * TrueLicense`对密码格式有要求，必须包含数字和字母
 * 
 * 除了TrueLicense可控制的常规字段【主题、生效时间、过期时间、consumerType、consumerAmount】以外
 * 扩展了下面控制
 *  可控制机器IP地址，支持IPv4，*代表不控制，可控制ip段 例如：10.5.10.* -> 允许10.5.10.以内任意ip
 *  可控制机器MAC地址，*代表不控制
 *  可控制cpu序列号，*代表不控制
 *  可控制主板序列号，*代表不控制
 * */
public class TrueLicenseTool {

	public static void main(String[] args) throws Exception {
		/*
		//OK生成证书license.lic  TrueLicense  */
		LicenseCreatorParam param = new LicenseCreatorParam();
		//licenseMakeParam.json
		param = setParam();
		LicenseCreatorManager licenseCreator = new LicenseCreatorManager(param);
		boolean result = licenseCreator.generateLicense();
		if(result)
			System.out.println("证书创建成功");
		else
			System.out.println("证书创建失败");
		
		
		LicenseVerifyParam param2 = new LicenseVerifyParam();
		param2 = setParam2();
		LicenseVerifyManager licenseVerify = new LicenseVerifyManager();
		System.out.println("param2:" + param2);
		/**安装验证证书*/
		licenseVerify.install(param2);
		/**校验证书是否有效*/
		boolean verifyResult = licenseVerify.verify();
		if(verifyResult){
			System.out.println("证书OK");
		}else{
			System.out.println("证书无效，请核查服务器是否取得授权或重新申请证书！");
		}

		/** OK 证书文件路径*/
		String cerPath = "D:/data/license/certfile.cer";
		//证书库文件路径  publicCerts.keystore
		String storePath = "D:/data/license/privateKeys.keystore";
		//证书别名
		String alias = "privateKey";
		String storePw = "private_password1234";
		String keyPw = "private_password1234";

		System.out.println("从证书获取的公钥为:" + getPublicKey(cerPath));
		System.out.println("从证书获取的私钥为:" + getPrivateKey(storePath, alias, storePw, keyPw));
		 
	}
	
	
	
	private static LicenseCreatorParam setParam()
	{
		LicenseCreatorParam  param = new LicenseCreatorParam(); 
		String json = "";
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader("D:/data/license/param/licenseMakeParam.json"));
			String str=null;
			while((str=br.readLine())!=null) {
				json = json + str + "\n";
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		param =  (LicenseCreatorParam) JsonKit.json2Bean_jackson(json,LicenseCreatorParam.class);
		
		
		return param;
	}
	private static LicenseVerifyParam setParam2()
	{
		LicenseVerifyParam param = new LicenseVerifyParam();
		String  propertiesPath = "D:/data/license/param/licenseVertifyParam.json";
		String json = "";
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(propertiesPath ));
			String str=null;
			while((str=br.readLine())!=null) {
				json = json + str + "\n";
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		ObjectMapper mapper = new ObjectMapper();
		try {
			param = mapper.readValue(json,LicenseVerifyParam.class );
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return param;
	}
	//X.509公共密钥的证书
	private static String getPublicKey(String cerPath) throws Exception 
	{
		CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");
		FileInputStream fis = new FileInputStream(cerPath);
		X509Certificate Cert = (X509Certificate) certificatefactory.generateCertificate(fis);
		PublicKey pk = Cert.getPublicKey();
		String publicKey = base64Encode(pk.getEncoded());
		return publicKey;
	}

	private static String getPrivateKey(String storePath, String alias, String storePw, String keyPw) throws Exception 
	{
		FileInputStream is = new FileInputStream(storePath);
		//提供特定的 keystore 类型：
		KeyStore ks = KeyStore.getInstance("JKS");
		//使用默认类型：KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
		ks.load(is, storePw.toCharArray());
		is.close();
		PrivateKey key = (PrivateKey) ks.getKey(alias, keyPw.toCharArray());
		String privateKey = base64Encode(key.getEncoded());
		return privateKey;
	}
	static String base64Encode(byte[] bytes) {
		return Base64.getEncoder().encodeToString(bytes);
	}

}
