C#软件license管理(简单软件注册机制)

原博客地址

 基本原理:

  • 1.软件一运行就把计算机的CPU、主板、BIOS、MAC地址记录下来,然后加密(key=key1)生成文件【ComputerInfo.key】;
  • 2.注册机将该文件内容MD5加密后再进行一次加密(key=key2)保存成注册文件【RegistInfo.key】;
  • 3.注册验证的逻辑,计算机信息加密后(key=key1)加密md5==注册文件解密(key=key2);
  • 4.采用ConfuserEx将可执行文件加密

这样别人要破解也就需要点力气了(没打算防破解,本意只想防复制的),有能力破解的人也不在乎破解这个软件了

 1.获取电脑相关硬件信息代码:

【C#提供了ManagementClass类(命名空间System.Management):可以获得磁盘驱动器模块的方法、属性和限定符】

using Microsoft.Win32;
using System;
using System.Management;
using System.Net.NetworkInformation;

namespace RFIDClient1.util
{
    public class ComputerInfo
    {
        public static string GetComputerInfo()
        {
            string info = string.Empty;
            string cpu = GetCPUInfo();
            string baseBoard = GetBaseBoardInfo();
            string bios = GetBIOSInfo();
            string mac = GetMACInfo();
            info = string.Concat(bios, cpu, mac, baseBoard);
            return info;
        }

