license
package com.comName.dhm.common.license.tool;
import java.io.IOException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
/**
* 生成一对密钥,即私钥和公钥
*
*/
public class GenerateKeyPair
{
/**
* 密鈅对生成处理
*/
public void run()
{
try
{
KeyPairGenerator keygen = KeyPairGenerator.getInstance(LicenseToolUtil.KEY_ALGORITHM);
SecureRandom random = new SecureRandom();
keygen.initialize(LicenseToolUtil.KEY_SIZE, random);
KeyPair keyPair = keygen.genKeyPair();
// 得到钥匙对
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// 写公钥文件
LicenseToolUtil.writeFile(LicenseToolUtil.PUBLIC_KEY_FILE, publicKey.getEncoded());
// 写密钥文件
LicenseToolUtil.writeFile(LicenseToolUtil.PRIVATE_KEY_FILE, privateKey.getEncoded());
// 完成
System.out.println("生成密钥对成功,公钥路径【" + LicenseToolUtil.PUBLIC_KEY_FILE + "】,私钥路径【 "
+ LicenseToolUtil.PRIVATE_KEY_FILE + "】");
}
catch (NoSuchAlgorithmException e)
{
// error异常处理
System.err.println("生成密钥对失败:" + e.getMessage());
}
catch (IOException e)
{
// error异常处理
System.err.println("生成密钥对失败:" + e.getMessage());
}
}
/**
* 执行入口
*
* @param args
*/
public static void main(String[] args)
{
System.out.println("密钥对生成开始。");
// 执行
new GenerateKeyPair().run();
System.out.println("密钥对生成结束。");
}
}
package com.comName.dhm.common.license.tool;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
/**
* License工具的操作公用类
*
*/
public class LicenseToolUtil
{
/**
* key的size
*/
public final static int KEY_SIZE = 1024;
/**
* 加密算法
*/
public final static String KEY_ALGORITHM = "RSA";
/**
* 签名算法
*/
public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
/**
* 公钥文件
*/
public final static String PUBLIC_KEY_FILE = "conf/publickey.txt";
/**
* 私钥文件
*/
public final static String PRIVATE_KEY_FILE = "conf/privatekey.txt";
/**
* signature对象的名字
*/
public static final String SIGNATURE_NAME = "signature";
/**
* 读取文件内容,保存为byte数组
*
* @param filePath
* 文件路径
* @return 文件内容数据
* @throws IOException
*/
public static byte[] readFile(String filePath) throws IOException
{
// 文件名是否为空
if (filePath == null)
{
System.out.println("文件名为空,不能读取数据。");
return null;
}
// 构建File对象
File file = new File(filePath);
if (file.exists() && file.isFile())
{
long fileLength = file.length();
if (fileLength > 0L)
{
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file));
byte[] b = new byte[(int) fileLength];
while (fis.read(b) != -1)
{
}
fis.close();
fis = null;
return b;
}
}
else
{
return null;
}
return null;
}
/**
* 将byte数据写入写文件
*
* @param filePath
* 文件路径
* @param content
* byte数据
* @throws IOException
*/
public static void writeFile(String filePath, byte[] content) throws IOException
{
BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(filePath));
fos.write(content);
fos.flush();
fos.close();
}
/**
* 将字节数组转化为十六进制
*
* @param theData
* 字节数组
* @return 十六进制数据
*/
public static String bytesToHexString(byte[] theData)
{
StringBuffer hexStrBuff = new StringBuffer(theData.length * 2);
for (int i = 0; i < theData.length; i++)
{
String hexByteStr = Integer.toHexString(theData[i] & 0xff).toUpperCase();
if (hexByteStr.length() == 1)
{
hexStrBuff.append("0");
}
hexStrBuff.append(hexByteStr);
}
return hexStrBuff.toString();
}
/**
* 将十六进制转化为字节数组
*
* @param theHexString
* 十六进制数据
* @return 字节数组
*/
public static byte[] hexStringToBytes(String theHexString)
{
byte data[] = new byte[theHexString.length() / 2];
for (int i = 0; i < data.length; i++)
{
String a = theHexString.substring(i * 2, i * 2 + 2);
data[i] = (byte) Integer.parseInt(a, 16);
}
return data;
}
/**
* 取得文件对象的Dom对象
*
* @return 文件对象的Dom对象
*/
public static Element getFileRootDocument(File xmlFile)
{
if (xmlFile == null || !xmlFile.exists())
{
return null;
}
try
{
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(xmlFile);
return doc.getRootElement();
}
catch (JDOMException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
/**
* 取得签名信息
*
* @param rootElement
* license的Element对象
* @return 签名信息
*/
public static String getSignatureSource(Element rootElement)
{
if (rootElement == null)
{
// 没有要签名的对象
System.err.println("没有要签名的对象");
return null;
}
// 要签名的信息
StringBuffer sb = new StringBuffer();
fetchElementLeafValue(rootElement, sb);
return sb.toString();
}
/**
* 递归取得license文件的内容
*
* @param element
* 当前Element对象
* @param sb
* buffer
* @return 签名信息
*/
private static void fetchElementLeafValue(Element element, StringBuffer sb)
{
if (element == null)
{
return;
}
List<?> list = element.getChildren();
// signature对象不作为签名对象
if (list.size() == 0 && !SIGNATURE_NAME.equalsIgnoreCase(element.getName()))
{
sb.append("&").append(element.getText());
}
// 递归调用
for (Iterator<?> iterator = list.iterator(); iterator.hasNext();)
{
Element ele = (Element) iterator.next();
fetchElementLeafValue(ele, sb);
}
}
/**
* 读取文件的第一行数据
*
* @param file
* 数据文件
* @return 第一行数据
*/
public static String readContentFromFile(File file) throws IOException
{
if (file == null || !file.exists() || !file.isFile())
{
System.err.println("文件不存在!");
return null;
}
StringBuffer tmpStr = new StringBuffer();
InputStreamReader isr = new InputStreamReader(new FileInputStream(file));
char[] bf = new char[1024];
int i = -1;
while ((i = isr.read(bf)) != -1)
{
tmpStr.append(bf, 0, i);
}
isr.close();
return tmpStr.toString();
}
/**
* 写License文件
*
* @param licenseFileName
* license文件的名字
* @param rootElement
* RootDocument对象
* @param signature
* signature的值
* @return 写文件是否成功
*/
public static boolean writeLicenseXML(String licenseFileName, Element rootElement, String signature)
{
if (licenseFileName == null)
{
// error 文件名不能为空
System.err.println("文件名不能为空");
return false;
}
if (rootElement == null)
{
// error license内容对象不能为空
System.err.println("license内容对象不能为空");
return false;
}
try
{
// 写signature节点的值
Element element = getElementByName(rootElement, SIGNATURE_NAME);
if (element != null)
{
element.setText(signature);
}
Format format = Format.getCompactFormat();
format.setEncoding("utf-8");
format.setIndent(" ");
XMLOutputter XMLOut = new XMLOutputter(format);
XMLOut.output((Document) rootElement.getParent(), new FileOutputStream(licenseFileName));
return true;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return false;
}
/**
* 取得指定的element
*
* @param rootElement
* RootDocument对象
* @param name
* 节点名字
* @return 指定的element
*/
public static Element getElementByName(Element rootElement, String name)
{
List<Element> target = getElementsByName(rootElement, name);
if (target != null && target.size() > 0)
{
return target.get(0);
}
return null;
}
/**
* 取得指定的element一览
*
* @param rootElement
* RootDocument对象
* @param name
* 节点名字
* @return 指定的element一览
*/
public static List<Element> getElementsByName(Element rootElement, String name)
{
if (name == null)
{
// error 节点名字不能为空
System.err.println("节点名字不能为空");
return null;
}
if (rootElement == null)
{
// error license内容对象不能为空
System.err.println("license内容对象不能为空");
return null;
}
List<Element> target = new ArrayList<Element>();
searchElementByName(target, rootElement, name);
return target;
}
/**
* 递归取得指定的element一览
*
* @param target
* element一览
* @param rootElement
* RootDocument对象
* @param name
* 节点名字
* @return 指定的element一览
*/
private static List<Element> searchElementByName(List<Element> target, Element element, String name)
{
List<?> eleList = element.getChildren();
if (name.equalsIgnoreCase(element.getName()))
{
target.add(element);
}
if (eleList.size() == 0)
{
return target;
}
else
{
for (Iterator<?> iterator = eleList.iterator(); iterator.hasNext();)
{
Element element2 = (Element) iterator.next();
searchElementByName(target, element2, name);
}
}
return target;
}
}
读取初始化license文件,生成签名license文件的处理
package com.comName.dhm.common.license.tool;
import java.io.File;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import org.jdom.Element;
/**
* 读取初始化license文件,生成签名license文件的处理
*
*/
public class GenerateLicense
{
/**
* 初始化license文件
*/
private static String orgLicenseFile = "license.xml";
/**
* 签名license文件
*/
private static String licenseFile = "conf/license.xml";
/**
* license生成处理
*/
public void run()
{
try
{
// 取得初始化license文件的Element对象
Element rootElement = LicenseToolUtil.getFileRootDocument(new File(orgLicenseFile));
// 签名信息
String myinfo = LicenseToolUtil.getSignatureSource(rootElement);
if (myinfo == null)
{
// 异常处理
System.err.println("初始化license不存在,生成签名license文件生成密钥对失败。");
return;
}
// 取得私钥
byte[] privateKey = LicenseToolUtil.readFile(LicenseToolUtil.PRIVATE_KEY_FILE);
if (privateKey == null || privateKey.length == 0)
{
System.err.println("私钥取得失败,生成签名license文件生成密钥对失败。");
return;
}
// 取得加密的key
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(privateKey);
KeyFactory keyf = KeyFactory.getInstance(LicenseToolUtil.KEY_ALGORITHM);
PrivateKey myprikey = keyf.generatePrivate(priPKCS8);
// 用私钥对信息生成数字签名
Signature signet = Signature.getInstance(LicenseToolUtil.SIGNATURE_ALGORITHM);
signet.initSign(myprikey);
signet.update(myinfo.getBytes());
byte[] signed = signet.sign(); // 对信息的数字签名
// 签名信息加密
String sigStr = LicenseToolUtil.bytesToHexString(signed);
if (LicenseToolUtil.writeLicenseXML(licenseFile, rootElement, sigStr))
{
System.out.println("签名并生成文件成功,license文件的地址【" + licenseFile + "】");
}
else
{
System.out.println("签名失败");
}
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
// 异常处理
System.out.println("生成密钥对失败");
}
catch (IOException e)
{
e.printStackTrace();
// 异常处理
System.out.println("生成密钥对失败");
}
catch (InvalidKeySpecException e)
{
e.printStackTrace();
// 异常处理
System.out.println("生成密钥对失败");
}
catch (InvalidKeyException e)
{
e.printStackTrace();
// 异常处理
System.out.println("生成密钥对失败");
}
catch (SignatureException e)
{
e.printStackTrace();
// 异常处理
System.out.println("生成密钥对失败");
}
}
/**
* 执行入口
*
* @param args
*/
public static void main(String[] args)
{
System.out.println("License文件生成开始。");
// 是否传递路径
if (args.length == 2)
{
orgLicenseFile = args[0];
licenseFile = args[1];
}
else
{
System.out.println("没有指定初始化license文件与生成后license文件的路径,license文件将生成到默认路径。");
}
// 生成license文件
new GenerateLicense().run();
System.out.println("License文件生成结束。");
}
}
orgLicenseFile = "license.xml";
<?xml version="1.0" encoding="utf-8"?>
<comName-license>
<systemInfo>
<name>SDP.SME.CD</name>
<version>V300R002</version>
<serial>61635-6786786-1334569-22342</serial>
<ip>any</ip>
<mac>any</mac>
<expiration>2012-12-1 12:00:00</expiration>
<controlLevel>1</controlLevel>
</systemInfo>
<controlItems>
<controlItem>
<name>system_user_number</name>
<value>10000000</value>
</controlItem>
<controlItem>
<name>product_offering_number</name>
<value>10000000</value>
</controlItem>
</controlItems>
<signature>260BD1C81C5A661E71EFE7CE508703B91DA481DDF35631BCAF6BEDFAAF52E53D1BC83B8461BD0F515C4EDCC23C37C58FEEAA2E0DA15BFC4BFEAFCFA371606F1450408E8F8AF7850AC4B799DCE2C7E5E54A3A1F2808A897958F50023C114BAC6C1ACF537D3782810BB23DD2CE6E16BBC275B3CA43AF882E792F1DA9E8A922D4A4</signature>
</comName-license>
licenseFile = "conf/license.xml";
<?xml version="1.0" encoding="utf-8"?>
<comName-license>
<systemInfo>
<name>DHM.iEPG</name>
<version>V200R002</version>
<serial>61635-6786786-1334569-22342</serial>
<ip>any</ip>
<mac>any</mac>
<expiration>2011-12-1 12:00:00</expiration>
<controlLevel>1</controlLevel>
</systemInfo>
<controlItems>
<controlItem>
<name>system_user_number</name>
<value>1000</value>
</controlItem>
<controlItem>
<name>product_offering_number</name>
<value>100</value>
</controlItem>
</controlItems>
<signature>3772A5EDB2E31E82368BA6D199D8C2FFD55AD56CCA670C31EA0DFABD0C0C892C4A4E035757254A35D33850ECE0ABB39F30FBDEB4C966FC1E87EB07981C694F25A929CC27CE6A6FA4EDDE4B70E341BBD9DDF219FD86D9B5205535F963272012792C7D0ED0B35312DFBC2F72F19A1796DF69F2C3FC8895348E82179F83B82EEE6D</signature>
</comName-license>
package com.comName.dhm.common.license;
import java.util.Map;
import org.apache.log4j.Logger;
import com.comName.dhm.common.license.vo.License;
import com.comName.dhm.common.license.vo.LicenseInfo;
import com.comName.dhm.common.license.vo.SystemInfo;
/**
* License组件接口
*
*/
public class ControlItemCheck
{
/**
* 日志对象
*/
private static Logger logger = Logger.getLogger(ControlItemCheck.class);
/**
* 控制项检验<br />
* <ol>
* <li>控制项不存在时,FALSE
* <li>控制项超过控制上限值且控制级别为高,FALSE
* <li>控制项超过控制上限值但控制级别为低,TRUE
* <li>控制项没有超过控制上限值,TRUE
* </ol>
*
* @param controlName
* 控制项目名
* @param controlValue
* 控制项目值
* @return 是否合法
*/
public static boolean checkItem(String controlName, int controlValue)
{
if (logger.isDebugEnabled())
{
logger.info("控制项检查开始。");
logger.debug("控制项:【controlName:" + controlName + "】【controlValue:" + controlValue + "】");
}
// 获取license对象
License license = LicenseInfo.getLicense();
// 加载license失败或license不存在
if (license == null || controlName == null)
{
logger.error("验证异常,license对象不存在或license信息加载失败。");
return false;
}
// 系统信息取得
SystemInfo sysinfo = license.getSystemInfo();
if (sysinfo == null)
{
// 系统信息为空
logger.error("验证异常,license对象的系统信息不存在。");
return false;
}
// 控制级别验证
Map<String, String> controlItems = license.getControlItems();
String testValue = controlItems.get(controlName);
// 控制项是否存在
if (testValue == null)
{
// 没有取得控制项
logger.error("验证异常,控制项不存在。");
return false;
}
// 超过控制值
if (controlValue > Integer.parseInt(testValue))
{
// 控制级别
// 级别高
if (sysinfo != null && "1".equals(sysinfo.getControlLevel()))
{
// 超过控制值
if (logger.isInfoEnabled())
{
logger.info("验证不通过,超过控制值,且级别为高。");
}
return false;
}
// 超过控制值,但级别为低
if (logger.isInfoEnabled())
{
logger.info("超过控制值,但级别为低");
}
}
// 验证成功
if (logger.isDebugEnabled())
{
logger.debug("验证通过。");
}
return true;
}
/**
* 根据控制项名字取得控制项值<br />
*
* @param controlName
* 控制项目名
* @return 控制项目值
*/
public static int getControlValue(String controlName)
{
// log开始
if (logger.isInfoEnabled())
{
logger.info("控制项值取得处理开始。");
}
if (logger.isDebugEnabled())
{
logger.debug("控制项:【controlName:" + controlName + "】");
}
int controlValue = Integer.MIN_VALUE;
// 获取license对象
License license = LicenseInfo.getLicense();
// 加载license失败或license不存在
if (license == null || controlName == null)
{
logger.error("验证异常,license对象不存在或license信息加载失败。");
return controlValue;
}
// 控制项值取得
Map<String, String> controlItems = license.getControlItems();
String testValue = controlItems.get(controlName);
// 控制项是否存在
if (testValue == null)
{
// 没有取得控制项
logger.error("验证异常,控制项不存在。");
controlValue = Integer.MIN_VALUE;
}
try
{
controlValue = Integer.parseInt(testValue);
}
catch (NumberFormatException e)
{
logger.error("控制项值不正确。", e);
controlValue = Integer.MIN_VALUE;
}
return controlValue;
}
}
package com.comName.dhm.common.license.vo;
/**
* 保存License信息
*
*/
public class LicenseInfo
{
/**
* License信息
*/
private static License license;
/**
* 取得license
*
* @return license的值
*/
public static License getLicense()
{
return license;
}
/**
* 设置license
*
* @param 设置的license
*/
public static void setLicense(License license)
{
LicenseInfo.license = license;
}
}
package com.comName.dhm.common.license.vo;
import java.util.Map;
/**
* License实体(tag名:coship-license)
*
*/
public class License
{
/**
* 系统信息(tag名:systemInfo)
*/
private SystemInfo systemInfo;
/**
* 控制项列表(tag名:controlItems)
*/
private Map<String, String> controlItems;
/**
* 证书(tag名:signature)
*/
private String signature;
/**
* 取得systemInfo
*
* @return systemInfo的值
*/
public SystemInfo getSystemInfo()
{
return systemInfo;
}
/**
* 设置systemInfo
*
* @param 设置的systemInfo
*/
public void setSystemInfo(SystemInfo systemInfo)
{
this.systemInfo = systemInfo;
}
/**
* 取得controlItems
*
* @return controlItems的值
*/
public Map<String, String> getControlItems()
{
return controlItems;
}
/**
* 设置controlItems
*
* @param 设置的controlItems
*/
public void setControlItems(Map<String, String> controlItems)
{
this.controlItems = controlItems;
}
/**
* 取得signature
*
* @return signature的值
*/
public String getSignature()
{
return signature;
}
/**
* 设置signature
*
* @param 设置的signature
*/
public void setSignature(String signature)
{
this.signature = signature;
}
}
package com.comName.dhm.common.license.vo;
/**
* 系统信息实体(tag名:systemInfo)
*
*/
public class SystemInfo
{
/**
* 系统名(tag名:name)
*/
private String name;
/**
* 系统名(tag名:version)
*/
private String version;
/**
* 系统名(tag名:serial)
*/
private String serial;
/**
* 系统名(tag名:ip)
*/
private String ip;
/**
* 系统名(tag名:mac)
*/
private String mac;
/**
* 系统名(tag名:expiration)
*/
private String expiration;
/**
* 系统名(tag名:controlLevel)
*/
private String controlLevel;
/**
* 取得name
*
* @return name的值
*/
public String getName()
{
return name;
}
/**
* 设置name
*
* @param 设置的name
*/
public void setName(String name)
{
this.name = name;
}
/**
* 取得version
*
* @return version的值
*/
public String getVersion()
{
return version;
}
/**
* 设置version
*
* @param 设置的version
*/
public void setVersion(String version)
{
this.version = version;
}
/**
* 取得serial
*
* @return serial的值
*/
public String getSerial()
{
return serial;
}
/**
* 设置serial
*
* @param 设置的serial
*/
public void setSerial(String serial)
{
this.serial = serial;
}
/**
* 取得ip
*
* @return ip的值
*/
public String getIp()
{
return ip;
}
/**
* 设置ip
*
* @param 设置的ip
*/
public void setIp(String ip)
{
this.ip = ip;
}
/**
* 取得mac
*
* @return mac的值
*/
public String getMac()
{
return mac;
}
/**
* 设置mac
*
* @param 设置的mac
*/
public void setMac(String mac)
{
this.mac = mac;
}
/**
* 取得expiration
*
* @return expiration的值
*/
public String getExpiration()
{
return expiration;
}
/**
* 设置expiration
*
* @param 设置的expiration
*/
public void setExpiration(String expiration)
{
this.expiration = expiration;
}
/**
* 取得controlLevel
*
* @return controlLevel的值
*/
public String getControlLevel()
{
return controlLevel;
}
/**
* 设置controlLevel
*
* @param 设置的controlLevel
*/
public void setControlLevel(String controlLevel)
{
this.controlLevel = controlLevel;
}
}
LicenseInit
package com.comName.dhm.common.license;
import org.apache.log4j.Logger;
import com.comName.dhm.common.init.SystemInitiator;
/**
* @author
*
*/
public class LicenseInit
{
/**
*
*/
public LicenseInit()
{
}
/**
* 日志对象
*/
private Logger logger = Logger.getLogger(LicenseInit.class);
/**
* serialId
*/
private static final long serialVersionUID = -8345723002031989740L;
/**
* license文件
*/
private String licensePath = null;
/**
* 公钥文件
*/
private String publicKeyPath = null;
/**
* 过滤器初始化处理,取得配置参数的值
*
* @param config
* FilterConfig对象
*/
public void init(String licenseFileName, String publicKeyFileName)
{
// log开始
logger.debug("LicenseInitServlet加载开始。");
// 获取文件分割符
String fs = System.getProperty("file.separator");
// 从web.xml获取参数
String confPath = SystemInitiator.getSystemInfo().getConfPath();
// License路径
this.licensePath = confPath + fs + licenseFileName;
// publicKey路径
this.publicKeyPath = confPath + fs + publicKeyFileName;
if (logger.isDebugEnabled())
{
logger.debug("licensePath:" + licensePath + ";publicKeyPath:" + publicKeyPath);
}
// 执行处理
LicenseUtil.initLicense(licensePath, publicKeyPath);
}
public static void main(String[] args)
{
// 执行处理
LicenseUtil.initLicense("F:\\workspace\\SDP.SME.CD\\SDP.SME.CD\\aaa\\conf\\common\\license.xml",
"F:\\workspace\\SDP.SME.CD\\SDP.SME.CD\\aaa\\conf\\common\\publickey.txt");
}
}
SystemInitiator
package com.comName.dhm.common.init;
import javax.servlet.ServletContext;
/**
* @author 903939
*
*/
public class SystemInitiator
{
static private SystemInfo systemInfo = null;
static public SystemInfo getSystemInfo()
{
return systemInfo;
}
public static void setSystemInfo(SystemInfo systemInfo)
{
SystemInitiator.systemInfo = systemInfo;
}
public static void initApp(ServletContext ctx)
{
// get file seperator
String FS = System.getProperty("file.separator");
// get system name configed in web.xml
String systemName = ctx.getInitParameter("dhm-system-name");
// get working dir
String work_dir = System.getProperty("user.dir");
// set conf path
String confPath = work_dir + FS + systemName + FS + ctx.getInitParameter("system.config-path-name");
// set log path
String logPath = work_dir + FS + systemName + FS + ctx.getInitParameter("system.log-path-name");
systemInfo = new SystemInfo(systemName, confPath, logPath);
System.out.println(systemInfo.toString());
}
}
package com.comName.dhm.common.init;
/**
* @author
*
*/
public class SystemInfo
{
private String systemName = null;
private String confPath = null;
private String logPath = null;
public SystemInfo(String systemName, String confPath, String logPath)
{
this.systemName = systemName;
this.confPath = confPath;
this.logPath = logPath;
}
public String getSystemName()
{
return systemName;
}
public String getConfPath()
{
return confPath;
}
public String getLogPath()
{
return logPath;
}
public String toString()
{
return this.getClass().getName() + "[systemName=" + this.getSystemName() + ";confPath=" + this.getConfPath()
+ ";logPath=" + this.getLogPath() + "]";
}
}
package com.comName.dhm.common.license;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import org.apache.log4j.Logger;
import com.comName.dhm.common.init.SystemInitiator;
/**
* <一句话功能简述>
* <功能详细描述>
*
* @author 904008
* @version [V200R001]
* @date 2010-9-26
* @see [相关类/方法]
* @since [DHM.Core.IEPGM-V200R001]
*/
/**
* <一句话功能简述>
* <功能详细描述>
*
* @author 904008
* @version [V200R001, 2010-9-26]
* @see [相关类/方法]
* @since [DHM.Core.IEPGM-V200R001]
*/
public class LicenseInitListener implements ServletContextListener
{
/**
* 日志对象
*/
private static Logger logger = Logger.getLogger(LicenseInitServlet.class);
/**
* serialId
*/
private static final long serialVersionUID = -8345723002031989740L;
/**
* license文件
*/
private String licensePath = null;
/**
* 公钥文件
*/
private String publicKeyPath = null;
/**
* 过滤器初始化处理,取得配置参数的值
*
* @param config
* FilterConfig对象
* @throws ServletException
*/
public void contextDestroyed(ServletContextEvent sce)
{
}
public void contextInitialized(ServletContextEvent sce)
{
// log开始
logger.debug("LicenseInitListener加载开始。");
ServletContext ctx = sce.getServletContext();
// 获取文件分割符
String fs = System.getProperty("file.separator");
// 从web.xml获取参数
String confPath = SystemInitiator.getSystemInfo().getConfPath();
String licenseFileName = ctx.getInitParameter("license.license-file");
String publicKeyFileName = ctx.getInitParameter("license.public-key-file");
// License路径
this.licensePath = confPath + fs + licenseFileName;
// publicKey路径
this.publicKeyPath = confPath + fs + publicKeyFileName;
logger.debug("licensePath:" + licensePath + ";publicKeyPath:" + publicKeyPath);
// 执行处理
LicenseUtil.initLicense(licensePath, publicKeyPath);
}
}
package com.comName.dhm.common.license;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import org.apache.log4j.Logger;
import com.comName.dhm.common.init.SystemInitiator;
public class LicenseInitListener implements ServletContextListener
{
/**
* 日志对象
*/
private static Logger logger = Logger.getLogger(LicenseInitServlet.class);
/**
* serialId
*/
private static final long serialVersionUID = -8345723002031989740L;
/**
* license文件
*/
private String licensePath = null;
/**
* 公钥文件
*/
private String publicKeyPath = null;
/**
* 过滤器初始化处理,取得配置参数的值
*
* @param config
* FilterConfig对象
* @throws ServletException
*/
public void contextDestroyed(ServletContextEvent sce)
{
}
public void contextInitialized(ServletContextEvent sce)
{
// log开始
logger.debug("LicenseInitListener加载开始。");
ServletContext ctx = sce.getServletContext();
// 获取文件分割符
String fs = System.getProperty("file.separator");
// 从web.xml获取参数
String confPath = SystemInitiator.getSystemInfo().getConfPath();
String licenseFileName = ctx.getInitParameter("license.license-file");
String publicKeyFileName = ctx.getInitParameter("license.public-key-file");
// License路径
this.licensePath = confPath + fs + licenseFileName;
// publicKey路径
this.publicKeyPath = confPath + fs + publicKeyFileName;
logger.debug("licensePath:" + licensePath + ";publicKeyPath:" + publicKeyPath);
// 执行处理
LicenseUtil.initLicense(licensePath, publicKeyPath);
}
}
package com.comName.dhm.common.license;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.apache.log4j.Logger;
import com.comName.dhm.common.init.SystemInitiator;
/**
* License加载Servlet
*/
public class LicenseInitServlet extends HttpServlet
{
/**
* 日志对象
*/
private static Logger logger = Logger.getLogger(LicenseInitServlet.class);
/**
* serialId
*/
private static final long serialVersionUID = -8345723002031989740L;
/**
* license文件
*/
private String licensePath = null;
/**
* 公钥文件
*/
private String publicKeyPath = null;
/**
* 过滤器初始化处理,取得配置参数的值
*
* @param config
* FilterConfig对象
* @throws ServletException
*/
public void init(ServletConfig config) throws ServletException
{
// log开始
logger.debug("LicenseInitServlet加载开始。");
// 获取文件分割符
String fs = System.getProperty("file.separator");
// 从web.xml获取参数
String confPath = SystemInitiator.getSystemInfo().getConfPath();
String licenseFileName = config.getInitParameter("license-file");
String publicKeyFileName = config.getInitParameter("public-key-file");
// License路径
this.licensePath = confPath + fs + licenseFileName;
// publicKey路径
this.publicKeyPath = confPath + fs + publicKeyFileName;
logger.debug("licensePath:" + licensePath + ";publicKeyPath:" + publicKeyPath);
// 执行处理
LicenseUtil.initLicense(licensePath, publicKeyPath);
}
}
package com.comName.dhm.common.license;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import com.comName.dhm.common.license.vo.License;
import com.comName.dhm.common.license.vo.LicenseInfo;
import com.comName.dhm.common.license.vo.SystemInfo;
/**
* License操作公用类
*
*/
public class LicenseUtil
{
/**
* 日志对象
*/
private static Logger logger = Logger.getLogger(LicenseUtil.class);
/**
* signature对象的名字
*/
public static final String SIGNATURE_NAME = "signature";
/**
* 将字节数组转化为十六进制
*
* @param theData
* 字节数组
* @return 十六进制数据
*/
public static String bytesToHexString(byte[] theData)
{
StringBuffer hexStrBuff = new StringBuffer(theData.length * 2);
for (int i = 0; i < theData.length; i++)
{
String hexByteStr = Integer.toHexString(theData[i] & 0xff).toUpperCase();
if (hexByteStr.length() == 1)
{
hexStrBuff.append("0");
}
hexStrBuff.append(hexByteStr);
}
return hexStrBuff.toString();
}
/**
* 将十六进制转化为字节数组
*
* @param theHexString
* 十六进制数据
* @return 字节数组
*/
public static byte[] hexStringToBytes(String theHexString)
{
byte data[] = new byte[theHexString.length() / 2];
for (int i = 0; i < data.length; i++)
{
String a = theHexString.substring(i * 2, i * 2 + 2);
data[i] = (byte) Integer.parseInt(a, 16);
}
return data;
}
/**
* 取得文件对象的Dom对象
*
* @return 文件对象的Dom对象
*/
public static Element getFileRootDocument(File xmlFile)
{
if (xmlFile == null || !xmlFile.exists())
{
logger.error("取得文件对象的Dom对象时,文件不存在。");
return null;
}
try
{
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(xmlFile);
return doc.getRootElement();
}
catch (JDOMException e)
{
logger.error("取得文件对象的Dom对象异常", e);
}
catch (IOException e)
{
logger.error("取得文件对象的Dom对象异常", e);
}
return null;
}
/**
* 读取文件内容,保存为byte数组
*
* @param filePath
* 文件路径
* @return 文件内容数据
* @throws IOException
*/
public static byte[] readFile(String filePath) throws IOException
{
// 文件名是否为空
if (filePath == null)
{
logger.error("文件名为空,不能读取数据。");
return null;
}
// 构建File对象
File file = new File(filePath);
if (file.exists() && file.isFile())
{
long fileLength = file.length();
if (fileLength > 0L)
{
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file));
byte[] b = new byte[(int) fileLength];
while (fis.read(b) != -1)
{
}
fis.close();
fis = null;
return b;
}
}
else
{
return null;
}
return null;
}
/**
* 读取文件的数据
*
* @param file
* 数据文件
* @return 文件的数据
*/
public static String readContentFromFile(File file)
{
if (file == null || !file.exists() || !file.isFile())
{
logger.debug("读取文件的数据时,文件不存在。");
return null;
}
StringBuffer tmpStr = new StringBuffer();
InputStreamReader isr = null;
try
{
isr = new InputStreamReader(new FileInputStream(file));
char[] bf = new char[1024];
int i = -1;
while ((i = isr.read(bf)) != -1)
{
tmpStr.append(bf, 0, i);
}
isr.close();
return tmpStr.toString();
}
catch (IOException e)
{
e.printStackTrace();
if (isr != null)
{
try
{
isr.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
return null;
}
/**
* 取得指定的element
*
* @param rootElement
* RootDocument对象
* @param name
* 节点名字
* @return 指定的element
*/
public static Element getElementByName(Element rootElement, String name)
{
List<Element> target = getElementsByName(rootElement, name);
if (target != null && target.size() > 0)
{
return target.get(0);
}
return null;
}
/**
* 取得指定的element一览
*
* @param rootElement
* RootDocument对象
* @param name
* 节点名字
* @return 指定的element一览
*/
public static List<Element> getElementsByName(Element rootElement, String name)
{
if (name == null)
{
// 节点名字不能为空
logger.error("取得指定的element一览时,节点名字为空。");
return null;
}
if (rootElement == null)
{
// license内容对象不能为空
logger.error("取得指定的element一览时,license内容对象为空。");
return null;
}
List<Element> target = new ArrayList<Element>();
searchElementByName(target, rootElement, name);
return target;
}
/**
* 递归取得指定的element一览
*
* @param target
* element一览
* @param rootElement
* RootDocument对象
* @param name
* 节点名字
* @return 指定的element一览
*/
private static List<Element> searchElementByName(List<Element> target, Element element, String name)
{
List<?> eleList = element.getChildren();
if (name.equalsIgnoreCase(element.getName()))
{
target.add(element);
}
if (eleList.size() == 0)
{
return target;
}
else
{
for (Iterator<?> iterator = eleList.iterator(); iterator.hasNext();)
{
Element element2 = (Element) iterator.next();
searchElementByName(target, element2, name);
}
}
return target;
}
/**
* 取得签名信息
*
* @param rootElement
* license的Element对象
* @return 签名信息
*/
public static String getSignatureSource(Element rootElement)
{
if (rootElement == null)
{
// TODO:error 没有要签名的对象
logger.error("取得签名信息时,没有要签名的对象。");
return null;
}
// 要签名的信息
StringBuffer sb = new StringBuffer();
fetchElementLeafValue(rootElement, sb);
return sb.toString();
}
/**
* 递归取得license文件的内容
*
* @param element
* 当前Element对象
* @param sb
* buffer
* @return 签名信息
*/
private static void fetchElementLeafValue(Element element, StringBuffer sb)
{
if (element == null)
{
return;
}
List<?> list = element.getChildren();
// signature对象不作为签名对象
if (list.size() == 0 && !SIGNATURE_NAME.equalsIgnoreCase(element.getName()))
{
sb.append("&").append(element.getText());
}
// 递归调用
for (Iterator<?> iterator = list.iterator(); iterator.hasNext();)
{
Element ele = (Element) iterator.next();
fetchElementLeafValue(ele, sb);
}
}
/**
* 取得License对象
*
* @param rootElement
* RootDocument对象
* @return License对象
*/
public static License getLicenseByXML(Element rootElement)
{
License license = new License();
// SystemInfo
SystemInfo sysInfo = new SystemInfo();
sysInfo.setName(getElementValueByName(rootElement, "name"));
sysInfo.setVersion(getElementValueByName(rootElement, "version"));
sysInfo.setSerial(getElementValueByName(rootElement, "serial"));
sysInfo.setIp(getElementValueByName(rootElement, "ip"));
sysInfo.setMac(getElementValueByName(rootElement, "mac"));
sysInfo.setExpiration(getElementValueByName(rootElement, "expiration"));
sysInfo.setControlLevel(getElementValueByName(rootElement, "controlLevel"));
license.setSystemInfo(sysInfo);
// ControlItems
List<Element> ciElementList = getElementsByName(rootElement, "controlItem");
Map<String, String> ciMap = new HashMap<String, String>();
for (Iterator<Element> iterator = ciElementList.iterator(); iterator.hasNext();)
{
Element element = (Element) iterator.next();
ciMap.put(element.getChildText("name"), element.getChildText("value"));
}
license.setControlItems(ciMap);
// signature
license.setSignature(getElementValueByName(rootElement, "signature"));
return license;
}
/**
* 取得指定的element的值
*
* @param rootElement
* RootDocument对象
* @param name
* 节点名字
* @return 指定的element的值
*/
private static String getElementValueByName(Element rootElement, String name)
{
Element element = getElementByName(rootElement, name);
if (element == null)
{
return null;
}
return element.getText();
}
/**
* <p>
* 方法 getLocalIp
* </p>
* 获取本机ip地址
*
* @return
*/
public static String getLocalIp()
{
String localIp = null;
try
{
localIp = InetAddress.getLocalHost().getHostAddress();
}
catch (UnknownHostException e)
{
// TODO:获取服务器IP地址失败!
logger.error("获取服务器IP地址失败。", e);
}
return localIp;
}
/**
* <p>
* 方法 getLocalMac
* </p>
* 获取本机MAC地址
*
* @return
*/
public static String getLocalMac()
{
String os = getOSName();
String mac = null;
try
{
// System.out.println(os);
if (os.startsWith("windows"))
{
// 本地是windows
mac = getWindowsMACAddress();
// System.out.println(mac);
}
else
{
// 本地是非windows系统 一般就是unix
mac = getUnixMACAddress();
// System.out.println(mac);
}
}
catch (Exception e)
{
// TODO:获取服务器MAC地址失败!
logger.error("获取服务器MAC地址失败。", e);
}
return mac;
}
/**
* 获取当前操作系统名称. return 操作系统名称 例如:windows xp,linux 等.
*/
private static String getOSName()
{
return System.getProperty("os.name").toLowerCase();
}
/**
* 获取unix网卡的mac地址. 非windows的系统默认调用本方法获取.如果有特殊系统请继续扩充新的取mac地址方法.
*
* @return mac地址
*/
private static String getUnixMACAddress()
{
String mac = null;
BufferedReader bufferedReader = null;
Process process = null;
try
{
process = Runtime.getRuntime().exec("ifconfig eth0");// linux下的命令,一般取eth0作为本地主网卡
// 显示信息中包含有mac地址信息
bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
int index = -1;
while ((line = bufferedReader.readLine()) != null)
{
index = line.toLowerCase().indexOf("hwaddr");// 寻找标示字符串[hwaddr]
if (index >= 0)
{// 找到了
mac = line.substring(index + "hwaddr".length() + 1).trim();// 取出mac地址并去除2边空格
break;
}
}
}
catch (IOException e)
{
logger.error("获取服务器MAC地址失败时,发生IO异常。", e);
}
finally
{
try
{
if (bufferedReader != null)
{
bufferedReader.close();
}
}
catch (IOException e1)
{
logger.error("获取服务器MAC地址失败时,发生IO异常。", e1);
}
bufferedReader = null;
process = null;
}
return mac;
}
/**
* 获取widnows网卡的mac地址.
*
* @return mac地址
*/
private static String getWindowsMACAddress()
{
String mac = null;
BufferedReader bufferedReader = null;
Process process = null;
try
{
process = Runtime.getRuntime().exec("ipconfig /all");// windows下的命令,显示信息中包含有mac地址信息
bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
int index = -1;
while ((line = bufferedReader.readLine()) != null)
{
index = line.toLowerCase().indexOf("physical address");// 寻找标示字符串[physical
// address]
if (index >= 0)
{// 找到了
index = line.indexOf(":");// 寻找":"的位置
if (index >= 0)
{
mac = line.substring(index + 1).trim();// 取出mac地址并去除2边空格
}
break;
}
}
}
catch (IOException e)
{
logger.error("获取服务器MAC地址失败时,发生IO异常。", e);
}
finally
{
try
{
if (bufferedReader != null)
{
bufferedReader.close();
}
}
catch (IOException e1)
{
logger.error("获取服务器MAC地址失败时,发生IO异常。", e1);
}
bufferedReader = null;
process = null;
}
return mac;
}
public static void initLicense(String licensePath, String publicKeyPath)
{
try
{
// license文件不存在
File lisenceFile = new File(licensePath);
if (!lisenceFile.exists() || !lisenceFile.isFile())
{
logger.error("License验证加载错误,系统退出。原因:License文件不存在。");
System.exit(1);
return;
}
// license文件不存在
File publicKeyFile = new File(publicKeyPath);
if (!publicKeyFile.exists() || !publicKeyFile.isFile())
{
logger.error("License验证加载错误,系统退出。原因:公钥文件不存在。");
System.exit(1);
return;
}
// 取得License 文件的rootElement
Element rootElement = LicenseUtil.getFileRootDocument(lisenceFile);
// 要签名的信息
String myinfo = LicenseUtil.getSignatureSource(rootElement);
// Signature取得
Element signEle = LicenseUtil.getElementByName(rootElement, LicenseUtil.SIGNATURE_NAME);
if (signEle == null)
{
logger.error("License验证加载错误,系统退出。原因:签名信息不存在。");
System.exit(1);
return;
}
String signStr = signEle.getText();
// license校验
// 这是GenerateKeyPair输出的公钥编码
byte[] publicKey = LicenseUtil.readFile(publicKeyPath);
if (publicKey == null || publicKey.length == 0)
{
logger.error("License验证加载错误,系统退出。原因:公钥取得失败。");
System.exit(1);
return;
}
// 公钥验证签名
X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(publicKey);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(bobPubKeySpec);
byte[] signed = LicenseUtil.hexStringToBytes(signStr);// 这是SignatureData输出的数字签名
Signature signetcheck = Signature.getInstance("MD5withRSA");
signetcheck.initVerify(pubKey);
signetcheck.update(myinfo.getBytes());
License license = null;
if (signetcheck.verify(signed))
{
// 将License对象放入内存
logger.info("签名正常。");
}
else
{
logger.error("License验证加载错误,系统退出。原因:签名验证失败。");
System.exit(1);
return;
}
license = LicenseUtil.getLicenseByXML(rootElement);
if (license == null)
{
logger.error("License验证加载错误,系统退出。原因:License对象取得失败。");
System.exit(1);
return;
}
SystemInfo sysinfo = license.getSystemInfo();
// ip 检验
String ip = sysinfo.getIp();
String serverIp = LicenseUtil.getLocalIp();
logger.debug("License Ip:" + ip + ";Server IP:" + serverIp);
if (!"any".equals(ip) && !serverIp.equals(ip))
{
// IP地址已经修改
logger.error("License验证加载错误,系统退出。IP地址已经修改。");
System.exit(1);
return;
}
// mac 检验
String mac = sysinfo.getMac();
String serverMac = LicenseUtil.getLocalMac();
logger.debug("License Mac:" + mac + ";Server Mac:" + serverMac);
if (!"any".equals(mac) && !serverMac.equalsIgnoreCase(mac))
{
// Mac地址已经修改
logger.error("License验证加载错误,系统退出。Mac地址已经修改。");
System.exit(1);
return;
}
// 系统超时 检验
logger.debug("License Expiration:" + sysinfo.getExpiration());
if (!"never".equalsIgnoreCase(sysinfo.getExpiration()))
{
Calendar cpCalendar = new GregorianCalendar();
// 日期格式:2009-1-1 12:00:00
SimpleDateFormat parseTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date expireDate;
try
{
expireDate = parseTime.parse(sysinfo.getExpiration());
}
catch (ParseException e)
{
// 日期格式化失败
logger.error("License验证加载错误,超时日期格式化失败。");
System.exit(1);
return;
}
cpCalendar.setTime(expireDate);
// 得到系统当前日期
Calendar nowCalendar = Calendar.getInstance();
if (nowCalendar.getTimeInMillis() > cpCalendar.getTimeInMillis())
{
// 已经过期
logger.error("License验证加载错误,系统退出。license已经失效。");
System.exit(1);
return;
}
}
LicenseInfo.setLicense(license);
}
catch (Exception e)
{
logger.error("License验证加载时,发生异常,系统退出。异常信息:", e);
System.exit(1);
return;
}
}
}
java中license授权方案 javalicense验证
转载本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
MYsql 写入中文 insert into
字符集转换概述我们有必要说明一下,字符其实是面向人类的一个概念,计算机可并不关心字符是什么,它只关心这个字符对应的字节编码是什么。对于一个字节序列,计算机怎么知道它是使用什么字符集编码的呢?计算机不知道,所以其实在计算机中表示一个字符串时,都需要附带上它对应的字符集是什么,就像这样(以C++语言为例):class String { byte* content; CHARSET_INFO* char
linux中的mysql输入中文是乱码 mac mysql客户端 mysql 序列 mysql 默认当前时间 mysql中文乱码 cmd