本文介绍了基于 本机特征信息(如CPU、主板、BIOS和MAC等) 的软件加密、授权与注册方法,并分享了 示例程序完整源代码。
1 加密、授权与注册
软件的加密、授权与注册流程如下:
2 本机特征信息
本机特征信息主要包括:①CPU信息、②主板序列号、③BIOS信息、④MAC地址,基于C#获取代码如下:
using System;
using System.Management;
using System.Net.NetworkInformation;
using Microsoft.Win32;
namespace RWRegister
{
public class Computer
{
public static string ComputerInfo()
{
string info = string.Empty;
string cpu = GetCPUInfo();
string baseBoard = GetBaseBoardInfo();
string bios = GetBIOSInfo();
string mac = GetMACInfo();
info = string.Concat(cpu, baseBoard, bios, mac);
return info;
}
private static string GetCPUInfo()
{
string info = string.Empty;
info = GetHardWareInfo("Win32_Processor", "ProcessorId");
return info;
}
private static string GetBaseBoardInfo()
{
string info = string.Empty;
info = GetHardWareInfo("Win32_BaseBoard", "SerialNumber");
return info;
}
private static string GetBIOSInfo()
{
string info = string.Empty;
info = GetHardWareInfo("Win32_BIOS", "SerialNumber");
return info;
}
private static string GetMACInfo()
{
string info = string.Empty;
info = GetMacAddressByNetwork();
return info;
}
private static string GetHardWareInfo(string typePath, string Key)
{
try
{
ManagementClass mageClass = new ManagementClass(typePath);
ManagementObjectCollection mageObjectColl = mageClass.GetInstances();
PropertyDataCollection Properties = mageClass.Properties;
foreach (PropertyData property in Properties)
{
if (property.Name == Key)
{
foreach (ManagementObject mageObject in mageObjectColl)
{
return mageObject.Properties[property.Name].Value.ToString();
}
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return string.Empty;
}
private static string GetMacAddressByNetwork()
{
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 rKey = Registry.LocalMachine.OpenSubKey(fRegistryKey, false);
if (rKey != null)
{
string fPnpInstanceID = rKey.GetValue("PnpInstanceID", "").ToString();
int fMediaSubType = Convert.ToInt32(rKey.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)
{
throw new Exception(ex.Message);
}
return macAddress;
}
}
}
3 加密与解密算法
加密方法包括:①秘钥加密(KeyA+keyB)、②MD5加密。基于C#的加密与解密算法如下:
using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;
namespace RWRegister
{
public enum CryptoKey
{
KeyA, KeyB
}
public class Encryption
{
private string KeyA = "Sgg***";
private string KeyB = "Qing***";
private string MD5strBegin = "C++***";
private string MD5strEnd = "Matlab***";
private string ExecuteKey = string.Empty;
public Encryption()
{
InitKey();//KeyA
}
public Encryption(CryptoKey Key)
{
InitKey(Key);//Custom
}
private void InitKey(CryptoKey Key = CryptoKey.KeyA)
{
switch (Key)
{
case CryptoKey.KeyA:
ExecuteKey = KeyA;
break;
case CryptoKey.KeyB:
ExecuteKey = KeyB;
break;
}
}
public string EncryptOfKey(string str)
{
return Encrypt(str, ExecuteKey);
}
public string DecryptOfKey(string str)
{
return Decrypt(str, ExecuteKey);
}
public string EncryptOfMD5(string str)
{
str = string.Concat(MD5strBegin, str, MD5strEnd);//trim
MD5 md5 = new MD5CryptoServiceProvider();
byte[] fromdata = Encoding.Unicode.GetBytes(str);
byte[] todata = md5.ComputeHash(fromdata);
string MD5str = string.Empty;
foreach (var data in todata)
{
MD5str += data.ToString("x2");
}
return MD5str;
}
private string Encrypt(string str, string sKey)
{
DESCryptoServiceProvider DESCsp = new DESCryptoServiceProvider();
byte[] InputBytes = Encoding.Default.GetBytes(str);
DESCsp.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DESCsp.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, DESCsp.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(InputBytes, 0, InputBytes.Length);
cs.FlushFinalBlock();
StringBuilder builder = new StringBuilder();
foreach (byte b in ms.ToArray())
{
builder.AppendFormat("{0:X2}", b);
}
builder.ToString();
return builder.ToString();
}
private string Decrypt(string pToDecrypt, string sKey)
{
DESCryptoServiceProvider DESCsp = new DESCryptoServiceProvider();
byte[] InputBytes = new byte[pToDecrypt.Length / 2];
for (int x = 0; x < pToDecrypt.Length / 2; x++)
{
int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
InputBytes[x] = (byte)i;
}
DESCsp.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DESCsp.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, DESCsp.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(InputBytes, 0, InputBytes.Length);
cs.FlushFinalBlock();
return Encoding.Default.GetString(ms.ToArray());
}
}
}
4 软件授权检测
软件授权检测代码如下:
using System;
using System.Collections.Generic;
using System.IO;
namespace RWRegister
{
public class Register
{
public static string CryptographFile = "Cryptograph.Key";
public static string LicenseFile = "license.Key";
public static void WriteCryptographFile(string info)
{
WriteFile(info, CryptographFile);
}
public static void WriteLicenseFile(string info)
{
WriteFile(info, LicenseFile);
}
public static string ReadCryptographFile()
{
return ReadFile(CryptographFile);
}
public static string ReadLicenseFile()
{
return ReadFile(LicenseFile);
}
public static bool ExistCryptographFile()
{
return File.Exists(CryptographFile);
}
public static bool ExistLicenseFile()
{
return File.Exists(LicenseFile);
}
private static void WriteFile(string info, string fileName)
{
try
{
using (StreamWriter writer = new StreamWriter(fileName, false))
{
writer.Write(info);
writer.Close();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private static string ReadFile(string fileName)
{
string info = string.Empty;
try
{
using (StreamReader reader = new StreamReader(fileName))
{
info = reader.ReadToEnd();
reader.Close();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return info;
}
public static bool CheckRegister()
{
//MD5 Cryptograph of Computer information
string CryptoInfo = Computer.ComputerInfo();
Encryption encryptor = new Encryption(CryptoKey.KeyA);
CryptoInfo = encryptor.EncryptOfKey(CryptoInfo);//KeyA
string MD5CryptoInfo = encryptor.EncryptOfMD5(CryptoInfo);//MD5
//judge the exist of Cryptograph file
if (!ExistCryptographFile() || CryptoInfo != ReadCryptographFile())
{
WriteCryptographFile(CryptoInfo);
}
//judge the exist of License file
if (!ExistLicenseFile())
{
return false;
}
//MD5 Cryptograph of License file
string MD5License = ReadLicenseFile();
encryptor = new Encryption(CryptoKey.KeyB);
MD5License = encryptor.DecryptOfKey(MD5License);//KeyB
if (MD5License == MD5CryptoInfo)//two md5 clash
{
return true;
}
else
{
return false;
}
}
}
}
5 示例程序
5.1 界面设计
示例程序界面设计如下图,包括:① “文件(F)” 菜单(包含“数据”、“退出”子菜单);② “帮助(H)” 菜单(包含“帮助文档”、“软件注册”子菜单)。软件开启时,将自动检测授权情况,若未授权仅有20秒的试用时间(20秒后将禁用软件);若软件未授权,可按 “帮助”->“软件注册”步骤 进行授权。
5.2 模块代码
模块代码如下,包括窗体载入、软件注册等。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
namespace RWRegister
{
public partial class softWare : Form
{
public static bool registerState = false;
private const int trialRunTime = 20;//seconds
public softWare()
{
InitializeComponent();
}
private void softWare_Load(object sender, EventArgs e)
{
MyTimer.Enabled = true;
MyTimer.Interval = 1000;
toolStripSLTime.Text = "";
//软件授权检测
if (Register.CheckRegister())
{
registerState = true;
}
else
{
softWareTrialRun();
}
}
/// <summary>
/// 试运行软件(后台线程)
/// </summary>
private void softWareTrialRun()
{
Thread threadClose = new Thread(softWareClose);
threadClose.IsBackground = true;//后台
threadClose.Start();
}
private void softWareClose()
{
int count = 0;
while (!registerState && count < trialRunTime)
{
if (registerState)
{
return;
}
Thread.Sleep(1000);//1 sec
count += 1;
}
if (registerState)
{
return;
}
else
{
Environment.Exit(0);
}
}
private void toolStripMExit_Click(object sender, EventArgs e)
{
Environment.Exit(0);
}
private void toolStripMRegister_Click(object sender, EventArgs e)
{
if (registerState)
{
MessageBox.Show("软件已注册授权!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
string fileName = string.Empty;
ofdLicense.Title = "打开许可文件";
ofdLicense.Filter = "许可文件(*.Key)|*.Key";
if (ofdLicense.ShowDialog() == DialogResult.OK)
{
fileName = ofdLicense.FileName;
}
else
{
return;
}
string localFileName = string.Concat(
Environment.CurrentDirectory,
Path.DirectorySeparatorChar,
Register.LicenseFile);
if (fileName != localFileName)
File.Copy(fileName, localFileName, true);
if (Register.CheckRegister())
{
registerState = true;
MessageBox.Show("注册成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("许可文件非法!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void MyTimer_Tick(object sender, EventArgs e)
{
toolStripSLTime.Text = "本地时间:" + DateTime.Now.ToString();//北京时间
}
}
}
5.3 完整代码下载
文档资源:基于C#的软件加密、授权与注册 货真价实、童叟无欺,欢迎指导交流学习!