如何对Unity工程进行加密

来源:互联网 发布:java可以做前端吗 编辑:程序博客网 时间:2024/06/15 03:48
如何对unity工程进行加密

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

第一步:生成License文件


1. 制作简单的生成License文件的Winform界面


Liscense生成界面

2. 编写License文件生成器代码


//-----------------------------------------////      CuteEditorLic V1.0////-----------------------------------------using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.IO;using System.Security.Cryptography;using System.Diagnostics;using System.Management;using System.Globalization;namespace CuteEditorLic{    public partial class 许可证文件生成器 : Form    {        private string key = "alskdfsakjsdikfhkjgfhjmvnnxfksajkwke135466dvfdsgjkfdhgskjsagbbkhfdgn";        private string iv = "qjhsqjhwencgfuyuyggkxgzzmgfmhgjhkjhkmjfjhfnsks4464fsdgffdhghgsdf";        public 许可证文件生成器()        {            InitializeComponent();        }        private void Form1_Load(object sender, EventArgs e)        {        }        /// <summary>        /// 输出Lic授权文件        /// </summary>        /// <param name="FilePath">输出文件路径</param>                      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);                //byte[] keys = new byte[] { 70, 0x35, 50, 0x42, 0x31, 0x38, 0x36, 70 };                //byte[] ivs = new byte[] { 70, 0x35, 50, 0x42, 0x31, 0x38, 0x36, 70 };                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[] keys = new byte[] { 70, 0x35, 50, 0x42, 0x31, 0x38, 0x36, 70 };            //byte[] ivs = new byte[] { 70, 0x35, 50, 0x42, 0x31, 0x38, 0x36, 70 };            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 void button1_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());            }            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 button2_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("许可证文件正确");            }            }        }        private void Form1_Load_1(object sender, EventArgs e)        {                    }        private void button7_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 = date01.ToString("d");            string date2 = date02.ToString("d");            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 button6_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))                    {                        // 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();                        string line = sr.ReadLine();                        //MessageBox.Show(line);                        //while (!sr.EndOfStream)                        //{                        //    if (!string.IsNullOrEmpty(line))                        //    {                        //        line = line.Trim();                        //        if (line.StartsWith("SoftWare_ID"))                        //        {                        //            MessageBox.Show(line);                        //        }                        //    }                        //    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();                }                //string text = decrption(this.textBox5.Text, key.Substring(0, 32), iv.Substring(0, 16));                //this.textBox6.Text = text;                //if (text == this.textBox4.Text)                //{                //    MessageBox.Show("许可证文件正确");                //}            }        }        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;            //newTime = newTime.AddHours(time.Hour);            //newTime = newTime.AddMinutes(time.Minute);            //newTime = newTime.AddSeconds(time.Second);            //获取以公元元年元旦日时间为基础的区间开始时间            DateTime newStartTime = new DateTime();            newStartTime = startTime;            //newStartTime = newStartTime.AddHours(startTime.Hour);            //newStartTime = newStartTime.AddMinutes(startTime.Minute);            //newStartTime = newStartTime.AddSeconds(startTime.Second);            //获取以公元元年元旦日时间为基础的区间结束时间            DateTime newEndTime = new DateTime();            newEndTime = endTime;            //if (startTime.Hour > endTime.Hour)            //{            //    newEndTime = newEndTime.AddDays(1);            //}            //newEndTime = newEndTime.AddHours(endTime.Hour);            //newEndTime = newEndTime.AddMinutes(endTime.Minute);            //newEndTime = newEndTime.AddSeconds(endTime.Second);            if (newTime >= newStartTime && newTime < newEndTime)            {                return true;            }            return false;        }    }    }
Liscense生成器主界面代码


