导航

C# 应用程序许可控制

Posted on 2006-09-12 10:01  hcfalan  阅读(2058)  评论(0编辑  收藏  举报
源代码下载:LicenseDemo.rar

首先,需要实现一个LicenseProvider
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Management;
using System.Security.Cryptography;
using System.Security.Permissions;

namespace LicenseDemo
{
    [ReflectionPermission(SecurityAction.Deny, MemberAccess
=false, ReflectionEmit=false)]
    
internal class MyLicenseProvider : LicenseProvider
    
{
        
Define MyLicense

        
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("Zx2@Yt8P");
            
//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;
        }

    }

}

然后,在需要许可控制的组件上使用该LicenseProvider:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace LicenseDemo
{
    [LicenseProvider(
typeof(MyLicenseProvider))]
    
public partial class Form1 : Form
    
{
        
private License mLicense = null;
        
        
public Form1()
        
{
            
this.mLicense = LicenseManager.Validate(typeof(Form1), this);
            InitializeComponent();
        }


        
~Form1()
        
{
            
if (this.mLicense != null)
            
{
                
this.mLicense.Dispose();
                
this.mLicense = null;
            }

        }


        
private void button1_Click(object sender, EventArgs e)
        
{
            System.Windows.Forms.MessageBox.Show(
"Hello, world!");
        }

    }

}

直接运行,在Form1窗口出来之前,先会Show出一个“!!!尚未注册!!!”的对话框,这是因为还没有提供License文件的缘故。然后在程序exe文件目录创建一个license.dat文件,使用notepad编辑,直接将本机Mac地址复制进来,然后保存该文件,此时相当于用户已经提供了正确的许可文件,再运行,就不会提示尚未注册的对话框了。