Licensing实例(二)

    技术2022-05-11  79

    接上一篇:Licensing实例(一)      /// <summary>    /// 加密许可证提供者    /// </summary>      public   class  EncryptedLicenseProvider : LicenseProvider     {        private static byte[] _designSignature;        private static byte[] _desIV = new byte[] 173631981771144221161 };        private static byte[] _desKey = new byte[] 146215616118237179194 };        private static string _rsaParameters;        private static byte[] _runtimeSignature;        private static EncryptedLicense _systemLicense;        private const string _systemParameters = "";        private const int keyLength = 7;        public EncryptedLicenseProvider()        {        }        /// <summary>        /// 数组匹配        /// </summary>        /// <param name="a1"></param>        /// <param name="a2"></param>        /// <returns></returns>        private static bool ArrayEqual(byte[] a1, byte[] a2)        {            if (a1 != a2)            {                if ((a1 == null|| (a2 == null))                {                    return false;                }                if (a1.Length != a2.Length)                {                    return false;                }                for (int num1 = 0; num1 < a1.Length; num1++)                {                    if (a1[num1] != a2[num1])                    {                        return false;                    }                }            }            return true;        }        /// <summary>        /// 序列尺寸        /// </summary>        /// <param name="length"></param>        /// <returns></returns>        private static int ArraySize(int length)        {            return length;        }        /// <summary>        /// 提取许可证信息        /// </summary>        /// <param name="licenseKey">许可证键值</param>        /// <param name="password">密码</param>        /// <returns></returns>        internal EncryptedLicense ExtractLicense(string licenseKey, string password)        {            try            {                //从哈希转到byte                byte[] buffer1 = EncryptedLicenseProvider.FromHex(licenseKey);                byte[] buffer2 = new byte[] 62126142556816519363 };                //获取公钥标识                byte[] buffer3 = Assembly.GetExecutingAssembly().GetName().GetPublicKeyToken();                if (!EncryptedLicenseProvider.ArrayEqual(buffer3, buffer2))                {                    EncryptedLicenseProvider._desKey.CopyTo(buffer2, 0);                }                DESCryptoServiceProvider provider1 = new DESCryptoServiceProvider();                provider1.Key = EncryptedLicenseProvider._desKey;                provider1.IV = EncryptedLicenseProvider._desIV;                byte[] buffer4 = provider1.CreateDecryptor().TransformFinalBlock(buffer1, 0, buffer1.Length);                byte[] buffer5 = new byte[EncryptedLicenseProvider.ArraySize(8)];                byte[] buffer6 = new byte[EncryptedLicenseProvider.ArraySize(buffer4.Length - 7)];                Array.Copy(buffer4, 0, buffer5, 07);                Array.Copy(buffer4, 7, buffer6, 0, buffer6.Length);                byte[] buffer7 = EncryptedLicenseProvider.GetEncryptionKey(password);                if (!EncryptedLicenseProvider.ArrayEqual(buffer5, buffer7))                {                    return null;                }                provider1.IV = buffer5;                byte[] buffer8 = provider1.CreateDecryptor().TransformFinalBlock(buffer6, 0, buffer6.Length);                byte[] buffer9 = new byte[EncryptedLicenseProvider.ArraySize(buffer8.Length - 2)];                Array.Copy(buffer8, 2, buffer9, 0, buffer9.Length);                ushort num1 = BitConverter.ToUInt16(buffer8, 0);                string text1 = Encoding.UTF8.GetString(buffer9);                return new EncryptedLicense(licenseKey, num1, text1);            }            catch            {                return null;            }        }        /// <summary>        /// 从哈希转到byte        /// </summary>        /// <param name="hex"></param>        /// <returns></returns>        private static byte[] FromHex(string hex)        {            string text1 = EncryptedLicenseProvider.Strip(hex, "  -");            if ((text1 == null|| ((text1.Length % 2!= 0))            {                throw new FormatException("Invalid hexadecimal string");            }            byte[] buffer1 = new byte[EncryptedLicenseProvider.ArraySize(text1.Length / 2)];            int num1 = 0;            for (int num2 = 0; num1 < text1.Length; num2++)            {                string text2 = text1.Substring(num1, 2);                buffer1[num2] = byte.Parse(text2, NumberStyles.HexNumber);                num1 += 2;            }            return buffer1;        }        /// <summary>        /// 生成键值        /// </summary>        /// <param name="password">密码</param>        /// <param name="productInfo">产品信息</param>        /// <param name="serialNo">序列号</param>        /// <returns></returns>        public virtual string GenerateKey(string password, string productInfo, ushort serialNo)        {            byte[] buffer1 = new byte[] 0x3e0x7e0x8e0x370x440xa50xc10x3f };            byte[] buffer2 = EncryptedLicenseProvider.GetEncryptionKey(password);            byte[] buffer3 = Encoding.UTF8.GetBytes(productInfo);            byte[] buffer4 = BitConverter.GetBytes(serialNo);            byte[] buffer5 = new byte[EncryptedLicenseProvider.ArraySize(buffer3.Length + buffer4.Length)];            byte[] buffer6 = Assembly.GetExecutingAssembly().GetName().GetPublicKeyToken();            buffer4.CopyTo(buffer5, 0);            buffer3.CopyTo(buffer5, 2);            if (EncryptedLicenseProvider.SystemLicense == null)            {                if (password != "TEST")                {                    throw new LicenseException(typeof(EncryptedLicenseProvider), this"The only allowable password in evaluation mode is 'TEST'");                }                if ((serialNo < 0|| (serialNo > 1))                {                    throw new LicenseException(typeof(EncryptedLicenseProvider), this"The only allowable serial numbers in evaluation mode are '0' or '1'");                }            }            if (!EncryptedLicenseProvider.ArrayEqual(buffer6, buffer1))            {                EncryptedLicenseProvider._desKey.CopyTo(buffer2, 0);            }            DESCryptoServiceProvider provider1 = new DESCryptoServiceProvider();            provider1.Key = EncryptedLicenseProvider._desKey;            provider1.IV = buffer2;            byte[] buffer7 = provider1.CreateEncryptor().TransformFinalBlock(buffer5, 0, buffer5.Length);            byte[] buffer8 = new byte[EncryptedLicenseProvider.ArraySize(7 + buffer7.Length)];            buffer2.CopyTo(buffer8, 0);            buffer7.CopyTo(buffer8, 7);            provider1.IV = EncryptedLicenseProvider._desIV;            byte[] buffer9 = provider1.CreateEncryptor().TransformFinalBlock(buffer8, 0, buffer8.Length);            return EncryptedLicenseProvider.ToHex(buffer9);        }        /// <summary>        /// 生成许可证参数        /// </summary>        /// <param name="password">密码</param>        /// <returns></returns>        public string GenerateLicenseParameters(string password)        {            CspParameters parameters1 = new CspParameters();            if (!Environment.UserInteractive)            {                parameters1.Flags = CspProviderFlags.UseMachineKeyStore;            }            RSACryptoServiceProvider provider1 = new RSACryptoServiceProvider(0x400, parameters1);            string text1 = provider1.ToXmlString(false);            byte[] buffer1 = EncryptedLicenseProvider.GetEncryptionKey(password);            byte[] buffer2 = provider1.SignData(buffer1, new SHA1CryptoServiceProvider());            DESCryptoServiceProvider provider2 = new DESCryptoServiceProvider();            provider2.Key = EncryptedLicenseProvider._desKey;            provider2.IV = buffer1;            byte[] buffer3 = provider2.CreateEncryptor().TransformFinalBlock(buffer1, 0, buffer1.Length);            byte[] buffer4 = new byte[EncryptedLicenseProvider.ArraySize(8)];            Array.Copy(buffer3, 0, buffer4, 07);            byte[] buffer5 = provider1.SignData(buffer4, new SHA1CryptoServiceProvider());            MemoryStream stream1 = new MemoryStream();            XmlTextWriter writer1 = new XmlTextWriter(stream1, Encoding.ASCII);            writer1.WriteStartElement("LicenseParameters");            writer1.WriteRaw(text1);            writer1.WriteElementString("DesignSignature", Convert.ToBase64String(buffer2));            writer1.WriteElementString("RuntimeSignature", Convert.ToBase64String(buffer5));            writer1.WriteEndElement();            writer1.Close();            string text2 = Encoding.ASCII.GetString(stream1.ToArray());            stream1.Close();            return text2;        }        /// <summary>        /// 获取加密键值        /// </summary>        /// <param name="password">密码</param>        /// <returns></returns>        private static byte[] GetEncryptionKey(string password)        {            byte[] buffer1 = new byte[] 0xf20xa130x9d0x630x870x350x5e };            byte[] buffer2 = new byte[] 0xab0xb80x940x7e0x1d0xe50xd10x33 };            DESCryptoServiceProvider provider1 = new DESCryptoServiceProvider();            provider1.Key = buffer1;            provider1.IV = buffer2;            if (password.Length < 8)            {                password = password.PadRight(8'*');            }            byte[] buffer3 = Encoding.ASCII.GetBytes(password);            byte[] buffer4 = provider1.CreateEncryptor().TransformFinalBlock(buffer3, 0, buffer3.Length);            byte[] buffer5 = new byte[EncryptedLicenseProvider.ArraySize(8)];            Array.Copy(buffer4, 0, buffer5, 07);            return buffer5;        }        /// <summary>        /// 获取许可证        /// </summary>        /// <param name="licenseFile">许可证文件</param>        /// <returns></returns>        public virtual EncryptedLicense GetLicense(string licenseFile)        {            string text1 = this.GetLicenseDirectory(LicenseManager.CurrentContext, null);            string text2 = Path.Combine(text1, licenseFile);            string text3 = this.ReadKeyFromFile(text2);            EncryptedLicense license1 = null;            if (text3 != null)            {                license1 = this.LoadLicense(LicenseManager.CurrentContext, null, text3);            }            return license1;        }        /// <summary>        /// 获取许可证        /// </summary>        /// <param name="licenseParameters">许可证参数</param>        /// <param name="licenseFile">许可证文件</param>        /// <returns></returns>        public virtual EncryptedLicense GetLicense(string licenseParameters, string licenseFile)        {            EncryptedLicenseProvider.SetParameters(licenseParameters);            return this.GetLicense(licenseFile);        }        /// <summary>        /// 获取许可证        /// </summary>        /// <param name="context">指定何时可使用授权的对象,并且提供一种方法,用以获取为支持在其域内运行的许可证所需要的附加服务。</param>        /// <param name="assembly"></param>        /// <param name="type">类型</param>        /// <returns></returns>        public virtual EncryptedLicense GetLicense(LicenseContext context, Assembly assembly, Type type)        {            if (assembly == null)            {                return null;            }            EncryptedLicense license1 = null;            string text1 = this.GetSavedLicenseKey(assembly, type);            if (text1 != null)            {                license1 = this.LoadLicense(context, null, text1);            }            return license1;        }        /// <summary>        /// 获取许可证        /// </summary>        /// <param name="context"></param>        /// <param name="type"></param>        /// <param name="instance">实例</param>        /// <param name="allowExceptions"></param>        /// <returns></returns>        public override License GetLicense(LicenseContext context, Type type, object instance, bool allowExceptions)        {            string text1 = this.GetLicenseKey(context, type);            License license1 = this.LoadLicense(context, type, text1);            if ((license1 == null&& allowExceptions)            {                if (instance == null)                {                    throw new LicenseException(type);                }                throw new LicenseException(type, instance);            }            return license1;        }        /// <summary>        /// 获取许可证目录        /// </summary>        /// <param name="context"></param>        /// <param name="type"></param>        /// <returns></returns>        protected virtual string GetLicenseDirectory(LicenseContext context, Type type)        {            string text1 = null;            if ((context != null&& (type != null))            {                ITypeResolutionService service1 = (ITypeResolutionService)context.GetService(typeof(ITypeResolutionService));                if (service1 != null)                {                    text1 = service1.GetPathOfAssembly(type.Assembly.GetName());                }            }            if (text1 == null)            {                if (type == null)                {                    text1 = AppDomain.CurrentDomain.BaseDirectory;                }                else                {                    text1 = type.Assembly.CodeBase;                    if (text1.StartsWith("file:///"))                    {                        text1 = text1.Replace("file:///""");                    }                    else                    {                        text1 = type.Module.FullyQualifiedName;                    }                }            }            return Path.GetDirectoryName(text1);        }        /// <summary>        /// 获取许可证目录        /// </summary>        /// <param name="context"></param>        /// <param name="type"></param>        /// <returns></returns>        protected virtual string GetLicenseFilePath(LicenseContext context, Type type)        {            string text1 = this.GetLicenseDirectory(context, type);            return string.Format(@"{0}{1}.lic", text1, type.FullName);        }        /// <summary>        /// 获取许可证键值        /// </summary>        /// <param name="context"></param>        /// <param name="type"></param>        /// <returns></returns>        protected virtual string GetLicenseKey(LicenseContext context, Type type)        {            string text1 = null;            if (context.UsageMode == LicenseUsageMode.Runtime)            {                text1 = context.GetSavedLicenseKey(type, null);            }            if (text1 == null)            {                text1 = this.ReadKeyFromFile(this.GetLicenseFilePath(context, type));            }            return text1;        }        /// <summary>        /// 获取已经保存的许可证键值        /// </summary>        /// <param name="assembly"></param>        /// <param name="type"></param>        /// <returns></returns>        private string GetSavedLicenseKey(Assembly assembly, Type type)        {            string text1 = null;            string text2 = assembly.GetName().Name + ".dll.licenses";            Stream stream1 = assembly.GetManifestResourceStream(text2);            if (stream1 != null)            {                IFormatter formatter1 = new BinaryFormatter();                object[] objArray1 = formatter1.Deserialize(stream1) as object[];                if (objArray1 != null)                {                    Hashtable hashtable1 = objArray1[1as Hashtable;                    if (hashtable1 != null)                    {                        foreach (DictionaryEntry entry1 in hashtable1)                        {                            string text3 = entry1.Key as string;                            if (text3 != null)                            {                                text3 = text3.Trim();                                if (text3.IndexOf(type.FullName) == 0)                                {                                    text1 = entry1.Value as string;                                    break;                                }                            }                        }                    }                }                stream1.Close();            }            return text1;        }        /// <summary>        /// 安装许可证文件        /// </summary>        /// <param name="licenseFile"></param>        /// <param name="licenseKey"></param>        /// <returns></returns>        public virtual EncryptedLicense InstallLicense(string licenseFile, string licenseKey)        {            EncryptedLicense license1 = this.LoadLicense(LicenseManager.CurrentContext, null, licenseKey);            if (license1 != null)            {                string text1 = this.GetLicenseDirectory(LicenseManager.CurrentContext, null);                string text2 = Path.Combine(text1, licenseFile);                this.WriteKeyToFile(text2, licenseKey);            }            return license1;        }        /// <summary>        /// 安装许可证文件        /// </summary>        /// <param name="type"></param>        /// <param name="licenseKey"></param>        /// <returns></returns>        public virtual EncryptedLicense InstallLicense(Type type, string licenseKey)        {            EncryptedLicense license1 = this.LoadLicense(LicenseManager.CurrentContext, type, licenseKey);            if (license1 != null)            {                string text1 = this.GetLicenseFilePath(LicenseManager.CurrentContext, type);                this.WriteKeyToFile(text1, licenseKey);            }            return license1;        }        /// <summary>        /// 安装许可证文件        /// </summary>        /// <param name="licenseParameters"></param>        /// <param name="licenseFile"></param>        /// <param name="licenseKey"></param>        /// <returns></returns>        public virtual EncryptedLicense InstallLicense(string licenseParameters, string licenseFile, string licenseKey)        {            EncryptedLicenseProvider.SetParameters(licenseParameters);            return this.InstallLicense(licenseFile, licenseKey);        }        /// <summary>        /// 载入许可证文件        /// </summary>        /// <param name="context"></param>        /// <param name="type"></param>        /// <param name="licenseKey"></param>        /// <returns></returns>        private EncryptedLicense LoadLicense(LicenseContext context, Type type, string licenseKey)        {            if (((EncryptedLicenseProvider._rsaParameters == null|| (EncryptedLicenseProvider._designSignature == null)) || (EncryptedLicenseProvider._runtimeSignature == null))            {                throw new InvalidOperationException();            }            if (licenseKey == null)            {                return null;            }            try            {                byte[] buffer1 = EncryptedLicenseProvider.FromHex(licenseKey);                DESCryptoServiceProvider provider1 = new DESCryptoServiceProvider();                provider1.Key = EncryptedLicenseProvider._desKey;                provider1.IV = EncryptedLicenseProvider._desIV;                byte[] buffer2 = provider1.CreateDecryptor().TransformFinalBlock(buffer1, 0, buffer1.Length);                byte[] buffer3 = new byte[EncryptedLicenseProvider.ArraySize(8)];                byte[] buffer4 = new byte[EncryptedLicenseProvider.ArraySize(buffer2.Length - 7)];                Array.Copy(buffer2, 0, buffer3, 07);                Array.Copy(buffer2, 7, buffer4, 0, buffer4.Length);                CspParameters parameters1 = new CspParameters();                if (!Environment.UserInteractive)                {                    parameters1.Flags = CspProviderFlags.UseMachineKeyStore;                }                RSACryptoServiceProvider provider2 = new RSACryptoServiceProvider(parameters1);                provider2.FromXmlString(EncryptedLicenseProvider._rsaParameters);                if (context.UsageMode == LicenseUsageMode.Designtime)                {                    if (!provider2.VerifyData(buffer3, new SHA1CryptoServiceProvider(), EncryptedLicenseProvider._designSignature))                    {                        return null;                    }                }                else if (!provider2.VerifyData(buffer3, new SHA1CryptoServiceProvider(), EncryptedLicenseProvider._runtimeSignature) && !provider2.VerifyData(buffer3, new SHA1CryptoServiceProvider(), EncryptedLicenseProvider._designSignature))                {                    return null;                }                provider1.IV = buffer3;                byte[] buffer5 = provider1.CreateDecryptor().TransformFinalBlock(buffer4, 0, buffer4.Length);                byte[] buffer6 = new byte[EncryptedLicenseProvider.ArraySize(buffer5.Length - 2)];                Array.Copy(buffer5, 2, buffer6, 0, buffer6.Length);                ushort num1 = BitConverter.ToUInt16(buffer5, 0);                string text1 = Encoding.UTF8.GetString(buffer6);                if ((context.UsageMode == LicenseUsageMode.Designtime) && (type != null))                {                    byte[] buffer7 = provider1.CreateEncryptor().TransformFinalBlock(buffer3, 0, buffer3.Length);                    byte[] buffer8 = new byte[EncryptedLicenseProvider.ArraySize(8)];                    Array.Copy(buffer7, 0, buffer8, 07);                    provider1.IV = buffer8;                    buffer4 = provider1.CreateEncryptor().TransformFinalBlock(buffer5, 0, buffer5.Length);                    buffer2 = new byte[EncryptedLicenseProvider.ArraySize(7 + buffer4.Length)];                    buffer8.CopyTo(buffer2, 0);                    buffer4.CopyTo(buffer2, 7);                    provider1.IV = EncryptedLicenseProvider._desIV;                    buffer1 = provider1.CreateEncryptor().TransformFinalBlock(buffer2, 0, buffer2.Length);                    string text2 = EncryptedLicenseProvider.ToHex(buffer1);                    context.SetSavedLicenseKey(type, text2);                }                return new EncryptedLicense(licenseKey, num1, text1);            }            catch            {                return null;            }        }        /// <summary>        /// 从许可证文件中读取键值        /// </summary>        /// <param name="licenseFile"></param>        /// <returns></returns>        protected virtual string ReadKeyFromFile(string licenseFile)        {            string text1 = null;            if (File.Exists(licenseFile))            {                Stream stream1 = new FileStream(licenseFile, FileMode.Open, FileAccess.Read, FileShare.Read);                StreamReader reader1 = new StreamReader(stream1);                text1 = reader1.ReadToEnd();                reader1.Close();            }            return text1;        }        /// <summary>        /// 设置许可证参数。        /// </summary>        /// <param name="licenseParameters"></param>        public static void SetParameters(string licenseParameters)        {            XmlReader reader1 = new XmlTextReader(licenseParameters, XmlNodeType.Element, null);            while (reader1.Read())            {                if (reader1.IsStartElement())                {                    if (reader1.LocalName == "RSAKeyValue")                    {                        EncryptedLicenseProvider._rsaParameters = reader1.ReadOuterXml();                    }                    if (reader1.LocalName == "DesignSignature")                    {                        string text1 = reader1.ReadElementString();                        EncryptedLicenseProvider._designSignature = Convert.FromBase64String(text1);                    }                    if (reader1.LocalName == "RuntimeSignature")                    {                        string text2 = reader1.ReadElementString();                        EncryptedLicenseProvider._runtimeSignature = Convert.FromBase64String(text2);                    }                }            }            reader1.Close();        }        /// <summary>        /// 在字符串中查找指定的字符        /// </summary>        /// <param name="value"></param>        /// <param name="characters"></param>        /// <returns></returns>        private static string Strip(string value, string characters)        {            if (value == null)            {                return null;            }            StringBuilder builder1 = new StringBuilder();            foreach (char ch1 in value)            {                if (characters.IndexOf(ch1, 0< 0)                {                    builder1.Append(ch1);                }            }            return builder1.ToString();        }        /// <summary>        /// 转为哈希        /// </summary>        /// <param name="data"></param>        /// <returns></returns>        private static string ToHex(byte[] data)        {            StringBuilder builder1 = new StringBuilder();            for (int num1 = 0; num1 < data.Length; num1++)            {                if ((num1 > 0&& ((num1 % 2== 0))                {                    builder1.Append("-");                }                builder1.Append(data[num1].ToString("X2"));            }            return builder1.ToString();        }        /// <summary>        /// 校验许可证键值        /// </summary>        /// <param name="licenseKey"></param>        /// <returns></returns>        public virtual EncryptedLicense ValidateLicenseKey(string licenseKey)        {            return this.LoadLicense(LicenseManager.CurrentContext, null, licenseKey);        }        /// <summary>        /// 校验许可证键值        /// </summary>        /// <param name="licenseParameters"></param>        /// <param name="licenseKey"></param>        /// <returns></returns>        public virtual EncryptedLicense ValidateLicenseKey(string licenseParameters, string licenseKey)        {            EncryptedLicenseProvider.SetParameters(licenseParameters);            return this.LoadLicense(LicenseManager.CurrentContext, null, licenseKey);        }        /// <summary>        /// 写键值到许可证文件。        /// </summary>        /// <param name="licenseFile"></param>        /// <param name="licenseKey"></param>        protected virtual void WriteKeyToFile(string licenseFile, string licenseKey)        {            Stream stream1 = new FileStream(licenseFile, FileMode.Create, FileAccess.Write, FileShare.None);            StreamWriter writer1 = new StreamWriter(stream1);            writer1.WriteLine(licenseKey);            writer1.Close();        }        internal static EncryptedLicense SystemLicense        {            get            {                if (EncryptedLicenseProvider._systemLicense == null)                {                    EncryptedLicenseProvider.SetParameters("");                    EncryptedLicenseProvider provider1 = new EncryptedLicenseProvider();                    EncryptedLicenseProvider._systemLicense = provider1.GetLicense(LicenseManager.CurrentContext, typeof(EncryptedLicenseProvider), nullfalseas EncryptedLicense;                }                return EncryptedLicenseProvider._systemLicense;            }        }    }  

    最新回复(0)