Unity/VS/C#Unity工程加密授权开发---LicenseProj

最近在发布Unity工程时要考虑给Unity加密的问题,但有关此类的文章很少,多数人推荐使用C#中的System.Management类实现,虽然Unity3d支持.net3.5架构,但是并不是所有功能都能支持,System.Management类就是其中一个,该类能在VS中很好运行,但在Unity框架中并不支持,因此,我在加密过程中绕过System.Management管理类,这里是通过Unity调用cmd获取ProcessorID,然后再通过C#中System.Security.Cryptography加密算法类进行加密解密。经过一番周折,终于测试成功,这里分享给大家。

主要分为三大步骤来完成:

1.VS创建Windows窗体应用,开发生成License文件工程

第一步,主要完成License生成器开发,能够从这一工程里获取到一个授权的License.lic文件。

2.VS创建类库.Net Framework应用,开发生成.dll类库工程

 第二步,主要完成获取ProcessorID和对License校验功能。

3.创建Uinty工程,引用.dll开发,实现License授权功能

这一步,主要完成对Unity工程授权的逻辑开发,通过对License的授权验证,确定是否进入到工程内部。

一、VS创建Windows窗体应用,生成License工程



1.1License文件生成器代码

 

//---------------------------
//@Author GarFey
//@date 20190612
//@version 1.0
//---------------------------

using System;
using System.Windows.Forms;
using System.IO;
using System.Security.Cryptography;
using System.Management;

namespace LicenesCreater
{
    public partial class 许可证生产器 : Form
    {
        private string key = "GarFey201906101620MA124EAAfeTud00CtDpoQwnvmmStsitSwtsitloxigpxnDPPdSod";
        private string iv = "LeadVR20190610GarFeyCreatPrivatekeyQe90QPlcMA124EA";

        public 许可证生产器()
        {
            InitializeComponent();
        }

        ///
        /// 数据加密 序列化
        ///
        ///
        ///
        ///
        ///
        private string encrption(string input, string key, string iv)
        {
            MemoryStream msEncrypt = null;//读写内存
            RijndaelManaged aesAlg = null;//加密算法类

            string sresult = string.Empty;

            try
            {
                byte[] keys = System.Text.Encoding.UTF8.GetBytes(key);
                byte[] ivs = System.Text.Encoding.UTF8.GetBytes(iv);

                aesAlg = new RijndaelManaged();//加密算法类实例化

                aesAlg.Key = keys;
                aesAlg.IV = ivs;

                ICryptoTransform ict = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);//加密转换接口类
                msEncrypt = new MemoryStream();//读写内存类实例化

                using (CryptoStream cts = new CryptoStream(msEncrypt, ict, CryptoStreamMode.Write))
                {
                    using (StreamWriter sw = new StreamWriter(cts))
                    {
                        sw.Write(input);
                    }
                }

            }
            finally
            {
                if (aesAlg != null)
                {
                    //aesAlg.Dispose();
                    aesAlg.Clear();
                }
            }

            if (msEncrypt != null)
            {
                byte[] content = msEncrypt.ToArray();

                sresult = Convert.ToBase64String(content);
            }

            return sresult;
        }

        ///
        /// 数据解密 反序列化
        ///
        ///
        ///
        ///
        ///
        private string decrption(string input, string key, string iv)
        {
            string sresult = string.Empty;

            byte[] keys = System.Text.Encoding.UTF8.GetBytes(key);
            byte[] ivs = System.Text.Encoding.UTF8.GetBytes(iv);

            byte[] inputbytes = Convert.FromBase64String(input);

            RijndaelManaged rm = null;

            try
            {
                rm = new RijndaelManaged();
                rm.Key = keys;
                rm.IV = ivs;

                ICryptoTransform ict = rm.CreateDecryptor(rm.Key, rm.IV);

                using (MemoryStream ms = new MemoryStream(inputbytes))
                {
                    using (CryptoStream cs = new CryptoStream(ms, ict, CryptoStreamMode.Read))
                    {
                        using (StreamReader sr = new StreamReader(cs))
                        {
                            sresult = sr.ReadToEnd();
                        }
                    }
                }
            }
            finally
            {
                if (rm != null)
                {
                    //rm.Dispose();
                    rm.Clear();
                }
            }
            return sresult;
        }


        private bool IsInTimeInterval(DateTime time, DateTime startTime, DateTime endTime)
        {
            //判断时间段开始时间是否小于时间段结束时间,如果不是就交换
            if (startTime > endTime)
            {
                DateTime tempTime = startTime;
                startTime = endTime;
                endTime = tempTime;
            }

            //获取以公元元年元旦日时间为基础的新判断时间
            DateTime newTime = new DateTime();
            newTime = time;

            //获取以公元元年元旦日时间为基础的区间开始时间
            DateTime newStartTime = new DateTime();
            newStartTime = startTime;

            //获取以公元元年元旦日时间为基础的区间结束时间
            DateTime newEndTime = new DateTime();
            newEndTime = endTime;

            if (newTime >= newStartTime && newTime < newEndTime)
            {
                return true;
            }
            return false;
        }