using System;using System.Collections.Generic;using System.Windows.Forms;namespace CuteEditorLic{    static class Program    {        /// <summary>        /// 应用程序的主入口点。        /// </summary>        [STAThread]        static void Main()        {            Application.EnableVisualStyles();            Application.SetCompatibleTextRenderingDefault(false);            Application.Run(new 许可证文件生成器());        }    }}
主程序入口代码


3. 执行代码生成Liscense文件



点击生成按钮获取本机CPU-ID



获取本机CPU-ID




将本机CPU-ID粘贴至待生成CPU-ID框中




选择License授权时限




生成许可证文件




验证许可证文件

第二步:生成获取ProcessorID的C++ DLL


#ifndef __Copyright_H__#define __Copyright_H__#include <Windows.h>#include <stdio.h>#include <tchar.h>#include <string>using namespace std;#ifdef Copyright_EXPORTS#define Copyright_EXPORTS __declspec(dllexport)#else#define Copyright_EXPORTS _declspec(dllimport)#endifextern"C" Copyright_EXPORTS void GetProcessor(INT32 *a, INT32 *b);#endif
头文件代码


#include "Copyright.h"#if _MSC_VER >=1400#include <intrin.h>// 所有Intrinsics函数#endifchar szBuf[64];INT32 dwBuf[4];#if defined(_WIN64)// 64位下不支持内联汇编. 应使用__cpuid、__cpuidex等Intrinsics函数。#else#if _MSC_VER < 1600// VS2010. 据说VC2008 SP1之后才支持__cpuidexvoid __cpuidex(INT32 CPUInfo[4], INT32 InfoType, INT32 ECXValue){if (NULL == CPUInfo)return;_asm{// load. 读取参数到寄存器mov edi, CPUInfo;// 准备用edi寻址CPUInfomov eax, InfoType;mov ecx, ECXValue;// CPUIDcpuid;// save. 将寄存器保存到CPUInfomov[edi], eax;mov[edi + 4], ebx;mov[edi + 8], ecx;mov[edi + 12], edx;}}#endif// #if _MSC_VER < 1600// VS2010. 据说VC2008 SP1之后才支持__cpuidex#if _MSC_VER < 1400// VC2005才支持__cpuidvoid __cpuid(INT32 CPUInfo[4], INT32 InfoType){__cpuidex(CPUInfo, InfoType, 0);}#endif// #if _MSC_VER < 1400// VC2005才支持__cpuid#endif// #if defined(_WIN64)void GetProcessor(INT32 *a, INT32 *b){__cpuidex(dwBuf, 1, 1);char szTmp[33] = { NULL };*a = dwBuf[3];*b = dwBuf[0];}

CPP代码



第三步:生成验证许可证文件的C# DLL


using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Text;using System.IO;using System.Security.Cryptography;using System.Diagnostics;using System.Globalization;namespace Cryption{    public class MyClass    {        private string key = "alskdfsakjsdikfhkjgfhjmvnnxfksajkwke135466dvfdsgjkfdhgskjsagbbkhfdgn";        private string iv = "qjhsqjhwencgfuyuyggkxgzzmgfmhgjhkjhkmjfjhfnsks4464fsdgffdhghgsdf";        public int  Verification(string processorid)        {                try                {                    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)                            {                                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));                                        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                {                    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;        }    }}
C#验证代码


第四步:在Unity中使用两个DLL





Unity中加载dll


第五步:测试结果


using UnityEngine;using System.Collections;using System;using System.Collections.Generic;using System.ComponentModel;using System.Text;using System.IO;using System.Security.Cryptography;using System.Globalization;using System.Runtime.InteropServices;using Cryption;public class test : MonoBehaviour {     [DllImport("Copyright")]    private static extern void GetProcessor(out Int32 a, out Int32 b);void Start () {        MyClass class1 = new MyClass();        Int32 a;        Int32 b;        GetProcessor(out a, out b);        string ssss = a.ToString("X8");        string bbbbb = b.ToString("X8");        string cc = ssss + bbbbb;        Debug.Log(class1.Verification(cc));}void Onable()    {            }// Update is called once per framevoid Update () {}}
测试结果代码



测试结果代码

阅读全文
0 0
原创粉丝点击