.NET中的许可证机制
主要类:
System.ComponentModel.License(为所有许可证提供 abstract 基类。向组件的特定实例授予许可证)
     System.ComponentModel.LicenseContext(指定何时可使用授权的对象,并且提供一种方法,用以获取为支持在其域内运行的许可证所需要的附加服务)
     System.ComponentModel.LicenseException(表示当组件不能被授予许可证时引发的异常。)
     System.ComponentModel.LicenseManager(提供属性和方法,用以将许可证添加到组件和管理 LicenseProvider)
     System.ComponentModel.LicenseProvider(提供 abstract 基类以便实现许可证提供程序)
     System.ComponentModel.LicenseProviderAttribute(指定要与类一起使用的 LicenseProvider)
许可证机制简介
.Net Framework中的许可证验证机制基于System.ComponentModel命名空间中的License、LicenseContext、LicenseException、LicenseManager、LicenseProvider和LicenseProviderAttribute六个类实现的。
License是一个抽象类,用于代表许可证主体;
LicenseContext中保存了许可证的上下文,其中UsageMode属性可以用来获取当前是运行时(runtime)还是设计模式(designtime);
LicenseException是许可证相关的异常,当许可证信息不可用时,在调用LicenseProvider(或其派生类)实例的GetLicense方法时将抛出此类型的异常;
LicenseManager是一个密封(sealed)类,LicenseManager提供了多个静态(static)方法用于验证许可证、获取许可证等操作;
LicenseProviderAttribute属性用于指定某一个类所采用的许可证提供程序(LicenseProvider)的具体类型;
LicenseProvider是一个抽象类,用于代表许可证验证机制提供程序。LicenseProvider的类型通过LicenseProviderAttribute属性提供给CLR,当调用LicenseManager的操作时,LicenseManager将根据LicenseProviderAttribute中所提供的LicenseProvider类型创建LicenseProvider实例,并进行相应操作。LicFileLicenseProvider基于文本文件的许可证机制。
简单应用:
1:首先要创建一个License,但是因为License是抽象的,所以要创建一个集成自License的子类,实现License的一些方法。
2:创建一个LicenseProvider类,这个类要集成LicenseProvider的类。实现一些方法。LicenseProvider类提供了验证机制的程序。LicenseProvider类要重载GetLicense(LicenseContext,Type ,object ,bool)方法,该方法真正提供了,一些算法,去实现验证。
3:创建一个自定义的类,并且给该类添加LicenseProviderAttribute属性。指定对这个类进行验证的机制采用LiceseProvider。
具体代码:
定义Licese类
private class MyLicense : License
        {
            private String mLicenseKey = null;
            private MyLicenseProvider mProvider = null;
            public MyLicense(MyLicenseProvider provider, String key)
            {
                this.mProvider = provider;
                this.mLicenseKey = key;
            }
            public override string LicenseKey
            {
                get { return this.mLicenseKey; }
            }
            public override void Dispose()
            {
                this.mProvider = null;
                this.mLicenseKey = null;
            }
        }
