license生成

阅读更多
package com.dameng.dmdp.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class License {
private static final String licensePath = "license.dat";
private static final String keyFilename = "key.data";
private static SimpleDateFormat sdf  = new SimpleDateFormat( "yyyy-MM-dd");   //yyyy-MM-dd HH:mm:ss
//Product.title , AppServer
private String title = "AppServer";
//Product.sku, J2EE/CORBA
private String sku  = "J2EE/CORBA";
//Serial.number, MAC Address
private byte[] serialNumber;
//Platform, all
private String platform  = "";
//Trial.license
private boolean isTrial;
//License.expiry, 2010-05-12
private String expiry = "";
//Test
public static void main(String[] args) throws Exception{


//
InetAddress ia = InetAddress.getLocalHost();
System.out.println(ia);
String mac =getLocalMac(ia);

//为用户生成license,并email给他
License om = new License();
om.setTitle("AppServer");
om.setSku("J2EE/CORBA");
//String mac = getMACAddress();
om.setPlatform("Windows");
om.setTrial(false);
om.setExpiry("2010-05-12");
License.generateLicense(om,mac);
//在程序中校验license
License.validate();
}
//为用户生成license, 也就是将serialNumber字段的MAC加密
public static License generateLicense(License om,String mac){
    try{
    //密匙不存在,则生成密匙
            if(! new File(keyFilename).exists()){
            generateKey();   
}
    //用密匙加密数据
    byte rawKeyData[] = readFile(keyFilename);        //用某种方法获得密匙数据
    DESKeySpec dks = new DESKeySpec( rawKeyData );    //从原始密匙数据创建DESKeySpec对象
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); //创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象
    SecretKey key = keyFactory.generateSecret( dks );
    Cipher cipher = Cipher.getInstance( "DES" );      //Cipher对象实际完成加密操作
    SecureRandom sr = new SecureRandom();             //DES算法要求有一个可信任的随机数源
    cipher.init(Cipher.ENCRYPT_MODE, key, sr );       //用密匙初始化Cipher对象
    System.out.println("mac-----"+mac);
    byte data[] = mac.getBytes();    //用某种方法获取数据
    byte encryptedData[] = cipher.doFinal( data );    //正式执行加密操作
    System.out.println("加密后的数据:" + encryptedData);
    om.setSerialNumber(encryptedData);
    //输出license
    write(om);
    }catch(Exception e){
    e.printStackTrace();
    }
return om;
}
//生成密匙
private static boolean generateKey(){
boolean result = false;
String algorithm = "DES";
try{
    SecureRandom sr = new SecureRandom();              //DES算法要求有一个可信任的随机数源
    KeyGenerator kg = KeyGenerator.getInstance(algorithm);
    kg.init( sr );
    SecretKey key = kg.generateKey();                  //[-68, -68, -57, -71, 42, -125, 32, 13]
    result = writeFile(keyFilename, key.getEncoded()); //把密匙数据保存到文件
}catch(Exception e){
e.printStackTrace();
}
return result;
}
public static boolean validate(){
boolean result = false;
try{
License om = read();
String os = System.getProperty("os.name");
if (os.toLowerCase().startsWith(om.getPlatform().toLowerCase()) || "all".equals(om.getPlatform())) {
Date expireDate = sdf.parse(om.getExpiry());
if(expireDate.getTime() - new Date().getTime() < 0){
System.err.println("License过期了");
result = false;
}else{
if(om.isTrial()){
System.out.println("试用License有效");
result = true;
}else{
String mac = getMACAddress();
//用密匙解密数据
    byte rawKeyData[] = readFile(keyFilename);        //用某种方法获得密匙数据
    DESKeySpec dks = new DESKeySpec( rawKeyData );    //从原始密匙数据创建DESKeySpec对象
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); //创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象
    SecretKey key = keyFactory.generateSecret( dks );
    Cipher cipher = Cipher.getInstance( "DES" );      //Cipher对象实际完成加密操作
    SecureRandom sr = new SecureRandom();             //DES算法要求有一个可信任的随机数源
    cipher.init(Cipher.DECRYPT_MODE, key, sr );       //用密匙初始化Cipher对象
    byte data[] = om.getSerialNumber();               //用某种方法获取数据
    byte encryptedData[] = cipher.doFinal(data);      //正式执行加密操作
    String tmp = new String(encryptedData);
    System.out.println("解密后的数据:" + tmp);
    if(mac.equals(tmp)){
    System.out.println("License有效");
    result = true;
    }else{
    System.err.println("License无效");
    result = false;
    }
}
}
}else{
System.err.println("License的平台无效");
    result = false;
}
}catch(Exception e){
e.printStackTrace();
}
return result;
}
public static License read(){
License om = null;
try{
om = new License();
ObjectInputStream in = new ObjectInputStream(new FileInputStream(licensePath));
om.setTitle((String)in.readObject());
om.setSku((String)in.readObject());
om.setPlatform((String)in.readObject());
om.setTrial(in.readBoolean());
om.setExpiry((String)in.readObject());
om.setSerialNumber((byte[])in.readObject());
in.close();
}catch(Exception e){
e.printStackTrace();
}
return om;
}
public static boolean write(License om){
boolean result;
try{
File f = new File(licensePath);
if(f.exists())
f.delete();
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f));
out.writeObject(om.getTitle());
out.writeObject(om.getSku());
out.writeObject(om.getPlatform());
out.writeBoolean(om.isTrial());
out.writeObject(om.getExpiry());
out.writeObject(om.getSerialNumber());
out.close();
            result = true;
}catch(Exception e){
e.printStackTrace();
result = false;
}
return result;
}
public static boolean writeFile(String path, byte[] bytes){
boolean result = false;
try {
FileOutputStream   fos = new FileOutputStream(path);
fos.write(bytes);
fos.close();
result = true;
} catch (Exception e) {
e.printStackTrace();
}  
return result;
}
public static byte[] readFile(String path){
byte[] bytes = null;
try {
FileInputStream   fin = new FileInputStream(path);
bytes = new byte[fin.available()];
fin.read(bytes);
fin.close();
} catch (Exception e) {
e.printStackTrace();
}  
return bytes;
}
  public static String getMACAddress() {
String address = "";
String os = System.getProperty("os.name");
if (os.startsWith("Windows")) {
try {
String command = "ipconfig /all";
Process p = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream(),"GB2312"));
String line;
while ((line = br.readLine()) != null) {
if (line.toLowerCase().indexOf("physical address") > 0) {
int index = line.indexOf(":");
index += 2;
address = line.substring(index);
break;
}
}
br.close();
return address.trim();
} catch (IOException e) {
e.printStackTrace();
}
} else if (os.startsWith("Linux")) {
String command = "/bin/sh -c ifconfig -a";
Process p;
try {
p = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
if (line.indexOf("HWaddr") > 0) {
int index = line.indexOf("HWaddr") + "HWaddr".length();
address = line.substring(index);
break;
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
address = address.trim();
return address;
}
  private static String getLocalMac(InetAddress ia) throws SocketException {
// TODO Auto-generated method stub
//获取网卡,获取地址
byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
System.out.println("mac数组长度:"+mac.length);
StringBuffer sb = new StringBuffer("");
for(int i=0; i if(i!=0) {
sb.append("-");
}
//字节转换为整数
int temp = mac[i]&0xff;
String str = Integer.toHexString(temp);
System.out.println("每8位:"+str);
if(str.length()==1) {
sb.append("0"+str);
}else {
sb.append(str);
}
}
System.out.println("本机MAC地址:"+sb.toString().toUpperCase());
return sb.toString().toUpperCase();
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public byte[] getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(byte[] serialNumber) {
this.serialNumber = serialNumber;
}
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
public boolean isTrial() {
return isTrial;
}
public void setTrial(boolean isTrial) {
this.isTrial = isTrial;
}
public String getExpiry() {
return expiry;
}
public void setExpiry(String expiry) {
this.expiry = expiry;
}
}

你可能感兴趣的:(license生成)