C#生成设备机器码(MachineCode)公共方法类

机器码可以用于限制软件使用的设备,通常用于订阅类得收费软件,根据电脑的CPU序列号、硬盘序列号、网卡序列号等不会更改的标识,进行md5或者其他加密,最后生成一个每台电脑唯一的值来判定是否有软件的授权,进行软件的使用限制。

实例代码:

public class MachineCode
{

    static MachineCode machineCode;

    public static string GetMachineCodeString()
    {
        string machineCodeString = string.Empty;
        if (machineCode == null)
        {
            machineCode = new MachineCode();
        }
        machineCodeString = "PC." + machineCode.GetCpuInfo() + "." +
                            machineCode.GetHDid() + "." +
                            machineCode.GetMoAddress();
        return machineCodeString;
    }

    ///   <summary> 
    ///   获取cpu序列号     
    ///   </summary> 
    ///   <returns> string </returns> 
    public string GetCpuInfo()
    {
        string cpuInfo = "";
        try
        {
            using (ManagementClass cimobject = new ManagementClass("Win32_Processor"))
            {
                ManagementObjectCollection moc = cimobject.GetInstances();

                foreach (ManagementObject mo in moc)
                {
                    cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
                    mo.Dispose();
                }
            }
        }
        catch (Exception)
        {
            throw;
        }
        return cpuInfo.ToString();
    }

    ///   <summary> 
    ///   获取硬盘ID     
    ///   </summary> 
    ///   <returns> string </returns> 
    public string GetHDid()
    {
        string HDid = "";
        try
        {
            using (ManagementClass cimobject1 = new ManagementClass("Win32_DiskDrive"))
            {
                ManagementObjectCollection moc1 = cimobject1.GetInstances();
                foreach (ManagementObject mo in moc1)
                {
                    HDid = (string)mo.Properties["Model"].Value;
                    mo.Dispose();
                }
            }
        }
        catch (Exception)
        {

            throw;
        }
        return HDid.ToString();
    }

    ///   <summary> 
    ///   获取网卡硬件地址 
    ///   </summary> 
    ///   <returns> string </returns> 
    public string GetMoAddress()
    {
        string MoAddress = "";
        try
        {
            using (ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"))
            {
                ManagementObjectCollection moc2 = mc.GetInstances();
                foreach (ManagementObject mo in moc2)
                {
                    if ((bool)mo["IPEnabled"] == true)
                        MoAddress = mo["MacAddress"].ToString();
                    mo.Dispose();
                }
            }
        }
        catch (Exception)
        {
            throw;
        }
        return MoAddress.ToString();
    }
}

使用方法:

调取 GetMachineCodeString() 获取网卡序列号、CPU序列号、硬盘序列号,然后再加入自己设定的一些值,通过自己熟悉的加密方式,例如MD5,生成最终的机器码即可。

注意事项:

该机器码生成后,若遇到系统重装或者格式化硬盘等情况,则有可能造成机器码失效,这时候可能需要重新进行机器码生成并完成授权。

使用示例:

THE END