License大家是如何设计的,and相关资料

V 发布于 2012/03/30 14:45
阅读 1K+
收藏 0
如题
加载中
0
V
V

。。。。。。

没人回,贴下用的上来

package license.crypto;
import java.security.*;    

import javax.crypto.*;    

public class Base64 {    
	private static String strDefaultKey = "national";    

	private Cipher encryptCipher = null;    

	private Cipher decryptCipher = null;    

	/**   
	 * 将byte数组转换为表示16进制值的字符串, 如:byte[]{8,18}转换为:0813, 和public static byte[]   
	 * hexStr2ByteArr(String strIn) 互为可逆的转换过程   
	 *   
	 * @param arrB   
	 * 需要转换的byte数组   
	 * @return 转换后的字符串   
	 * @throws Exception   
	 * 本方法不处理任何异常,所有异常全部抛出   
	 */     
	public static String byteArrToHexStr(byte[] arrB) throws Exception {    
		int iLen = arrB.length;    
//		每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍    
		StringBuffer sb = new StringBuffer(iLen * 2);    
		for (int i = 0; i < iLen; i++) {    
			int intTmp = arrB[i];    
//			把负数转换为正数   
			while (intTmp < 0) {    
				intTmp = intTmp + 256;    
			}    
//			小于0F的数需要在前面补0    
			if (intTmp < 16) {    
				sb.append("0");    
			}    
			sb.append(Integer.toString(intTmp, 16));    
		}    
		return sb.toString();    
	}    

	/**   
	.* 将表示16进制值的字符串转换为byte数组, 和public static String byteArr2HexStr(byte[] arrB)   
		 * 互为可逆的转换过程   
		 *   
		 * @param strIn   
		 * 需要转换的字符串   
		 * @return 转换后的byte数组   
		 * @throws Exception   
		 * 本方法不处理任何异常,所有异常全部抛出   
		 * @author <a href="mailto:leo841001@163.com">LiGuoQing</a>   
		 */    
	public static byte[] hexStrToByteArr(String strIn) throws Exception {    
		byte[] arrB = strIn.getBytes();    
		int iLen = arrB.length;    

//		两个字符表示一个字节,所以字节数组长度是字符串长度除以2    
		byte[] arrOut = new byte[iLen / 2];    
		for (int i = 0; i < iLen; i = i + 2) {    
			String strTmp = new String(arrB, i, 2);    
			arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);    
		}    
		return arrOut;    
	}    

	/**   
	 * 默认构造方法,使用默认密钥   
	 * @throws Exception 
	 *   
	 * @throws Exception   
	 */    
	public Base64(){    
		this(strDefaultKey);    
	}    

	/**   
	 * 指定密钥构造方法   
	 *   
	 * @param strKey   
	 * 指定的密钥   
	 * @throws Exception   
	 */    
	public Base64(String strKey)  {    
		Security.addProvider(new com.sun.crypto.provider.SunJCE());    
		try {
			Key key = getKey(strKey.getBytes());    

			encryptCipher = Cipher.getInstance("DES");    
			encryptCipher.init(Cipher.ENCRYPT_MODE, key);    

			decryptCipher = Cipher.getInstance("DES");    
			decryptCipher.init(Cipher.DECRYPT_MODE, key);
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}    
	}    

	/**   
	 * 加密字节数组   
	 *   
	 * @param arrB   
	 * 需加密的字节数组   
	 * @return 加密后的字节数组   
	 * @throws Exception   
	 */    
	public byte[] encrypt(byte[] arrB) {   
		byte[] encrypt=null;
		try {
			encrypt = encryptCipher.doFinal(arrB);
		} catch (IllegalBlockSizeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BadPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}   
		return encrypt;
	}    

	/**   
	 * 加密字符串   
	 *   
	 * @param strIn   
	 * 需加密的字符串   
	 * @return 加密后的字符串   
	 * @throws Exception   
	 */    
	public String encrypt(String strIn) throws Exception {    
		return byteArrToHexStr(encrypt(strIn.getBytes()));    
	}    

	/**   
	 * 解密字节数组   
	 *   
	 * @param arrB   
	 * 需解密的字节数组   
	 * @return 解密后的字节数组   
	 * @throws Exception   
	 */    
	public byte[] decrypt(byte[] arrB) throws Exception {    
		return decryptCipher.doFinal(arrB);    
	}    

	/**   
	 * 解密字符串   
	 *   
	 * @param strIn   
	 * 需解密的字符串   
	 * @return 解密后的字符串   
	 * @throws Exception   
	 */    
	public String decrypt(String strIn) throws Exception {    
		return new String(decrypt(hexStrToByteArr(strIn)));    
	}    

	/**   
	 * 从指定字符串生成密钥,密钥所需的字节数组长度为8位 不足8位时后面补0,超出8位只取前8位   
	 *   
	 * @param arrBTmp   
	 * 构成该字符串的字节数组   
	 * @return 生成的密钥   
	 * @throws java.lang.Exception   
	 */     
	private Key getKey(byte[] arrBTmp) throws Exception {    
//		创建一个空的8位字节数组(默认值为0)       
		byte[] arrB = new byte[8];    

//		将原始字节数组转换为8位    
		for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {    
			arrB[i] = arrBTmp[i];    
		}    

//		生成密钥    
		Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");    

		return key;    
	}    



}   

