MasstransferExporter/MasstransferCommon/Utils/DeviceInfoUtil.cs

90 lines
2.4 KiB
C#

using System.Management;
using System.Security.Cryptography;
using System.Text;
namespace MasstransferSecurity.Utils;
/// <summary>
/// 设备信息工具类方法
/// </summary>
public sealed class DeviceInfoUtil
{
public static string GenerateUniqueID()
{
var cpuId = GetCpuId();
var motherboardId = GetMotherboardId();
var diskDriveId = GetDiskDriveId();
var macAddress = GetMacAddress();
var deviceId = $"{cpuId}-{motherboardId}-{diskDriveId}-{macAddress}";
return ComputeSha256Hash(deviceId);
}
private static string GetCpuId()
{
var cpuId = string.Empty;
var searcher = new ManagementObjectSearcher("SELECT ProcessorId FROM Win32_Processor");
foreach (var item in searcher.Get())
{
cpuId = item["ProcessorId"].ToString();
break;
}
return cpuId;
}
private static string GetMotherboardId()
{
var motherboardId = string.Empty;
var searcher = new ManagementObjectSearcher("SELECT SerialNumber FROM Win32_BaseBoard");
foreach (var item in searcher.Get())
{
motherboardId = item["SerialNumber"].ToString();
break;
}
return motherboardId;
}
private static string GetDiskDriveId()
{
string diskDriveId = string.Empty;
var searcher = new ManagementObjectSearcher("SELECT SerialNumber FROM Win32_DiskDrive");
foreach (var item in searcher.Get())
{
diskDriveId = item["SerialNumber"].ToString();
break;
}
return diskDriveId;
}
private static string GetMacAddress()
{
string macAddress = string.Empty;
var searcher = new ManagementObjectSearcher(
"SELECT MACAddress FROM Win32_NetworkAdapter WHERE MACAddress IS NOT NULL AND NOT (MACAddress LIKE '')");
foreach (var item in searcher.Get())
{
macAddress = item["MACAddress"].ToString();
break;
}
return macAddress.Replace(":", string.Empty);
}
private static string ComputeSha256Hash(string rawData)
{
using SHA256 sha256Hash = SHA256.Create();
var bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));
var builder = new StringBuilder();
foreach (var t in bytes)
{
builder.Append(t.ToString("x2"));
}
return builder.ToString();
}
}