精华内容
下载资源
问答
  • License校验

    千次阅读 2015-11-28 09:59:53
    license
    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;
            }
        }
    }



    展开全文
  • License 校验

    2017-10-24 16:40:00
    1:了解keytool 的一些命令 ... 本人在github找的一个demo:https://github.com/jingshauizh/JavaSpringSurmmary/tree/master/java-license-jar 2:生成备用的 privateKeys.store(...

    1:了解keytool 的一些命令  http://www.micmiu.com/lang/java/keytool-start-guide/

    本人在github找的一个demo:https://github.com/jingshauizh/JavaSpringSurmmary/tree/master/java-license-jar

     

    2:生成备用的 privateKeys.store(认证端) 和 publicCerts.store(使用端)

     生成privateKeys.store,执行如下命令

    keytool -genkey -alias privatekey -keystore privateKeys.store -storepass bug55555 -keypass aa123456 -validity 365

    生成certfile.cer

    keytool -export -alias privatekey -file certfile.cer -keystore privateKeys.store

    生成publicCerts.store

    keytool -import -alias publiccert -file certfile.cer -keystore publicCerts.store -storepass bug55555

     

    注意: 创建的license.lic文件 和 验证的文件必须在同一个包位置

     

    转载于:https://www.cnblogs.com/eason-d/p/7724371.html

    展开全文
  • 重新打包至com.spket.ui_1.6.18.jar。 替换原来安装目录的com.spket.ui_1.6.18.jar包。 重新打开Spket。
  • 页面构件license校验失败"的错误,license过期吗?难道他的studio用了有一年了,显然还没到,我记得上个月他才重装过一次,那是怎么了? 想了好一会他才提起为了测试方便他改了本地时间,从08-10-17改成了08-5-...

          最近项目中一位开发人员机器上出现一个有趣的现象(该TX经常遇到类似的怪问题),studio用的好好的执行页面时却突然出现"页面构件license校验失败"的错误,license过期吗?难道他的studio用了有一年了,显然还没到,我记得上个月他才重装过一次,那是怎么了?
          想了好一会他才提起为了测试方便他改了本地时间,从08-10-17改成了08-5-17,这就难怪了,他的studio大概是9月十几号才装的,本地时间比安装时间还要早不报错才怪......时间调整回来重启SERVER问题解决。

    总之,SERVER端时间不能早于EOS安装时间,否则会报"页面构件license校验失败"的错误。

    展开全文
  • License制作校验工具

    千次阅读 2018-12-15 16:04:00
    License key tool 生成私钥和公钥库 生成密钥库和密钥 keytool -genkey -alias privatekey -keysize 1024 -keystore D:\privateKey.store -validity 365 导出密钥库内密钥的证书 keytool -export -alias privatekey...

    License

    key tool 生成私钥和公钥库

    生成密钥库和密钥

    keytool -genkey -alias privatekey -keysize 1024 -keystore D:\privateKey.store -validity 365
    

    导出密钥库内密钥的证书

    keytool -export -alias privatekey -keystore D:\privateKey.store -file D:\certfile.cer
    

    创建公钥库

    keytool -import -alias pulbiccert -file D:\certfile.cer -keystore D:\publicCerts.store
    

    解释

     -alias 表示密钥的别名
     
     -keystore 表示当前密钥属于哪个密钥库 
     
     -validity 表示有效期(单位:天)
    

    Server

    package com.yzz.license.server.license;
    
    import com.yzz.license.server.bean.LicenseConfigBean;
    import com.yzz.license.server.manager.LicenseManagerHolder;
    import com.yzz.license.server.reader.AbstractPropertyReader;
    import com.yzz.license.server.reader.PropertyServerReader;
    import de.schlichtherle.license.*;
    
    import javax.security.auth.x500.X500Principal;
    import java.io.File;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.prefs.Preferences;
    
    /**
     * describe:
     * E-mail:yzzstyle@163.com  date:2018/12/5
     *
     * @Since ${project_version}
     */
    public class LicenseMaker {
    
        /**
         * X500Principal是一个证书文件的固有格式
         */
        private final static X500Principal DEFAULTHOLDERANDISSUER =
                new X500Principal("CN=y,OU=y,O=y,L=y,ST=y,C=y");
    
        private LicenseParam initLicenseParam(LicenseConfigBean licenseConfigBean) {
            Class<LicenseMaker> clazz = LicenseMaker.class;
            Preferences pre = Preferences.userNodeForPackage(clazz);
            //设置对证书内容加密的对称密码
            CipherParam cipherParam = new DefaultCipherParam(licenseConfigBean.getKeyStorePwd());
            /**
             * clazz 从哪个类Class.getResource()获得密钥库
             * priPath 从哪个类Class.getResource()获得密钥库
             * priAlias 密钥库的别名
             * keystorePwd 密钥库存储密码
             * privateKeyPwd 密钥库密码
             */
            KeyStoreParam privateStoreParam = new DefaultKeyStoreParam(
                    clazz, licenseConfigBean.getPriPath(), licenseConfigBean.getPriAlias(), licenseConfigBean.getKeyStorePwd(), licenseConfigBean.getPrivateKeyPwd());
            //返回生成证书时需要的参数
            LicenseParam licenseParam = new DefaultLicenseParam(
                    licenseConfigBean.getSubject(), pre, privateStoreParam, cipherParam);
            return licenseParam;
        }
    
        public LicenseContent buildLicenseContent(LicenseConfigBean licenseConfigBean) throws ParseException {
            LicenseContent content = new LicenseContent();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            content.setSubject(licenseConfigBean.getSubject());
            content.setConsumerAmount(licenseConfigBean.getConsumerAmount());
            content.setConsumerType(licenseConfigBean.getConsumerType());
            content.setHolder(DEFAULTHOLDERANDISSUER);
            content.setIssuer(DEFAULTHOLDERANDISSUER);
            content.setIssued(format.parse(licenseConfigBean.getIssued()));
            content.setNotBefore(format.parse(licenseConfigBean.getNotBefore()));
            content.setNotAfter(format.parse(licenseConfigBean.getNotAfter()));
            content.setInfo(licenseConfigBean.getInfo());
            content.setExtra(new Object());
            return content;
        }
    
        public void create(String confPath) {
            try {
                //将配置文件加载进内存
                AbstractPropertyReader<LicenseConfigBean> propertyReader = new PropertyServerReader();
                LicenseConfigBean licenseConfigBean = propertyReader.read(confPath);
                LicenseManager licenseManager = LicenseManagerHolder.initManager(initLicenseParam(licenseConfigBean));
                LicenseContent content = buildLicenseContent(licenseConfigBean);
                licenseManager.store(content, new File(licenseConfigBean.getLicPath()));
                System.out.println("证书发布成功");
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public static void main(String[] args) {
            LicenseMaker maker = new LicenseMaker();
            maker.create("license-make-config.properties");
        }
    }
    
    

    Client

    package com.yzz.license.client.valid;
    
    import com.yzz.license.client.Exception.LicenseExpiredException;
    import com.yzz.license.client.Exception.LicenseInstallFailedException;
    import com.yzz.license.client.Exception.LicenseVerifyFailedException;
    import com.yzz.license.client.bean.ClientValidConfigBean;
    import com.yzz.license.client.reader.PropertyClientReader;
    import de.schlichtherle.license.*;
    
    import java.io.File;
    import java.util.prefs.Preferences;
    
    /**
     * describe:客户端验证License Api
     * E-mail:yzzstyle@163.com  date:2018/12/5
     *
     * @Since 0.0.1
     */
    public class ClientValidLicense {
    
        private static final String Def_CONF_PATH = "client-valid.properties";
    
        private static volatile ClientValidLicense clientValidLicense;
    
        private ClientValidLicense(String onlyKey) {
            //防止反射
            if (null != clientValidLicense){
                throw new IllegalStateException("ClientValidLicense has be created !");
            }
           new ClientValidLicense(Def_CONF_PATH,onlyKey);
        }
    
        private ClientValidLicense(String confPath, String onlyKey) {
            //防止反射
            if (null != clientValidLicense){
                throw new IllegalStateException("ClientValidLicense has be created !");
            }
            PropertyClientReader reader = new PropertyClientReader();
            ClientValidConfigBean clientValidConfigBean = reader.read(confPath);
            clientValidConfigBean.setOnlykey(onlyKey);
            //初始licenseManger
            LicenseParam param = initLicenseParams(clientValidConfigBean);
            LicenseManagerHolder.initManager(param);
    
        }
    
        public static ClientValidLicense getInstance(String onlyKey){
            return getInstance(Def_CONF_PATH,onlyKey);
        }
    
        /**
         * 需要加上volatile关键字,防止ClientValidLicense 实例化的时候重排序,导致其他获取的对象为null
         * double check 单利
         * @param confPath
         * @param onlyKey
         * @return
         */
        public static ClientValidLicense getInstance(String confPath, String onlyKey){
            if (null != clientValidLicense){
                return clientValidLicense;
            }
            synchronized (ClientValidLicense.class){
                clientValidLicense = new ClientValidLicense(confPath, onlyKey);
            }
            return clientValidLicense;
        }
    
        /**
         * 初始化参数
         * @param clientValidConfigBean
         * @return
         */
        private LicenseParam initLicenseParams(ClientValidConfigBean clientValidConfigBean) {
            Class<ClientValidLicense> clazz = ClientValidLicense.class;
            Preferences pre = Preferences.userNodeForPackage(clazz);
            CipherParam cipherParam = new DefaultCipherParam(clientValidConfigBean.getKeyStorePwd());
            KeyStoreParam pubStoreParam = new DefaultKeyStoreParam(
                    clazz, clientValidConfigBean.getPubPath(),clientValidConfigBean.getPubAlias(), clientValidConfigBean.getKeyStorePwd(), null);
    
            LicenseParam licenseParam = new DefaultLicenseParam(
                    clientValidConfigBean.getOnlykey(), pre, pubStoreParam, cipherParam);
            return licenseParam;
        }
    
        /**
         * 安装license
         * @param licDir
         * @return
         */
        public void install(String licDir) throws LicenseInstallFailedException, LicenseVerifyFailedException {
            try {
                LicenseManager licenseManager = LicenseManagerHolder.getLicenseManager();
                File file = new File(licDir);
                licenseManager.install(file);
            } catch (Exception e) {
                e.printStackTrace();
                if (e instanceof LicenseContentException){
                    throw new LicenseInstallFailedException();
                }else {
                    throw new LicenseVerifyFailedException();
                }
            }
        }
    
        /**
         * 验证license
         * @return
         */
        public void verify() throws LicenseExpiredException, LicenseVerifyFailedException {
            try {
                LicenseManagerHolder.getLicenseManager().verify();
            } catch (LicenseContentException ex) {
                throw new LicenseExpiredException();
            } catch (Exception e) {
               throw new LicenseVerifyFailedException();
            }
    
        }
    
        public static void main(String[] args) {
            try {
                ClientValidLicense clientValidLicense = ClientValidLicense.getInstance("GADQB");
                clientValidLicense.install("D:\\key\\lic\\license.lic");
                clientValidLicense.verify();
            } catch (LicenseInstallFailedException e) {
                e.printStackTrace();
            } catch (LicenseVerifyFailedException e) {
                e.printStackTrace();
            } catch (LicenseExpiredException e) {
                e.printStackTrace();
            }
    
        }
    }
    
    

    GitHub主页

    展开全文
  • 给客户部署的应用中添加License校验1,添加License校验类需要的参数2,添加Listener,用于在项目启动的时候安装License证书3,添加拦截器,用于在登录的时候校验License证书4,添加登录页面并测试 一,简介 L
  • License文件生成原理

    千次阅读 2020-01-02 13:32:38
    license通过认证和鉴权实现管控,认证指识别用户身份信息,鉴权指校验用户具有哪些功能权限信息; 认证实现方式:可以分为离线和在线,对于在线认证的实现方案,实现一个登录方案,通过账号和密...
  • license 文件不生效

    2020-10-19 09:12:10
    目录 环境 BUG/漏洞编码 症状 触发条件 ...系统平台:银河麒麟U系(CPU飞腾)4,中标麒麟(CPU龙芯)7 ...在飞腾银河麒麟、龙芯中标麒麟操作系统下,校验license的RototeL函数在运行memcpy(ln,ln+loop,le..
  • License授权 本地部署

    2020-07-14 16:27:18
    跟着产品走 选用license 后来发现业务完全不需要 如果只是校验验证方面问题 完全可以用定时器 加密的激活码 校验部署的mac地址即可 这些东西都可以生成搞成一个不可看的加密文件 但不能白研究两天 因此把研究心得和...
  • DbVisualizer10.0.13破解+LicenseKey

    热门讨论 2018-08-13 17:04:07
    说一下原理dbvis.jar文件的com.onseven.dbvis.util.I包下的A.class里有个方法控制了dbvis.license文件中的dbvis.license.seal项签名校验,修改了字节码,默认返回true。自己动手丰衣足食,同时也希望大家不要太看重...
  • JSR 303 基本的校验规则 1.首先通过IDEA找到类 2.随便点开一个,这些注解类大致配置一样 来个栗子: ( @Pattern 验证 String 对象是否符合正则表达式的规则) /* * Jakarta Bean Validation API * * License: ...
  • 营业执照号校验

    2018-04-25 11:42:00
    jQuery.validator.addMethod("license", function(value, element) { // var length = value.length; var license = /[^_IOZSVa-z\W]{2}\d{6}[^_IOZSVa-z\W]{10}/g; return this.optional(element) || (license.t...
  • 自动分发校验脚本

    2015-07-08 12:04:54
    主要功能是自动发现被监控目录的上传文件。并通过socket传送给各个选定的父节点,然后父节点在同步到子节点IDC#!/usr/bin/envpython #encoding=utf8 ...@license:GNUGPLv3 @author:Wayne @contact:wangzh...
  • swagger 携带taken做为登录校验

    千次阅读 2018-07-05 18:03:29
    /** * * &lt;p&gt; * Licensed under the Apache License, Version 2.0 (the "... * use this file except in compliance with the License. You may obtain a copy of * the License at *...
  • 在具体使用License证书的应用程序,需要加载证书,进行校验证书的有效性。 二、生成公私钥 使用JDK自带的 keytool 工具生成公私钥证书库(1)生成命令:用KeyTool工具来生成私匙库(-alias别名 –validity 3650表示...
  • 合并任务(内部往来抵消、内部收入成本抵消、内部投资资本抵消、双方抵消凭证手工过账、三金冲销、合并后数据校验) 帐一定来源与凭证—报表一定从帐中出 业务场景—实例演示—任务、凭证类型‘记账等级 要合并抵销...
  • Jwt生成token以及token过期校验

    千次阅读 2019-12-06 09:48:02
    永远免费和开源(Apache License,版本2.0),JJWT很容易使用和理解。它被设计成一个以建筑为中心的流畅界面,隐藏了它的大部分复杂性。 2 JJWT快速入门 2.1 token的创建 (1)创建maven工程,引入依赖 <...
  • 串口 传数据位 停止位 校验

    千次阅读 2014-01-04 10:49:22
    /*  * Copyright 2009-2011 Cedric Priscal  *  * Licensed under the Apache License, Version 2.0 (the "License");  * you may not use this file except in compliance with the License.  * You may obtai
  • /*-------------------------------------------------------------------------- jq-idealforms 2.1 * Author: Cedric Ruiz * License: GPL or MIT * Demo: http://elclanrs.github.com/jq-idealfo
  • /******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NO...
  • 网上相关的JS验证和JAVA验证还是有些的. 但是一部分存在String下表越界的bug,自己进行了一些修改后分享给大家. /** * 营业执照 统一社会信用代码(18位) * @param license ...if(StringUtils.isEmpty(license)...
  • package com.moya.common.util;   /** * Copyright (C) 2009-2010 Yichuan, Fuchun All rights reserved.... * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreem
  • 1.这几天在客户这边新装的 Windows 2008 R2企业版做财务服务器使用,上面安装SQL Server和Oracle 11G,找的激活工具进行...查了些相关资料发现该服务是license校验服务,看来激活工具没有彻底激活08系统,从server mana...

空空如也

空空如也

1 2 3 4 5 ... 7
收藏数 131
精华内容 52
关键字:

license校验