package license.license;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.FileHandler;
import license.crypto.Base64;
import license.md5.MD5String;



public class License {
	private static Base64 base64=null;
	private static File file=null;
	private static String split=System.getProperty("file.separator");
	public FileHandler myFileHandler =null; 
	public   String licensePath = "";
	public String logPath = "";
	
	public License(){
		licensePath = "license"+split+"license";
		logPath = "log"+split+"license.log";
		try {
					
			base64=new Base64("sztaiji");
			File logfile = new File(logPath);
			
			file=new File(licensePath);
			File logParentFile=new File(logfile.getParent());
			if(!logParentFile.exists()){
				logParentFile.mkdir();
			}
			if(!logfile.exists()){
				logfile.createNewFile();	
			}
			
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private String createLicense(String uuid,String key,String startTime,String testTime,String endTime,String md5) throws Exception{

		StringBuffer xmlLicense=new StringBuffer();
		xmlLicense.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
		xmlLicense.append("<lincese version=\"5.0\" company=\"key\">\n");
		xmlLicense.append("<uuid id=\"uuid\">"+uuid+"</uuid>\n");
		xmlLicense.append("<key id=\"key\">"+key+"</key>");
		xmlLicense.append("<startTime id=\"startTime\">"+startTime+"</startTime>");
		xmlLicense.append("<testTime id=\"testTime\">"+testTime+"</testTime>");
		xmlLicense.append("<endTime id=\"endTime\">"+endTime+"</endTime>");
		xmlLicense.append("<MD5 id=\"md5\">"+md5+"</MD5>");
		xmlLicense.append("</lincese>");
		return xmlLicense.toString();
	}

	public void writeLicense(String uuid,String key,String startTime,String testTime,String endTime,String md5){
		try {

			if(createMkdir(file.getParent())){
				if(!file.exists()){
					file.createNewFile();
				}
				FileWriter writer=new FileWriter(file);
				writer.write(base64.encrypt(createLicense(uuid,key,startTime,testTime,endTime,md5)));
				writer.close();
			}else{
				FileWriter writer=new FileWriter(file);
				writer.write(base64.encrypt(createLicense(uuid,key,startTime,testTime,endTime,md5)));
				writer.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	public String createMD5(String uuid,String key,String startTime,String testTime,String endTime) throws Exception{
		String line="";
		String md5="";

		line=createLicense(uuid,key,startTime,testTime,endTime,"");
		line=line.substring(0, 250);
		md5=MD5String.get(line,"utf-8");
		return md5;
	}

	public String getMD5() throws Exception{
		String line="";
		String md5="";
		FileReader fileReader=new FileReader(file);
		BufferedReader bufferedReader=new BufferedReader(fileReader);
		while(bufferedReader.ready()){
			line+=bufferedReader.readLine();
		}
		line=base64.decrypt(line);
		line=line.substring(0, 250);
		md5=MD5String.get(line, "utf-8");
		bufferedReader.close();
		return md5;
	}

	private boolean createMkdir(String path){
		boolean result=false;
		File f=new File(path);
		if(!f.exists()){
			if(f.mkdir())
				result=true;
		}
		return result;
	}
}

package license.license;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import license.crypto.Base64;
import license.mac.address.OsMacAddress;

public class ReadLicense {
	private final static ReadLicense readL = new ReadLicense();

	private ReadLicense() {
	}

	public static ReadLicense getReadLicense() {
		return readL;
	}

	private static Logger logger = null;
	private static FileHandler myFileHandler = null;
	private String uuid = "";
	private String key = "";
	private String startTime = "";
	private String testTime = "";
	private String endTime = "";
	private String md5 = "";
	private static License license = null;
	// private static String split=System.getProperty("file.separator");
	private static SimpleFormatter formatter = null;
	/*
	 * License状态 0 无法读取 1 license已损坏 2 license不合法 3 license已超过有效期 4 license验证通过
	 * 5 试用信息
	 */
	private int status;

	public int getStatus() {
		return status;
	}

	public void setStatus(int status) {
		this.status = status;
	}

	private boolean isDemon = true; //是否为测试版
	public boolean isDemon() {
		return isDemon;
	}

	public void setDemon(boolean isDemon) {
		this.isDemon = isDemon;
	}

	private long days; //剩余天数
	public long getDays() {
		return days;
	}

	public void setDays(long days) {
		this.days = days;
	}

	static {
		try {
			license = new License();
			String path = license.logPath;
			logger = Logger.getLogger("license.license");
			myFileHandler = new FileHandler(path);
			formatter = new SimpleFormatter();
			logger.addHandler(myFileHandler);
			myFileHandler.setFormatter(formatter);
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	DateFormat format = new SimpleDateFormat("yyyy-MM-dd",
			Locale.SIMPLIFIED_CHINESE);

	// 重载praseLicense方法,用于界面显示
	private String praseLicense(String license_Msg, ReadLicense instance) {
		Base64 base64 = null;

		String xmlLicense = "";
		String line = "";

		File file = null;
		FileReader fileReader = null;
		BufferedReader bufferedReader = null;
		InputStream input = null;

		DocumentBuilderFactory factory = null;
		DocumentBuilder builder = null;
		Document document = null;
		try {
			base64 = new Base64("key");
			;
			file = new File(license.licensePath);

			fileReader = new FileReader(file);
			bufferedReader = new BufferedReader(fileReader);
			line = bufferedReader.readLine();
			fileReader.close();
			bufferedReader.close();
			factory = DocumentBuilderFactory.newInstance();
			builder = factory.newDocumentBuilder();

			xmlLicense = base64.decrypt(line);
			input = new ByteArrayInputStream(xmlLicense.getBytes());
			document = builder.parse(input);

			uuid = getNodeTextContent("uuid", document);
			key = getNodeTextContent("key", document);
			startTime = getNodeTextContent("startTime", document);
			testTime = getNodeTextContent("testTime", document);
			endTime = getNodeTextContent("endTime", document);
			md5 = getNodeTextContent("MD5", document);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.log(Level.SEVERE,
					"msg"
							+ e);
			instance.setStatus(0);
			return license_Msg = "msg";
		}
		return null;
	}

	private String getTime() {
		String time = "";
		Date date = new Date();
		date.setYear(date.getYear());
		date.setMonth(date.getMonth() + 4);
		date.setDate(date.getDate());
		time = new SimpleDateFormat("yyyy-MM-dd", Locale.SIMPLIFIED_CHINESE)
				.format(date);
		return time;
	}

	// 重载modify方法,用于界面显示
	public String modify(String license_Msg, ReadLicense instance) {
		license_Msg = praseLicense(license_Msg, instance);
		if (license_Msg == null) {
			String mac = OsMacAddress.macAddress();
			try {
				if ( (uuid==null || "".equals(uuid)) && ( key==null || "".equals(key))) {
					UUID uid = UUID.nameUUIDFromBytes(mac.getBytes());
					uuid = uid.toString();
					Date date = new Date();
					startTime = format.format(date);
					//testTime = getTime();
					md5 = license.createMD5(uuid, key, startTime, testTime,
							endTime);
					license.writeLicense(uuid, key, startTime, testTime,
							endTime, md5);
					logger
							.log(Level.INFO,
									"msg");
					license_Msg = "msg";
					instance.setStatus(5);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return license_Msg;
		} else {
			return license_Msg;
		}

	}

	// 重载check方法,用于界面显示
	public String check(String license_Msg, ReadLicense instance) {
		license_Msg = praseLicense(license_Msg, instance);
		if (license_Msg == null) {
			String cMd5 = "";
			String mac = OsMacAddress.macAddress();
			String macUUID = UUID.nameUUIDFromBytes(mac.getBytes()).toString();
			Date newDate = new Date();
			long days = 0L;
			try {
				Date test = format.parse(testTime);
				cMd5 = license.getMD5();
				if (!cMd5.equals(md5)) {
					logger
							.log(Level.INFO,
									"msg");
					license_Msg = "msg";
					instance.setStatus(1);
				} else if (!macUUID.equals(uuid)) {
					logger
							.log(Level.INFO,
									"msg");
					license_Msg = "msg";
					instance.setStatus(2);
				} else {
					if (key == null || "".equals(key)) {
						if (newDate.after(test)) {
							logger
									.log(Level.INFO,
											"msg");
							license_Msg = "msg";
							instance.setStatus(3);
						} else {
							days = getDistDates(newDate, test);
							logger.log(Level.INFO,
									"msg");
							license_Msg = "msg";
							instance.setStatus(4);
							instance.setDays(days);
						}
					} else {
						Date end = format.parse(endTime);
						if (newDate.after(end)) {
							logger
									.log(Level.INFO,
											"msg");
							license_Msg = "msg";
							instance.setStatus(3);
						} else {
							days = getDistDates(newDate, end);
							logger.log(Level.INFO,
									"msg");
							license_Msg = "";
							instance.setStatus(4);
							instance.setDemon(false);
						}
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return license_Msg;
		} else {
			return license_Msg;
		}

	}

	public long getDistDates(Date startDate, Date endDate) {
		long day = 0L;
		Calendar aCalendar = Calendar.getInstance();
		aCalendar.setTime(startDate);
		long timeStart = aCalendar.getTimeInMillis();
		aCalendar.setTime(endDate);
		long timeEnd = aCalendar.getTimeInMillis();
		day = Math.abs(timeEnd - timeStart) / (1000 * 60 * 60 * 24);
		return day;
	}

	private String getNodeTextContent(String tagName, Document document) {
		String tag = "";
		NodeList uList = document.getElementsByTagName(tagName);
		Node uNode = uList.item(0);
		tag = uNode.getTextContent();
		return tag;
	}

	public String getStartTime() {
		return startTime;
	}

	public String getTestTime() {
		return testTime;
	}

	public String getEndTime() {
		return endTime;
	}

	private void praseLicense() {
		Base64 base64 = null;

		String xmlLicense = "";
		String line = "";

		File file = null;
		FileReader fileReader = null;
		BufferedReader bufferedReader = null;
		InputStream input = null;

		DocumentBuilderFactory factory = null;
		DocumentBuilder builder = null;
		Document document = null;
		try {
			base64 = new Base64("sztaiji");
			;
			file = new File(license.licensePath);

			fileReader = new FileReader(file);
			bufferedReader = new BufferedReader(fileReader);
			line = bufferedReader.readLine();
			fileReader.close();
			bufferedReader.close();
			factory = DocumentBuilderFactory.newInstance();
			builder = factory.newDocumentBuilder();

			xmlLicense = base64.decrypt(line);
			input = new ByteArrayInputStream(xmlLicense.getBytes());
			document = builder.parse(input);

			uuid = getNodeTextContent("uuid", document);
			key = getNodeTextContent("key", document);
			startTime = getNodeTextContent("startTime", document);
			testTime = getNodeTextContent("testTime", document);
			endTime = getNodeTextContent("endTime", document);
			md5 = getNodeTextContent("MD5", document);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.log(Level.SEVERE,
					"msg"
							+ e);
			System.exit(1);
		}
	}

	public void modify() {
		praseLicense();
		String mac = OsMacAddress.macAddress();
		try {
			if ((uuid == null || "".equals(uuid))
					&& (key == null || "".equals(key))) {
				UUID uid = UUID.nameUUIDFromBytes(mac.getBytes());
				uuid = uid.toString();
				Date date = new Date();
				startTime = format.format(date);
				testTime = getTime();
				md5 = license
						.createMD5(uuid, key, startTime, testTime, endTime);
				license.writeLicense(uuid, key, startTime, testTime, endTime,
						md5);
				logger
						.log(Level.INFO,
								"msg");
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public boolean check() {
		boolean result = false;
		praseLicense();
		String cMd5 = "";
		String mac = OsMacAddress.macAddress();
		String macUUID = UUID.nameUUIDFromBytes(mac.getBytes()).toString();
		Date newDate = new Date();
		long days = 0L;
		try {
			Date test = format.parse(testTime);

			cMd5 = license.getMD5();
			if (!cMd5.equals(md5)) {
				logger
						.log(Level.INFO,
								"msg");
				result = false;
			} else if (!macUUID.equals(uuid)) {
				logger
						.log(Level.INFO,
								"msg");
				result = false;
			} else {
				if (key == null || "".equals(key)) {
					if (newDate.after(test)) {
						logger
								.log(Level.INFO,
										"msg");
						result = false;
					} else {
						days = getDistDates(newDate, test);
						logger.log(Level.INFO,
								"msg");
						result = true;
					}
				} else {
					Date end = format.parse(endTime);
					if (newDate.after(end)) {
						logger
								.log(Level.INFO,
										"msg");
						result = false;
					} else {
						days = getDistDates(newDate, end);
						logger.log(Level.INFO,
								"msg");
						result = true;
					}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

}

package license.mac.address;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class OsMacAddress {


	private static  String getWindowsMAC(String ip) {
		String mac = null;
		Pattern macPattern = Pattern
		.compile("([0-9A-Fa-f]{2})(-[0-9A-Fa-f]{2}){5}");
		Matcher macMatcher;
		try {
			Process p = Runtime.getRuntime().exec("ipconfig /all");

			BufferedReader br = new BufferedReader(new InputStreamReader(p
					.getInputStream()));
			String content = null;
			boolean result= false;

			while ((content = br.readLine()) != null) {
				macMatcher = macPattern.matcher(content);

				macMatcher = macPattern.matcher(content);
				result = macMatcher.find();
				if (result){
					mac= macMatcher.group(0);
					break;
				}

			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		return mac;
	}
	private static String unixMacAddress(){
		String mac=null;
		BufferedReader bufferedReader=null;
		Process process=null;
		try {
			process=Runtime.getRuntime().exec("/sbin/ifconfig -a");
			bufferedReader=new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line=null;
			int index=-1;
			while((line=bufferedReader.readLine())!=null){
				index=line.toLowerCase().indexOf("hwaddr");
				if(index>=0){
					mac=line.substring(index+"hwaddr".length()+1).trim();
					break;
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				if(bufferedReader!=null){
					bufferedReader.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			bufferedReader=null;
			process=null;
		}
		return mac;

	}
	private static String osName(){
		String osName=System.getProperty("os.name");
		return osName.toLowerCase();
	}
	public static String macAddress(){
		String mac=null;
		try {
			if(osName().startsWith("windows")){
				InetAddress addre=InetAddress.getLocalHost();
				mac=OsMacAddress.getWindowsMAC(addre.getHostAddress() );
			}else {
				mac=OsMacAddress.unixMacAddress();
			}
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return mac.trim();
	}

}

还有MD5的就不贴了

 

 

 

0
苦逼程序员
苦逼程序员
大哥,能不能把你的程序发一份给我啊?我什么都不懂license新手从来没有用过,现在开始学。你应该也有一些文档的吧!呵呵,顺便一起打个包借我参详参详好吗?感谢。。十分感谢,万分感谢。。
0
苦逼程序员
苦逼程序员
忘了贴我的邮箱了,不好意思,呵呵  593342680@qq.com
V
V
都贴上面了啊,自己组装下就OK了啊
返回顶部
顶部