        private static string GetCPUInfo()
        {
            string info = string.Empty;
            info = GetHardWareInfo("Win32_Processor", "ProcessorId");
            return info;
        }
        private static string GetBIOSInfo()
        {
            string info = string.Empty;
            info = GetHardWareInfo("Win32_BIOS", "SerialNumber");
            return info;
        }
        private static string GetBaseBoardInfo()
        {
            string info = string.Empty;
            info = GetHardWareInfo("Win32_BaseBoard", "SerialNumber");
            return info;
        }
        private static string GetMACInfo()
        {
            string info = string.Empty;
            info = GetHardWareInfo("Win32_BaseBoard", "SerialNumber");
            return info;
        }
        private static string GetHardWareInfo(string typePath, string key)
        {
            try
            {
                ManagementClass managementClass = new ManagementClass(typePath);
                ManagementObjectCollection mn = managementClass.GetInstances();
                PropertyDataCollection properties = managementClass.Properties;
                foreach (PropertyData property in properties)
                {
                    if (property.Name == key)
                    {
                        foreach (ManagementObject m in mn)
                        {
                            return m.Properties[property.Name].Value.ToString();
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                //这里写异常的处理  
            }
            return string.Empty;
        }
        private static string GetMacAddressByNetworkInformation()
        {
            string key = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\";
            string macAddress = string.Empty;
            try
            {
                NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
                foreach (NetworkInterface adapter in nics)
                {
                    if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet
                        && adapter.GetPhysicalAddress().ToString().Length != 0)
                    {
                        string fRegistryKey = key + adapter.Id + "\\Connection";
                        RegistryKey rk = Registry.LocalMachine.OpenSubKey(fRegistryKey, false);
                        if (rk != null)
                        {
                            string fPnpInstanceID = rk.GetValue("PnpInstanceID", "").ToString();
                            int fMediaSubType = Convert.ToInt32(rk.GetValue("MediaSubType", 0));
                            if (fPnpInstanceID.Length > 3 &&
                                fPnpInstanceID.Substring(0, 3) == "PCI")
                            {
                                macAddress = adapter.GetPhysicalAddress().ToString();
                                for (int i = 1; i < 6; i++)
                                {
                                    macAddress = macAddress.Insert(3 * i - 1, ":");
                                }
                                break;
                            }
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                //这里写异常的处理  
            }
            return macAddress;
        }
    }

}

   2.加密解密代码;

【 注:这边在MD5时前后各加了一段字符,这样增加一点破解难度。】

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace RFIDClient1.util
{
    public enum EncryptionKeyEnum
    {
        KeyA,
        KeyB
    }
    public class EncryptionHelper
    {
        string encryptionKeyA = "pfe_Nova";
        string encryptionKeyB = "WorkHard";
        string md5Begin = "Hello";
        string md5End = "World";
        string encryptionKey = string.Empty;
        public EncryptionHelper()
        {
            this.InitKey();
        }
        public EncryptionHelper(EncryptionKeyEnum key)
        {
            this.InitKey(key);
        }
        private void InitKey(EncryptionKeyEnum key = EncryptionKeyEnum.KeyA)
        {
            switch (key)
            {
                case EncryptionKeyEnum.KeyA:
                    encryptionKey = encryptionKeyA;
                    break;
                case EncryptionKeyEnum.KeyB:
                    encryptionKey = encryptionKeyB;
                    break;
            }
        }

        public string EncryptString(string str)
        {
            return Encrypt(str, encryptionKey);
        }
        public string DecryptString(string str)
        {
            return Decrypt(str, encryptionKey);
        }
        public string GetMD5String(string str)
        {
            str = string.Concat(md5Begin, str, md5End);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] fromData = Encoding.Unicode.GetBytes(str);
            byte[] targetData = md5.ComputeHash(fromData);
            string md5String = string.Empty;
            foreach (var b in targetData)
                md5String += b.ToString("x2");
            return md5String;
        }

        private string Encrypt(string str, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.Default.GetBytes(str);
            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            ret.ToString();
            return ret.ToString();
        }
        private string Decrypt(string pToDecrypt, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
            for (int x = 0; x < pToDecrypt.Length / 2; x++)
            {
                int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                inputByteArray[x] = (byte)i;
            }
            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            return System.Text.Encoding.Default.GetString(ms.ToArray());
        }
    }

}

3.读写文件

using System;
using System.IO;

namespace RFIDClient1.util
{
    public class RegistFileHelper
    {
        public static string ComputerInfofile = "ComputerInfo.key";
        public static string RegistInfofile = "RegistInfo.key";
        public static void WriteRegistFile(string info)
        {
            WriteFile(info, RegistInfofile);
        }
        public static void WriteComputerInfoFile(string info)
        {
            WriteFile(info, ComputerInfofile);
        }
        public static string ReadRegistFile()
        {
            return ReadFile(RegistInfofile);
        }
        public static string ReadComputerInfoFile()
        {
            return ReadFile(ComputerInfofile);
        }
        public static bool ExistComputerInfofile()
        {
            return File.Exists(ComputerInfofile);
        }
        public static bool ExistRegistInfofile()
        {
            return File.Exists(RegistInfofile);
        }
        private static void WriteFile(string info, string fileName)
        {
            try
            {
                using (StreamWriter sw = new StreamWriter(fileName, false))
                {
                    sw.Write(info);
                    sw.Close();
                }
            }
            catch (Exception ex)
            {
            }
        }
        private static string ReadFile(string fileName)
        {
            string info = string.Empty;
            try
            {
                using (StreamReader sr = new StreamReader(fileName))
                {
                    info = sr.ReadToEnd();
                    sr.Close();
                }
            }
            catch (Exception ex)
            {
            }
            return info;
        }
    }

}

 4.其他界面代码:

主界面代码:

public partial class FormMain : Form
{
    private string encryptComputer = string.Empty;
    private bool isRegist = false;
    private const int timeCount = 30;
    public FormMain()
    {
        InitializeComponent();
        Control.CheckForIllegalCrossThreadCalls = false;
    }
    private void FormMain_Load(object sender, EventArgs e)
    {
        string computer = ComputerInfo.GetComputerInfo();
        encryptComputer = new EncryptionHelper().EncryptString(computer);
        if (CheckRegist() == true)
        {
            lbRegistInfo.Text = "已注册";
        }
        else
        {
            lbRegistInfo.Text = "待注册,运行十分钟后自动关闭";
            RegistFileHelper.WriteComputerInfoFile(encryptComputer);
            TryRunForm();
        }
    }
    /// <summary>
    /// 试运行窗口
    /// </summary>
    private void TryRunForm()
    {
        Thread threadClose = new Thread(CloseForm);
        threadClose.IsBackground = true;
        threadClose.Start();
    }
    private bool CheckRegist()
    {
        EncryptionHelper helper = new EncryptionHelper();
        string md5key = helper.GetMD5String(encryptComputer);
        return CheckRegistData(md5key);
    }
    private bool CheckRegistData(string key)
    {
        if (RegistFileHelper.ExistRegistInfofile() == false)
        {
            isRegist = false;
            return false;
        }
        else
        {
            string info = RegistFileHelper.ReadRegistFile();
            var helper = new EncryptionHelper(EncryptionKeyEnum.KeyB);
            string registData = helper.DecryptString(info);
            if (key == registData)
            {
                isRegist = true;
                return true;
            }
            else
            {
                isRegist = false;
                return false;
            }
        }
    }
    private void CloseForm()
    {
        int count = 0;
        while (count < timeCount && isRegist == false)
        {
            if (isRegist == true)
            {
                return;
            }
            Thread.Sleep(1 * 1000);
            count++;
        }
        if (isRegist == true)
        {
            return;
        }
        else
        {
            this.Close();
        }
    }
 
    private void btnRegist_Click(object sender, EventArgs e)
    {
        if (lbRegistInfo.Text == "已注册")
        {
            MessageBox.Show("已经注册~");
            return;
        }
        string fileName = string.Empty;
        OpenFileDialog openFileDialog = new OpenFileDialog();
        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            fileName = openFileDialog.FileName;
        }
        else
        {
            return;
        }
        string localFileName = string.Concat(
            Environment.CurrentDirectory,
            Path.DirectorySeparatorChar,
            RegistFileHelper.RegistInfofile);
        if (fileName != localFileName)
            File.Copy(fileName, localFileName, true);
 
        if (CheckRegist() == true)
        {
            lbRegistInfo.Text = "已注册";
            MessageBox.Show("注册成功~");
        }
    }
}

 注册机代码:

public partial class FormMain : Form
{
    public FormMain()
    {
        InitializeComponent();
    }
 
    private void btnRegist_Click(object sender, EventArgs e)
    {
        string fileName = string.Empty;
        OpenFileDialog openFileDialog = new OpenFileDialog();
        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            fileName = openFileDialog.FileName;
        }
        else
        {
            return;
        }
        string localFileName = string.Concat(
            Environment.CurrentDirectory,
            Path.DirectorySeparatorChar,
            RegistFileHelper.ComputerInfofile);
 
        if (fileName != localFileName)
            File.Copy(fileName, localFileName, true);
        string computer = RegistFileHelper.ReadComputerInfoFile();
        EncryptionHelper help = new EncryptionHelper(EncryptionKeyEnum.KeyB);
        string md5String = help.GetMD5String(computer);
        string registInfo = help.EncryptString(md5String);
        RegistFileHelper.WriteRegistFile(registInfo);
        MessageBox.Show("注册码已生成");
    }
}

最后采用ConfuserEx将可执行文件加密(ConfuserEx介绍),这样就不能反编译获得源码。

