c#获取机器唯一识别码的方法记忆

来源:


http://www.cnblogs.com/leestar54/p/4375173.html

前言

在客户端认证的过程中,我们总要获取客户机的唯一识别信息,曾经以为MAC地址是不会变的,但是现在各种改,特别是使用无线上网卡,MAC地址插一次变一次,所以这样使用MAC就没有什么意义了,怎么办,又开始求助Google,最后找到一个折中的方案

原理

通过获取主板、处理器、BIOS、mac、显卡、硬盘等的ID生成唯一识别码

建议

1、使用那些不经常更换的模块来生成识别码。

2、如果经常更换MAC,显卡,硬盘,则不要使用这些ID。

3、确保使用static变量在整个应用来保存唯一识别码。

实现

复制代码
using System;
using System.Management;
using System.Security.Cryptography;
using System.Security;
using System.Collections;
using System.Text;
namespace Security
{
    /// <summary>
    /// Generates a 16 byte Unique Identification code of a computer
    /// Example: 4876-8DB5-EE85-69D3-FE52-8CF7-395D-2EA9
    /// </summary>
    public class FingerPrint  
    {
        private static string fingerPrint = string.Empty;
        public static string Value()
        {
            if (string.IsNullOrEmpty(fingerPrint))
            {
                fingerPrint = GetHash("CPU >> " + cpuId() + "\nBIOS >> " + 
            biosId() + "\nBASE >> " + baseId()
                            //+"\nDISK >> "+ diskId() + "\nVIDEO >> " + 
            videoId() +"\nMAC >> "+ macId()
                                     );
            }
            return fingerPrint;
        }
        private static string GetHash(string s)
        {
            MD5 sec = new MD5CryptoServiceProvider();
            ASCIIEncoding enc = new ASCIIEncoding();
            byte[] bt = enc.GetBytes(s);
            return GetHexString(sec.ComputeHash(bt));
        }
        private static string GetHexString(byte[] bt)
        {
            string s = string.Empty;
            for (int i = 0; i < bt.Length; i++)
            {
                byte b = bt[i];
                int n, n1, n2;
                n = (int)b;
                n1 = n & 15;
                n2 = (n >> 4) & 15;
                if (n2 > 9)
                    s += ((char)(n2 - 10 + (int)'A')).ToString();
                else
                    s += n2.ToString();
                if (n1 > 9)
                    s += ((char)(n1 - 10 + (int)'A')).ToString();
                else
                    s += n1.ToString();
                if ((i + 1) != bt.Length && (i + 1) % 2 == 0) s += "-";
            }
            return s;
        }
        #region Original Device ID Getting Code
        //Return a hardware identifier
        private static string identifier
        (string wmiClass, string wmiProperty, string wmiMustBeTrue)
        {
            string result = "";
            System.Management.ManagementClass mc = 
        new System.Management.ManagementClass(wmiClass);
            System.Management.ManagementObjectCollection moc = mc.GetInstances();
            foreach (System.Management.ManagementObject mo in moc)
            {
                if (mo[wmiMustBeTrue].ToString() == "True")
                {
                    //Only get the first one
                    if (result == "")
                    {
                        try
                        {
                            result = mo[wmiProperty].ToString();
                            break;
                        }
                        catch
                        {
                        }
                    }
                }
            }
            return result;
        }
        //Return a hardware identifier
        private static string identifier(string wmiClass, string wmiProperty)
        {
            string result = "";
            System.Management.ManagementClass mc = 
        new System.Management.ManagementClass(wmiClass);
            System.Management.ManagementObjectCollection moc = mc.GetInstances();
            foreach (System.Management.ManagementObject mo in moc)
            {
                //Only get the first one
                if (result == "")
                {
                    try
                    {
                        result = mo[wmiProperty].ToString();
                        break;
                    }
                    catch
                    {
                    }
                }
            }
            return result;
        }
        private static string cpuId()
        {
            //Uses first CPU identifier available in order of preference
            //Don't get all identifiers, as it is very time consuming
            string retVal = identifier("Win32_Processor", "UniqueId");
            if (retVal == "") //If no UniqueID, use ProcessorID
            {
                retVal = identifier("Win32_Processor", "ProcessorId");
                if (retVal == "") //If no ProcessorId, use Name
                {
                    retVal = identifier("Win32_Processor", "Name");
                    if (retVal == "") //If no Name, use Manufacturer
                    {
                        retVal = identifier("Win32_Processor", "Manufacturer");
                    }
                    //Add clock speed for extra security
                    retVal += identifier("Win32_Processor", "MaxClockSpeed");
                }
            }
            return retVal;
        }
        //BIOS Identifier
        private static string biosId()
        {
            return identifier("Win32_BIOS", "Manufacturer")
            + identifier("Win32_BIOS", "SMBIOSBIOSVersion")
            + identifier("Win32_BIOS", "IdentificationCode")
            + identifier("Win32_BIOS", "SerialNumber")
            + identifier("Win32_BIOS", "ReleaseDate")
            + identifier("Win32_BIOS", "Version");
        }
        //Main physical hard drive ID
        private static string diskId()
        {
            return identifier("Win32_DiskDrive", "Model")
            + identifier("Win32_DiskDrive", "Manufacturer")
            + identifier("Win32_DiskDrive", "Signature")
            + identifier("Win32_DiskDrive", "TotalHeads");
        }
        //Motherboard ID
        private static string baseId()
        {
            return identifier("Win32_BaseBoard", "Model")
            + identifier("Win32_BaseBoard", "Manufacturer")
            + identifier("Win32_BaseBoard", "Name")
            + identifier("Win32_BaseBoard", "SerialNumber");
        }
        //Primary video controller ID
        private static string videoId()
        {
            return identifier("Win32_VideoController", "DriverVersion")
            + identifier("Win32_VideoController", "Name");
        }
        //First enabled network card ID
        private static string macId()
        {
            return identifier("Win32_NetworkAdapterConfiguration", 
                "MACAddress", "IPEnabled");
        }
        #endregion
    }
}
复制代码

 