        private void curCpuId_TextChanged(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }
        private void button2_Click(object sender, EventArgs e)
        {
            System.Management.ManagementClass mc = new ManagementClass("win32_processor");
            ManagementObjectCollection moc = mc.GetInstances();
            String processorid = "";
            foreach (ManagementObject mo in moc)
            {
                processorid = mo["processorid"].ToString();
                //MessageBox.Show(mo["processorid"].ToString());
                break;
            }
            this.textBox1.Text = processorid;
            string text = encrption(this.textBox1.Text, key.Substring(0, 32), iv.Substring(0, 16));
            this.textBox2.Text = text;
            using (FileStream fs = new FileStream("cuteeditor.lic", FileMode.Create, FileAccess.Write, FileShare.None))
            {

                using (StreamWriter sw = new StreamWriter(fs))
                {
                    // sw.Write("None;zh-cn;None;8H489467LS631834L;CuteEditor.Editor for asp.net is licensed.;1.6;5;51aspx.com;125.76.229.233;09/09/2099");
                    sw.Write(text);
                }

                Console.ReadLine();

            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            System.Management.ManagementClass mc = new ManagementClass("win32_processor");
            ManagementObjectCollection moc = mc.GetInstances();
            string processorid = "";
            string testext = "";
            foreach (ManagementObject mo in moc)
            {
                processorid = mo["processorid"].ToString();
                //MessageBox.Show(mo["processorid"].ToString());


                using (FileStream fs = new FileStream("cuteeditor.lic", FileMode.Open, FileAccess.Read, FileShare.None))
                {

                    using (StreamReader sr = new StreamReader(fs))
                    {
                        // sw.Write("None;zh-cn;None;8H489467LS631834L;CuteEditor.Editor for asp.net is licensed.;1.6;5;51aspx.com;125.76.229.233;09/09/2099");
                        testext = sr.ReadToEnd();

                    }

                    Console.ReadLine();

                }
                string text = decrption(testext, key.Substring(0, 32), iv.Substring(0, 16));
                this.textBox3.Text = text;
                if (text == processorid)
                {
                    MessageBox.Show("许可证文件正确");
                }
                else
                {
                    MessageBox.Show("许可证文件不正确 LicInfo:"+ text);
                }
            }
        }


        private void button1_Click(object sender, EventArgs e)
        {
            string text = encrption(this.textBox4.Text, key.Substring(0, 32), iv.Substring(0, 16));
            this.textBox5.Text = text;
            DateTime date01 = dateTimePicker1.Value;
            DateTime date02 = dateTimePicker2.Value;
           
            string date1 = string.Format("{0:yyyy}-" + "{0:MM}-" + "{0:dd}", date01);
            string date2 = string.Format("{0:yyyy}-" + "{0:MM}-" + "{0:dd}", date02);
            string date1changed = encrption(date1, key.Substring(0, 32), iv.Substring(0, 16));
            string date2changed = encrption(date2, key.Substring(0, 32), iv.Substring(0, 16));

            System.DateTime currentTime = new System.DateTime();
            currentTime = System.DateTime.Now;
            if (IsInTimeInterval(currentTime, date01, date02) == true)
            {
                MessageBox.Show("在授权期限内");
            }
            else
            {
                MessageBox.Show("不在授权期限内");
            }
            //MessageBox.Show(date1);
            using (FileStream fs = new FileStream("License.lic", FileMode.Create, FileAccess.Write, FileShare.None))
            {

                using (StreamWriter sw = new StreamWriter(fs))
                {
                    // sw.Write("None;zh-cn;None;8H489467LS631834L;CuteEditor.Editor for asp.net is licensed.;1.6;5;51aspx.com;125.76.229.233;09/09/2099");
                    sw.WriteLine("Copyright (c) [本软件授权使用期限:" + date1 + "--" + date2 + "] [本软件由XXXX有限公司开发]");
                    sw.WriteLine("XXXX 软件许可协议(OEM/IHV/ISV 分销和单个用户)");
                    sw.WriteLine("重要通知 - 在复制、安装或使用之前,请先仔细阅读。");
                    sw.WriteLine("只有在仔细阅读下面的条款之后,方可使用或装载本软件及相关材料(总称为“软件”)。装载或使用本“软件”,即表明您同意本“协议”的条款。如果您不同意本“协议”的条款,请不要安装或使用本“软件”。");
                    sw.WriteLine("此外,还请注意:");
                    sw.WriteLine("* 如果您是原始设备制造商 (OEM)、独立硬件销售商 (IHV),或独立软件供应商 (ISV),本“许可协议”的所有内容对您适用。");
                    sw.WriteLine("* 如果您是最终用户,则只有附件一,即“XXXX 软件许可协议”对您适用。");
                    sw.WriteLine("对于 OEM、IHV 和 ISV:");
                    sw.WriteLine("许可:这一“软件”仅许可用来与 XXXX 组件产品结合使用。本“协议”不授予将此“软件”和其它非 XXXX 组件产品结合使用的许可。受本“协议”条款的约束,XXXX 公司据其版权授予您下述非专有、不可转让、全球性和完全付清的许可:");
                    sw.WriteLine("1. 为您本身的开发和维护目的而内部使用、改动和复制“软件”;并且");
                    sw.WriteLine("2. 更改、复制并向您的最终用户分销“软件”,包括本“软件”的衍生产品,条件是,这种分发必须按照一项许可协议进行,其条款至少要象下面所附的附件一,即 XXXX 公司最终、单个用户“许可协议”中所包含的条款一样严格,以及");
                    sw.WriteLine("3. 更改、复制和分销随“软件”所附的最终用户说明文件,但只能和“软件”一起分发。");
                    sw.WriteLine("");
                    sw.WriteLine("如果您不是装有本“软件”的计算机系统或软件程序的最终制造商或销售商,那么,您可以转让本“软件”的一份副本,包括本“软件”的衍生产品(和有关的最终用户说明文件)给您的接收者,按本“协议”的条款供其使用,条件是,该接收者必须同意完全接受本“协议”条款的约束。您将不得转让、分让或租让许可或以任何其它方式将本“软件”转移或透露给任何第三者。您将不得分解编码、拆散本“软件”或对其进行逆向工程设计。");
                    sw.WriteLine("除本“协议”中明确规定者以外,没有通过任何直接的、隐含的、推理的、禁止反悔的或其它方式授予贵方任何许可或权利。XXXX 公司将有权检查或经由独立审计人检查贵方的有关记录,以证实贵方是否遵守本“协议”的条款。");
                    sw.WriteLine("保密:如果贵方希望由第三方咨询机构或转包人(“承包人”)代贵方从事一些需要接触和使用本“软件”的工作,贵方必须从承包人处获得书面保密协议,其条款和接触使用本“软件”所涉及的责任至少应和本“协议”的条款一样严格,并规定承包人不得分发本“软件”或将之用于任何其它目的。除此之外,贵方不得透露签署过本“协议”或其中的条款,未经 XXXX 公司的书面同意,也不得在任何出版物、广告或其它公告中使用 XXXX 公司的名称。贵方没有任何权利使用 XXXX 公司的任何商标或标识。");
                    sw.WriteLine("软件的所有权和版权:本“软件”所有副本的所有权归 XXXX 公司或其供应商所有。本“软件”具有版权,并受到美国和其它国家法律以及国际条约条款的保护。您不得从本“软件”上删除任何版权通知。XXXX 公司可随时改变本“软件”或其中述及的项目,恕不另行通知,但是,XXXX 公司没有义务支持本“软件”或对其进行更新。除非另有明确规定,XXXX 公司未以任何明确的或隐含的方式授予贵方任何其拥有的专利、版权、商标或其它知识产权方面的权利。只有在接收者同意完全接受这些条款的约束且贵方不保留“软件”副本的前提下,您才能转让本“软件”。");
                    sw.WriteLine("有限的媒体品质保证:如果本“软件”由 XXXX 公司以实物媒体递交,XXXX 公司保证自该媒体交递之日起九十 (90) 天内没有材料和实物上的缺陷。如果出现这样的缺陷,请将有缺陷的媒体退还 XXXX 公司进行更换,XXXX 公司也可能选择以另外的途径递交该“软件”。");
                    sw.WriteLine("不包括任何其它保证:除上述保证之外,本“软件”是按其“现状”而提供的,没有任何其它明确或隐含的保证,包括适销性、非侵权性或适用于某一特定用途的保证。XXXX 公司对本“软件”中包括的任何信息、文字、图形、链接或其它项目的精确性或完整性不作担保,也不承担责任。");
                    sw.WriteLine("有限责任:对于因使用或无法使用本“软件”所造成的任何损失(包括但并不限于利润损失、业务中断或信息丢失等),无论在何种情况下,即使 XXXX 公司已被事先通知可能会出现这样的损失,XXXX 公司及其供应商均不承担任何责任。有些法律管区禁止排除或限制隐含保证或后果性、事故性损失的责任,因此,上述限制可能对您不适用。随法律管区的不同,您还可能拥有其它法定权利。");
                    sw.WriteLine("本协议的终止:如果您违反“协议”的条款,XXXX 公司则可随时终止本“协议”。协议终止时,您应该立即销毁本“软件”或将“软件”的所有副本退还 XXXX 公司。");
                    sw.WriteLine("适用的法律:因本“协议”而产生的索赔将接受加利福尼亚州法律的管辖,但不受其法律冲突原则的约束。本“协议”将不受《联合国国际货物销售合同公约》的约束。您不得违反适用的出口法规而将本“软件”出口国外。XXXX 公司不承担任何其它协议的责任,除非这些协议为书面协议并经过 XXXX 公司的授权代表签署。");
                    sw.WriteLine("政府机构有限的权利:本“软件”是以“有限的权利”而提供的。政府机构使用、复制或透露本“软件”应受到 FAR52.227-14 和 DFAR252.227-7013 及其承续法的限制。政府机构使用本“软件”即表明其承认 XXXX 公司对“软件”的所有权权利。承包商或制造商为:XXXX Corporation, 2200 Mission College Blvd., Santa Clara, CA 95052 USA。");
                    sw.WriteLine("");
                    sw.WriteLine("附件一");
                    sw.WriteLine("XXXX 软件许可协议(最终、单个用户)");
                    sw.WriteLine("重要通知 - 在复制、安装或使用之前,请先仔细阅读。");
                    sw.WriteLine("只有在仔细阅读下面的条款之后,方可使用或装载本软件及相关材料(总称为“软件”)。装载或使用本“软件”,即表明您同意本“协议”的条款。如果您不同意本“协议”的条款,请不要安装或使用本“软件”。");
                    sw.WriteLine("许可:您可将本“软件”复制到一台计算机上供非商业性的个人使用,并可复制一份本“软件”的备份。上述使用和备份受以下条款的约束:");
                    sw.WriteLine("1. 这一“软件”仅许可用来与 XXXX 组件产品结合使用。本“协议”不授予将此“软件”和其它非 XXXX 组件产品结合使用的许可。");
                    sw.WriteLine("2. 除本“协议”中规定者之外,您不得复制、改变、出租、出售、分发或转让本“软件”的任何部分,您并且同意防止他人未经授权而复制本“软件”。");
                    sw.WriteLine("3. 您不得分解编码、拆散本“软件”或对其进行逆向工程设计。");
                    sw.WriteLine("4. 您不得分让或允许同时有一个以上的用户使用本“软件”。");
                    sw.WriteLine("5. 本“软件”可能含有第三方供应商的软件或其它财产,其中有些可能已经在随附的“license.txt”或其它文本或文件中注明并根据这些文件而获得许可。");
                    sw.WriteLine("软件的所有权和版权:本“软件”所有副本的所有权归 XXXX 公司或其供应商所有。本“软件”具有版权,并受到美国和其它国家法律以及国际条约条款的保护。您不得从本“软件”上删除任何版权通知。XXXX 公司可随时改变本“软件”或其中述及的项目,恕不另行通知,但是,XXXX 公司没有义务支持本“软件”或对其进行更新。除非另有明确规定,XXXX 公司未以任何明确的或隐含的方式授予贵方任何其拥有的专利、版权、商标或其它知识产权方面的权利。只有在接收者同意完全接受这些条款的约束且贵方不保留“软件”副本的前提下,您才能转让本“软件”。");
                    sw.WriteLine("有限的媒体品质保证:如果本“软件”由 XXXX 公司以实物媒体交递,XXXX 公司保证自该媒体交递之日起九十 (90) 天内没有材料和实物上的缺陷。如果出现这样的缺陷,请将有缺陷的媒体退还 XXXX 公司进行更换,XXXX 公司也可能选择以另外的途径交递该“软件”。");
                    sw.WriteLine("不包括任何其它保证:除上述保证之外,本“软件”是按其“现状”而提供的,没有任何其它明确或隐含的保证,包括适销性、非侵权性或适用于某一特定用途的保证。XXXX 公司对本“软件”中包括的任何信息、文字、图形、链接或其它项目的精确性或完整性不作担保,也不承担责任。");
                    sw.WriteLine("有限责任:对于因使用或无法使用本“软件”所造成的任何损失(包括但并不限于利润损失、业务中断或信息丢失等),无论在何种情况下,即使 XXXX 公司已被事先通知可能会出现这样的损失,XXXX 公司及其供应商均不承担任何责任。有些法律管区禁止排除或限制隐含保证或后果性、事故性损失的责任,因此,上述限制可能对您不适用。随法律管区的不同,您还可能拥有其它法定权利。");
                    sw.WriteLine("本协议的终止:如果您违反本“协议”的条款,XXXX 公司则可随时终止本“协议”。“协议”终止时,您应该立即销毁本“软件”或将“软件”的所有副本退还 XXXX 公司。");
                    sw.WriteLine("适用的法律:因本“协议”而产生的索赔将中华人民共和国法律的管辖,但不受其法律冲突原则的约束。本“协议”将不受《联合国国际货物销售合同公约》的约束。您不得违反适用的出口法规而将本“软件”出口国外。XXXX 公司不承担任何其它协议的责任,除非这些协议为书面协议并经过 XXXX 公司的授权代表签署。");
                    sw.WriteLine("政府机构有限的权利:本“软件”是以“有限的权利”而提供的。政府机构使用、复制或透露本“软件”受到 FAR52.227-14 和 DFAR252.227-7013 及其承续法的限制。政府机构使用本“软件”即表明其承认 XXXX 公司对“软件”的所有权权利。承包商或制造商为:XXXX Corporation, 2200 Mission College Blvd., Santa Clara, CA 95052 USA。SLAOEMISV1/RBK/01-21-00");
                    sw.WriteLine("INCREMENT jackDataManagerbase ugslmd 7.0 15caugc2013 100 SUPERSEDE");
                    sw.WriteLine("DUPDataManagerGROUP=UHD ISSUED=10caprc2013 ck=197 SIGN=13E6 6CA8 B322");
                    sw.WriteLine("vwViht2lF5ylrm86DcwjI2bO/T7msUGMdslcgEH+EqY=cMKidern7PkegIelOLyYycxcA");
                    sw.WriteLine("");
                    sw.WriteLine(date1changed);
                    sw.WriteLine("");
                    sw.WriteLine(date2changed);
                    sw.WriteLine("0CED 1E9E 40C4 F4C5 11EF 2257 024B 2F89 F32F C5E0 A8B5");
                    sw.WriteLine("404E F48C A0E0");
                    sw.WriteLine("INCREMENT jackDataManagermocap ugslmd 7.0 15caugc2013 100 SUPERSEDE");
                    sw.WriteLine("DUPDataManagerGROUP=UHD ISSUED=10caprc2013 ck=213 SIGN=0E14 0B08 72EE");
                    sw.WriteLine("vwVihs2oF6ylpm8mDcwAI2bO/T7qsUGMdGupgEH+EvY=cqGcMKlk3gvcOIlOLyllYycA");
                    sw.WriteLine("");
                    sw.WriteLine(date1changed);
                    sw.WriteLine("");
                    sw.WriteLine(date2changed);
                    sw.WriteLine("17C0 A842 8C45 589D 0DFE 4AD5 BC98 5477 6119 14BE 44A6 43BC");
                    sw.WriteLine("F203 A4D9 E7B8");
                    sw.WriteLine("INCREMENT jackDataManageropt ugslmd 7.0 15caugc2013 100 SUPERSEDE DUPDataManagerGROUP=UHD");
                    sw.WriteLine("ISSUED=10caprc2013 ck=153 SIGN=1A92 02DD 4141 8368 E567 8A7F");
                    sw.WriteLine("vwVtht2oF5ydrmsmDcwAj2bO/T7qbUGMdGuqgEH+EgY=7PH7k3OIfhlOjhdfPLyYycA");
                    sw.WriteLine("");
                    sw.WriteLine(date1changed);
                    sw.WriteLine("");
                    sw.WriteLine(date2changed);
                    sw.WriteLine("1126 FC56 F296 8EA7 E581 3F14 9010 A358 842F A95C DF78 1F41");
                    sw.WriteLine("INCREMENT jackDataManagertat ugslmd 7.0 15caugc2013 100 SUPERSEDE DUPDataManagerGROUP=UHD");
                    sw.WriteLine("ISSUED=10caprc2013 ck=246 SIGN=0530 5C25 E534 748D 8C6D 18B4");
                    sw.WriteLine(text + "7PH7k3OI46lOjhdffsPLyYycA");
                    sw.WriteLine("");
                    sw.WriteLine(date1changed);
                    sw.WriteLine("");
                    sw.WriteLine(date2changed);
                    sw.WriteLine("F771 BEE5 2B9B B401 9B68 7CAD AC16 748F 366F 5536 E8BF 7067");
                    sw.WriteLine("INCREMENT jackDataManagertoolkit ugslmd 7.0 15caugc2013 100 SUPERSEDE");
                    sw.WriteLine("DUPDataManagerGROUP=UHD ISSUED=10caprc2013 ck=146 SIGN=02F5 0DD5 E558");
                    sw.WriteLine("vwViht0oF5ylrw8mDcwAI2zO/T7fsUHMdGuzgEH-EqY=l7k3OIlshhOnmjkgPLyYycA");
                    sw.WriteLine("");
                    sw.WriteLine(date1changed);
                    sw.WriteLine("");
                    sw.WriteLine(date2changed);
                    sw.WriteLine("1F86 4E64 35B5 0A4E 597E 78B0 0A28 A0C9 644B E5D8 1F80 94FA");
                    sw.WriteLine("DFFA A6AE BEF4");
                    sw.WriteLine("FEATURE serverDataManagerid ugslmd 7.0 permanent 1 VENDORDataManagerSTRING=IN04102013 c");
                    sw.WriteLine("SIEMENS PLM SOFTWA userDataManagerinfo=3TLFWAM3CP ISSUER=SIEMENS ck=175");
                    sw.WriteLine("SIGN=116C 3E2A 6874 5E61 97B9 9942 5EED 2661 A20C 690E F60D");
                    sw.WriteLine("F803 C42E 47E9 D6E1 0005 7F17 3AB3 5EA7 68FD 2D8C 81AD 171D");
                }

                Console.ReadLine();

            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            System.Management.ManagementClass mc = new ManagementClass("win32_processor");
            ManagementObjectCollection moc = mc.GetInstances();
            string processorid = "";
            string testext = "";
            foreach (ManagementObject mo in moc)
            {
                processorid = mo["processorid"].ToString();
                //MessageBox.Show(mo["processorid"].ToString());


                using (FileStream fs = new FileStream("License.lic", FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    int iXH = 0;
                    using (StreamReader sr = new StreamReader(fs))
                    {
                        string line = sr.ReadLine();

                        while ((line = sr.ReadLine()) != null)
                        {
                            //这里的Line就是您要的的数据了
                            iXH++;//计数,总共几行
                            line = sr.ReadLine();
                            if (!string.IsNullOrEmpty(line))
                            {
                                line = line.Trim();

                                if (line.StartsWith("ISSUED=10caprc2013 ck=246 SIGN=0530 5C25 E534 748D 8C6D 18B4"))
                                {
                                    line = sr.ReadLine().Substring(0, 44);
                                    string text = decrption(line, key.Substring(0, 32), iv.Substring(0, 16));
                                    this.textBox6.Text = text;

                                    if (text == this.textBox4.Text)
                                    {
                                        line = sr.ReadLine();
                                        line = sr.ReadLine();

                                        string date001 = decrption(line, key.Substring(0, 32), iv.Substring(0, 16));
                                        //MessageBox.Show(date001);
                                        line = sr.ReadLine();
                                        line = sr.ReadLine();
                                        string date002 = decrption(line, key.Substring(0, 32), iv.Substring(0, 16));
                                        //MessageBox.Show(date002);
                                        System.DateTime currentTime = new System.DateTime();
                                        currentTime = System.DateTime.Now;
                                        string[] s1 = date001.Split(new char[] { '-' });
                                        string[] s2 = date002.Split(new char[] { '-' });
                                        int date01year = Int32.Parse(s1[0]);
                                        int date02year = Int32.Parse(s2[0]);
                                        int date01month = Int32.Parse(s1[1]);
                                        int date02month = Int32.Parse(s2[1]);
                                        int date01day = Int32.Parse(s1[2]);
                                        int date02day = Int32.Parse(s2[2]);
                                        DateTime date01 = new DateTime(date01year, date01month, date01day);
                                        DateTime date02 = new DateTime(date02year, date02month, date02day);

                                        if (IsInTimeInterval(currentTime, date01, date02) == true)
                                        {
                                            MessageBox.Show("许可证文件正确,且在授权期限内");
                                        }
                                        else
                                        {
                                            MessageBox.Show("许可证文件已失时效");
                                        }
                                    }
                                    else
                                    { MessageBox.Show("许可证文件非法!", "提示"); }
                                }
                            }
                        }
                    }
                    Console.ReadLine();
                }
            }
        }
    }
}

工程运行生成可执行文件:


 

1.2License使用

启动License生成器后,看到如下界面,点击 生成(生成器授权.lic)按钮

稍等片刻,本机cpu-id 和 许可证文件源码 就会生成出来,然后按照图片操作,把cpu-id复制到下面待生成cpu-id框内。


复制好后,选择license的授权日期。 



选择完成后,点击 生成(License.lic)按钮,弹出如下提示框,说明生成文件完成且正确。


 

二、VS创建类库.Net Framework应用,开发生成.dll类库工程

Dll工程代码

//---------------------------
//@Author GarFey
// @date 20190612
// @version 1.0
//---------------------------
using System;
using System.IO;
using System.Security.Cryptography;

namespace License
{
    public class LicenesCheck
    {
        private string key = "GarFey201906101620MA124EAAfeTud00CtDpoQwnvmmStsitSwtsitloxigpxnDPPdSod";
        private string iv = "LeadVR20190610GarFeyCreatPrivatekeyQe90QPlcMA124EA";

        ///
        /// 
        ///
        ///
        ///
        /// 0 许可证文件正确,且在授权期限内
        /// 1 没有许可证文件
        /// 2 许可证文件已失时效
        /// 3 许可证文件非法!
        ///
        public int Verification(string licPath)
        {
            try
            {
                string processorid = GetProcessorId();
                string path = licPath + "/License/License.lic";
                //WriteLog.Log("licpath == "+ path);
                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    int iXH = 0;
                    using (StreamReader sr = new StreamReader(fs))
                    {
                        string line = sr.ReadLine();
                        while ((line = sr.ReadLine()) != null)
                        {
                            iXH++;//计数,总共几行
                            line = sr.ReadLine();
                            if (!string.IsNullOrEmpty(line))
                            {
                                line = line.Trim();

                                if (line.StartsWith("ISSUED=10caprc2013 ck=246 SIGN=0530 5C25 E534 748D 8C6D 18B4"))
                                {
                                    line = sr.ReadLine().Substring(0, 44);
                                    //WriteLog.Log("line "+ line);
                                    string text = decrption(line, key.Substring(0, 32), iv.Substring(0, 16));
                                    //WriteLog.Log("decrption text " + text);
                                    if (text == processorid)
                                    {
                                        line = sr.ReadLine();
                                        line = sr.ReadLine();
                                        string date001 = decrption(line, key.Substring(0, 32), iv.Substring(0, 16));
                                        line = sr.ReadLine();
                                        line = sr.ReadLine();
                                        string date002 = decrption(line, key.Substring(0, 32), iv.Substring(0, 16));
                                        System.DateTime currentTime = new System.DateTime();
                                        currentTime = System.DateTime.Now;
                                        string[] s1 = date001.Split(new char[] { '-' });
                                        string[] s2 = date002.Split(new char[] { '-' });
                                        int date01year = Int32.Parse(s1[0]);
                                        int date02year = Int32.Parse(s2[0]);
                                        int date01month = Int32.Parse(s1[1]);
                                        int date02month = Int32.Parse(s2[1]);
                                        int date01day = Int32.Parse(s1[2]);
                                        int date02day = Int32.Parse(s2[2]);
                                        DateTime date01 = new DateTime(date01year, date01month, date01day);
                                        DateTime date02 = new DateTime(date02year, date02month, date02day);

                                        if (IsInTimeInterval(currentTime, date01, date02) == true)
                                        {
                                            return 0;//许可证文件正确,且在授权期限内
                                        }
                                        else
                                        {
                                            return 2;//许可证文件已失时效
                                        }
                                    }
                                    else
                                    {
                                        return 3;//许可证文件非法!

                                    }

                                }
                            }
                        }

                    }

                    Console.ReadLine();

                }
            }
            catch(Exception e)
            {
                string errorStr = e.ToString();
                //WriteLog.LogExcption("Exception:: License 获取警告" + errorStr);
                if (errorStr.StartsWith("System.Security.Cryptography.CryptographicException: Invalid input block size."))
                {
                    return 3;//许可证文件非法!
                }
                return 1; //没有许可证文件
            }
            return 4; 
        }
        private bool IsInTimeInterval(DateTime time, DateTime startTime, DateTime endTime)
        {
            //判断时间段开始时间是否小于时间段结束时间,如果不是就交换
            if (startTime > endTime)
            {
                DateTime tempTime = startTime;
                startTime = endTime;
                endTime = tempTime;
            }

            //获取以公元元年元旦日时间为基础的新判断时间
            DateTime newTime = new DateTime();
            newTime = time;

            //获取以公元元年元旦日时间为基础的区间开始时间
            DateTime newStartTime = new DateTime();
            newStartTime = startTime;

            //获取以公元元年元旦日时间为基础的区间结束时间
            DateTime newEndTime = new DateTime();
            newEndTime = endTime;

            if (newTime >= newStartTime && newTime < newEndTime)
            {
                return true;
            }
            return false;
        }
        public string encrption(string input, string key, string iv)
        {
            MemoryStream msEncrypt = null;
            RijndaelManaged aesAlg = null;

            string sresult = string.Empty;

            try
            {
                byte[] keys = System.Text.Encoding.UTF8.GetBytes(key);
                byte[] ivs = System.Text.Encoding.UTF8.GetBytes(iv);
                aesAlg = new RijndaelManaged();
                aesAlg.Key = keys;
                aesAlg.IV = ivs;

                ICryptoTransform ict = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                msEncrypt = new MemoryStream();

                using (CryptoStream cts = new CryptoStream(msEncrypt, ict, CryptoStreamMode.Write))
                {
                    using (StreamWriter sw = new StreamWriter(cts))
                    {
                        sw.Write(input);
                    }
                }

            }
            finally
            {
                if (aesAlg != null)
                {
                    aesAlg.Clear();
                }
            }

            if (msEncrypt != null)
            {
                byte[] content = msEncrypt.ToArray();

                sresult = Convert.ToBase64String(content);
            }

            return sresult;
        }

        public string decrption(string input, string key, string iv)
        {
            string sresult = string.Empty;

            byte[] keys = System.Text.Encoding.UTF8.GetBytes(key);
            byte[] ivs = System.Text.Encoding.UTF8.GetBytes(iv);

            byte[] inputbytes = Convert.FromBase64String(input);

            RijndaelManaged rm = null;

            try
            {
                rm = new RijndaelManaged();
                rm.Key = keys;
                rm.IV = ivs;

                ICryptoTransform ict = rm.CreateDecryptor(rm.Key, rm.IV);

                using (MemoryStream ms = new MemoryStream(inputbytes))
                {
                    using (CryptoStream cs = new CryptoStream(ms, ict, CryptoStreamMode.Read))
                    {
                        using (StreamReader sr = new StreamReader(cs))
                        {
                            sresult = sr.ReadToEnd();
                        }
                    }
                }
            }
            finally
            {
                if (rm != null)
                {
                    rm.Clear();
                }
            }
            return sresult;
        }
        ///
        /// 获取cpuid
        ///
        ///
        public string GetProcessorId()
        {
            string processorid = "";
            string outstr = RunCmdNoErr("wmic", " CPU get ProcessorID");
            string cpuId = outstr.Replace("ProcessorId", "");
            processorid = cpuId.Trim();
            return processorid;
        }

        ///
        /// 构建Process对象,并执行
        ///
        /// 命令
        /// 命令的参数
        /// 工作目录
        /// Process对象
        private System.Diagnostics.Process CreateCmdProcess(string cmd, string args, string workdir = null)
        {
            var pStartInfo = new System.Diagnostics.ProcessStartInfo(cmd);
            pStartInfo.Arguments = args;
            pStartInfo.CreateNoWindow = false;
            pStartInfo.UseShellExecute = false;
            pStartInfo.RedirectStandardError = true;
            pStartInfo.RedirectStandardInput = true;
            pStartInfo.RedirectStandardOutput = true;
            pStartInfo.StandardErrorEncoding = System.Text.UTF8Encoding.UTF8;
            pStartInfo.StandardOutputEncoding = System.Text.UTF8Encoding.UTF8;
            if (!string.IsNullOrEmpty(workdir))
                pStartInfo.WorkingDirectory = workdir;
            return System.Diagnostics.Process.Start(pStartInfo);
        }

        ///
        /// 运行命令,不返回stderr版本
        ///
        /// 命令
        /// 命令的参数
        /// 工作目录
        /// 命令的stdout输出
        private string RunCmdNoErr(string cmd, string args, string workingDri = "")
        {
            var p = CreateCmdProcess(cmd, args, workingDri);
            var res = p.StandardOutput.ReadToEnd();
            p.Close();
            return res;
        }
    }
}

工程运行后,得到dll文件:

三、在Unity中引用该dll,进行逻辑开发

Unity端代码:

//-----------------------------------------------
// @Author GarFey
// @date 20190612
// @version 1.0
//-----------------------------------------------
using UnityEngine;
using License;
using System;
using MsgBoxBase = System.Windows.Forms.MessageBox; //引用命名空间下消息类
using WinForms = System.Windows.Forms;              //引用命名空间

public class Main : MonoBehaviour {