 示例源码下载

  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
C# 中,你可以通过以下代码设置软件管理员权限: ```csharp using System.Diagnostics; using System.Security.Principal; // 检查当前用户是否为管理员 bool isAdmin = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); if (!isAdmin) { // 创建一个启动信息对象 ProcessStartInfo startInfo = new ProcessStartInfo(); // 指定要启动的程序的路径和文件名 startInfo.FileName = Application.ExecutablePath; // 指定启动时要使用的用户名和密码 startInfo.UserName = "Administrator"; startInfo.Password = new SecureString(); string password = "123456"; // 这里需要替换为实际的管理员密码 foreach (char c in password) { startInfo.Password.AppendChar(c); } // 指定启动时使用的域名,默认为本地机器名 startInfo.Domain = Environment.MachineName; // 指定启动时的参数 startInfo.Arguments = "/restart"; // 指定启动时的工作目录 startInfo.WorkingDirectory = Application.StartupPath; // 指定启动时的窗口模式 startInfo.WindowStyle = ProcessWindowStyle.Normal; // 指定启动时的标准输入输出流 startInfo.UseShellExecute = false; startInfo.RedirectStandardInput = true; startInfo.RedirectStandardOutput = true; // 启动程序,并等待程序退出 Process process = new Process(); process.StartInfo = startInfo; process.Start(); process.WaitForExit(); } ``` 这段代码首先检查当前用户是否为管理员,如果不是,则使用 `ProcessStartInfo` 对象来启动程序,并使用管理员权限运行程序。在 `ProcessStartInfo` 对象中,我们可以指定启动时使用的用户名、密码、域名、参数、工作目录、窗口模式以及标准输入输出流等信息。最后,我们使用 `Process` 对象启动程序,并等待程序退出。 需要注意的是,使用管理员权限运行程序需要输入管理员账户的密码,这里我们将密码以明文的方式写在代码中,这并不是一个安全的做法。为了保证安全性,我们应该将密码以加密的方式保存在配置文件中,或者使用其他安全的方式来获取管理员密码。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值