Pregunta

necesito en mi programa para atar una licencia a un identificador de hardware. He intentado utilizar WMI, pero sigue siendo lento.

necesito, por ejemplo, CPU, disco duro, y la información de la placa base.

¿Fue útil?

Solución

Para más detalles consulte este enlace

El siguiente código le dará CPU ID:

espacio de nombres requerido System.Management

var mbs = new ManagementObjectSearcher("Select ProcessorId From Win32_processor");
ManagementObjectCollection mbsList = mbs.Get();
string id = "";
foreach (ManagementObject mo in mbsList)
{
    id = mo["ProcessorId"].ToString();
    break;
}

Para la identificación del disco duro y los datos de identificación de la placa base se refieren este enlace

Para acelerar este procedimiento, asegúrese de que no utiliza SELECT *, pero sólo seleccionar lo que realmente necesita. Uso SELECT * sólo durante el desarrollo cuando intenta averiguar lo que necesita para su uso, ya continuación, la consulta se llevará a más más tiempo en completarse.

Otros consejos

he llegado hasta aquí en busca de lo mismo y he encontrado otra solución. Si está interesado ustedes comparto esta clase:

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
    }
}

No tendrá ningún crédito por esto porque me encontré aquí Se trabajó más rápido de lo que esperaba para mí. Sin la tarjeta gráfica, mac y de ID de la unidad me dieron el identificador único en unos 2-3 segundos. Con los de arriba se incluye lo tengo en unos 4-5 segundos.

Nota:. Añadir referencia a System.Management

El siguiente enfoque se inspiró en esta respuesta a una pregunta relacionada (más general).

El método consiste en leer el valor MachineGuid en HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography clave de registro. Este valor se genera durante la instalación del sistema operativo.

Hay pocas maneras de evitar la singularidad del Hardware-ID por máquina utilizando este enfoque. Un método está editando el valor del registro, pero esto podría causar complicaciones en la máquina del usuario después. Otro método consiste en clonar una imagen de unidad que copiar el valor MachineGuid.

Sin embargo, ningún enfoque es a prueba de hackers y esto sin duda será lo suficientemente bueno para los usuarios normales. En el lado positivo, este método es rápido en cuanto al rendimiento y fácil de implementar.

public string GetMachineGuid()
{
   string location = @"SOFTWARE\Microsoft\Cryptography";
   string name = "MachineGuid";

   using (RegistryKey localMachineX64View = 
       RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
   {
       using (RegistryKey rk = localMachineX64View.OpenSubKey(location))
       {
           if (rk == null)
               throw new KeyNotFoundException(
                   string.Format("Key Not Found: {0}", location));

           object machineGuid = rk.GetValue(name);
           if (machineGuid == null)
               throw new IndexOutOfRangeException(
                   string.Format("Index Not Found: {0}", name));

           return machineGuid.ToString();
       }
   }
}

Aquí es un DLL que muestra:
* Disco duro de identificación (número de serie de hardware único escrito en chip electrónico IDE de la unidad)
* Partición ID (número de serie de volumen)
* CPU ID (identificador de hardware exclusivo)
* CPU proveedor
* Velocidad de la CPU ejecuta Windows * CPU teórico de velocidad
* La carga de memoria (memoria total utilizada en porcentaje (%))
* El total de Física (memoria física total en bytes)
* Disponibilidad física (memoria física dada en bytes)
* El total de archivo de paginación (archivo de paginación total en bytes)
* Disponible de archivo de paginación (archivo de página a la izquierda en bytes)
* Virtual (memoria virtual total en bytes) Total
* Disponible virtual (memoria virtual a la izquierda en bytes)
* Bios identificación única numberBiosDate
* Bios identificación única numberBiosVersion
* Bios identificación única numberBiosProductID
* Bios único numberBiosVideo identificación

(texto agarró desde el sitio web original)
Funciona con C #.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top