定义LicenseProvider类
[ReflectionPermission(SecurityAction.Deny, MemberAccess=false, ReflectionEmit=false)]
    internal class MyLicenseProvider : LicenseProvider
    {
构造函数
   public MyLicenseProvider()
        { }
        /// <summary>
        /// 获取本机MAC地址 其实这个不管是获取本机硬件参数的任何信息都可以这要能标志该机器即可
        /// </summary>
        private String GetMacAddress()
        {
            String macAddr = null;
            ManagementClass inetAdapter = new ManagementClass("WIN32_NetworkAdapterConfiguration");
            ManagementObjectCollection objList = inetAdapter.GetInstances();
            foreach (ManagementObject mobj in objList)
            {
                if ((bool)mobj["IPEnabled"])
                {
                    macAddr = mobj["MacAddress"].ToString().Replace(":", "-");
                    break;
                }
            }
            return macAddr;
        }

/// <summary>
        /// 获取Assembly所在目录   获取应用程序所在的目录
        /// </summary>
        private String GetAssemblyPath(LicenseContext context)
        {
            String fileName = null;
            Type type = this.GetType();
            ITypeResolutionService service = (ITypeResolutionService)context.GetService(typeof(ITypeResolutionService));
            if (service != null)
            {
                fileName = service.GetPathOfAssembly(type.Assembly.GetName());
            }
            if (fileName == null)
            {
                fileName = type.Module.FullyQualifiedName;
            }
            return Path.GetDirectoryName(fileName);
        }

private String Encrypt(String source)     加密算法,可以用,也可不用,这里为了更安全,就用。
        {
            /**
             * 加密算法
             */
            byte[] keyData = Encoding.ASCII.GetBytes("");
            byte[] ivData = Encoding.ASCII.GetBytes("4iJ9Qw#L");
            MemoryStream stream = new MemoryStream();
            DES desProvider = new DESCryptoServiceProvider();
            CryptoStream cs = new CryptoStream(stream,
            desProvider.CreateEncryptor(keyData, ivData),
            CryptoStreamMode.Write);
            byte[] buffer = Encoding.ASCII.GetBytes(source);
            cs.Write(buffer, 0, buffer.Length);
            cs.FlushFinalBlock();
            cs.Close();
            buffer = stream.GetBuffer();
            stream.Close();
            return Convert.ToBase64String(buffer);
            return source;
        }

public override License GetLicense(LicenseContext context, Type type, object instance, bool allowExceptions)
        {
            MyLicense license = null;
            
            // 计算MAC地址加密串
            String macAddr = this.GetMacAddress();
            String encrypt = this.Encrypt(macAddr);
            if (context != null)
            {
                if (context.UsageMode == LicenseUsageMode.Runtime)
                {
                    String savedLicenseKey = context.GetSavedLicenseKey(type, null);
                    if (encrypt.Equals(savedLicenseKey))
                    {
                        return new MyLicense(this, encrypt);
                    }
                }
                if (license != null)
                {
                    return license;
                }
                
                // 打开License文件 'license.dat'
                String path = this.GetAssemblyPath(context);
                String licFile = Path.Combine(path, "license.dat");
                if (File.Exists(licFile))
                {
                    Stream fs = new FileStream(licFile, FileMode.Open, FileAccess.Read);
                    StreamReader sr = new StreamReader(fs);
                    String readedLicenseKey = sr.ReadToEnd();
                    sr.Close();
                    fs.Close();
                    if (encrypt.Equals(readedLicenseKey))
                    {
                        license = new MyLicense(this, encrypt);
                    }
                }
                if (license != null)
                {
                    context.SetSavedLicenseKey(type, encrypt);
                }
            }
            if (license == null)
            {
                System.Windows.Forms.MessageBox.Show("!!!尚未注册!!!");
                return new MyLicense(this, "evaluate");
            }
            return license;
        }
指定该类进行许可验证的程序采用MyLicenseProvider 这句必须的。
[LicenseProvider(typeof(MyLicenseProvider))]
    public partial class LicenseHelper
    {
        private License mLicense = null;
        
        public LicenseHelper()
        {
            this.mLicense = LicenseManager.Validate(typeof( LicenseHelper), this);
        }
        ~ LicenseHelper()    析构函数,在C#中,不常用。
        {
            if (this.mLicense != null)
            {
                this.mLicense.Dispose();
                this.mLicense = null;
            }
        }
    }
这样。在程序中调用LicenseHelper是就要进行验证,否则。就会出现异常。
该方法也可以对软件进行加密,只是在GetLicense(LicenseContext, type, object,bool);方法中写的机密算法要复杂一些。但是道理都是这样的。

出处:http://blog.csdn.net/joyhen/article/details/22715223

.NET中的许可证机制--License的更多相关文章

  1. 1 weekend110的复习 + hadoop中的序列化机制 + 流量求和mr程序开发

    以上是,weekend110的yarn的job提交流程源码分析的复习总结 下面呢,来讲weekend110的hadoop中的序列化机制 1363157985066      13726230503  ...

  2. 探索Android中的Parcel机制(上)

    一.先从Serialize说起 我们都知道JAVA中的Serialize机制,译成串行化.序列化……,其作用是能将数据对象存入字节流其中,在须要时又一次生成对象.主要应用是利用外部存储设备保存对象状态 ...

  3. Android中的Parcel机制(上)

    一.先从Serialize说起 我们都知道JAVA中的Serialize机制,译成串行化.序列化--,其作用是能将数据对象存入字节流当中,在需要时重新生成对象.主要应用是利用外部存储设备保存对象状态, ...

  4. .Net中Remoting通信机制简单实例

    .Net中Remoting通信机制 前言: 本程序例子实现一个简单的Remoting通信案例 本程序采用语言:c# 编译工具:vs2013工程文件 编译环境:.net 4.0 程序模块: Test测试 ...

  5. Objective-C中的属性机制

    Objective-C 2.0中的属性机制为我们提供了便捷的获取和设置实例变量的方式,也可以说属性为我们提供了一个默认的设置器和访问器的实现.在学习OC中属性之前我们先要知道为什么要为变量实现gett ...

  6. 浅谈Linux中的信号处理机制(二)

    首先谢谢 @小尧弟 这位朋友对我昨天夜里写的一篇<浅谈Linux中的信号处理机制(一)>的指正,之前的题目我用的“浅析”一词,给人一种要剖析内核的感觉.本人自知功力不够,尚且不能对着Lin ...

  7. java中的反射机制在Android开发中的用处

    JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法:对于任意一个对象,都能够调用它的任意一个方法和属性:这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反 ...

  8. C++中的异常处理机制

    C++中的捕获异常机制catch参数中实参的类型不同,采取的处理方式则不相同,且与普通的函数调用还不一样,具体表现为当抛出异常throw A()或throw obj时,对象会进行一次额外的对象复制操作 ...

  9. 别再为了this发愁了------JS中的this机制

    别再为了this发愁了------JS中的this机制 题记:JavaScript中有很多令人困惑的地方,或者叫做机制.但是,就是这些东西让JavaScript显得那么美好而与众不同.比方说函数也是对 ...

随机推荐

  1. [转]Qt中定时器使用的两种方法

    Qt中定时器的使用有两种方法,一种是使用QObject类提供的定时器,还有一种就是使用QTimer类. 其精确度一般依赖于操作系统和硬件,但一般支持20ms.下面将分别介绍两种方法来使用定时器. 方法 ...

  2. node.js 基础二 开启服务器监听

    1.server.js 2.监听 一 server.js 二 监听 运行server.js后,浏览器打开:http://localhost:8888/ //====================== ...

  3. java 日期与时间类

    1.Date类:  https://www.cnblogs.com/huangminwen/p/5994927.html 2.DateFormat和SimpleDateFormat (simple简单 ...

  4. kubernetes中infra容器的理解

    1. infra容器和用户容器的关系 1.1 pause 是k8s的基础设施的一部分,pod中其他容器通过pause容器跟其他pod进行通信. 1.2 pod中其他容器跟pause容器共享命名空间1. ...

  5. 人生苦短之学习Python50本书籍(包涵基础、算法、机器学习、模块、爬虫框架、树莓派等)总有你想要的书籍

    很多小伙伴说想学习想学习但是没有学习书籍,我给大家分享一大波学习书籍,具体的可以自己往下翻 ​<"笨办法学"Python3> Zed Shaw 著 (2018年5月) ...

  6. 盖茨基金会:如何使用Python拯救生命

    每年全球都要花费数十亿美元来预防疾病,减少死亡,资助预防保健及治疗的各种研发项目,以及其他的健康方案.但资金毕竟是有限的,所以一些组织,比如全球卫生资金的主要捐助者比尔&梅林达·盖茨基金会(B ...

  7. ( 转)Ubuntu下创建、重命名、删除文件及文件夹,强制清空回收站方法

    Ubuntu下创建.重命名.删除文件及文件夹,强制清空回收站方法 mkdir 目录名 ——创建一个目录 rmdir 空目录名 ——删除一个空目录 rm 文件名 文件名 ——删除一个文件或多个文件 rm ...

  8. Linux查看日志常用命令

    1.动态循环查看文件内容 tail  -n  10  test.log   查询日志尾部最后10行的日志; tail -n +10 test.log    查询10行之后的所有日志; head -n ...

  9. WPF制作带明细的环形图表

    效果 明细用Popup实现的,录gif时,Popup显示不出来,不知道为什么,所以静态图凑合看吧 大体思路 图表使用Arc+Popup实现 图表分为两部分,一是环形部分,一是标注的明细部分. 环形部分 ...

  10. Ubuntu16.04下使用rdesktop命令远程连接windows机器

    前段时间在本机安装了ubuntu16.04桌面版,后来需要远程连接一台win10系统的跳转机,下面介绍使用rdesktop命令远程连接windows机器的操作记录:1)首先安装rdesktop工具 k ...