参考

http://www.codeproject.com/Articles/28678/Generating-Unique-Key-Finger-Print-for-a-Computer

 

补充

现在遇到一些平板等简陋的机型,竟然获取到的所有设备标识都一样(除了mac),最后只好在本地再生成一个软件自身的标识,然后每次在计算标识的时候附带上,这样不会再重复了吧。

代码如下:

复制代码
        private static string localkey()
        {
            string path=Environment.CurrentDirectory + "client.key";
            if (File.Exists(path))
            {
                StreamReader sr = new StreamReader(path);
                string key= sr.ReadToEnd();
                sr.Close();
                return key;
            }
            else
            {
                StreamWriter sw = File.CreateText(path);
                string key = Guid.NewGuid().ToString();
                sw.WriteLine(key);
                sw.Close();
                return key;
            }
        }
复制代码

可以再把该文件设为隐藏等手段,防止用户误操作。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#获取硬件的唯一标识可以使用`System.Management`命名空间中的`ManagementObjectSearcher`类和`Win32_ComputerSystemProduct`类来实现。 首先,您需要在代码文件中添加对`System.Management`命名空间的引用: ```csharp using System.Management; ``` 然后,可以使用以下代码获取计算机系统产品的唯一标识: ```csharp public static string GetHardwareUniqueID() { string hardwareID = string.Empty; ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystemProduct"); ManagementObjectCollection collection = searcher.Get(); foreach (ManagementObject obj in collection) { hardwareID = obj.Properties["UUID"].Value.ToString(); break; // 只获取第一个计算机系统产品 } return hardwareID; } ``` 上述代码使用了`ManagementObjectSearcher`类来搜索并获取`Win32_ComputerSystemProduct`类的实例。然后,通过遍历集合获取第一个实例,并从中获取唯一标识属性(UUID)的值。 请注意,获取的硬件唯一标识可能因不同硬件和操作系统而异。在某些情况下,可能无法获取唯一标识或者获取到的标识不是硬件相关的。此外,需要以管理员权限运行应用程序才能访问这些硬件信息。 另外,硬件唯一标识不适合用于身份验证或安全目的。它仅用于标识硬件设备,并不保证其唯一性。如果需要进行身份验证或安全相关的操作,建议使用其他更可靠的方法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值