    // Use this for initialization
    void Start () {
        licenseCheck();
    }
    void licenseCheck()
    {
        LicenesCheck lc = new LicenesCheck();
        string licPath = Application.dataPath;

        int isLicOk = lc.Verification(licPath);
        Debug.Log("" + isLicOk);

        switch (isLicOk)
        {
            /// 0 许可证文件正确,且在授权期限内
            case 0:
Debug.Log("许可证文件正确,且在授权期限内");
                break;
            /// 1 没有许可证文件
            case 1:
                switch (MsgBoxBase.Show("没有找到许可证文件!", "提示", WinForms.MessageBoxButtons.OK, WinForms.MessageBoxIcon.Question))
                {
                    case WinForms.DialogResult.OK:
                    case WinForms.DialogResult.Cancel:
                        print("quit");
                        quit();
                        break;
                }
                break;
            /// 2 许可证文件已失时效
            case 2:
                switch (MsgBoxBase.Show("许可证文件已失时效!", "提示", WinForms.MessageBoxButtons.OK, WinForms.MessageBoxIcon.Warning))
                {
                    case WinForms.DialogResult.OK:
                    case WinForms.DialogResult.Cancel:
                        print("quit");
                        quit();
                        break;
                }
                break;
                break;
            /// 3 许可证文件非法!
            case 3:
                switch (MsgBoxBase.Show("许可证文件非法!", "提示", WinForms.MessageBoxButtons.OK, WinForms.MessageBoxIcon.Error))
                {
                    case WinForms.DialogResult.OK:
                    case WinForms.DialogResult.Cancel:
                        print("quit");
                        quit();
                        break;
                }
                break;
            default:
                quit();
                break;
        }
    }

    void quit()
    {
        Application.Quit();
    }
}

运行结果展示:

License验证成功,且许可证文件正确 

没有License许可证文件

License许可证文件过期



非法(不正确)的LIcense许可证文件
 


注意:

到这里如果你编译时,有错误,确认下你是否有导入 System.Windows.Forms.dll。

具体的Unity调用Windows弹框,博主有具体讲解。

  • 1
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GarFe-Liu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值