C#生成计算机独有的字符串

C# Generating strings unique to the computer

我需要生成的字符串在生成它们的所有机器上都具有极高的唯一性,并且每次代码 运行 时都不同。唯一性的概率不一定是 100%,这与安全无关,只有唯一性很重要(用例是播种大型状态非加密 PRNG)。

我目前的想法是对网络适配器信息进行 SHA512 哈希处理,包括适配器统计信息、计算机名称、进程 ID、以滴答为单位的计算机启动时间和以滴答为单位的 UTC 当前时间,并将其转换为 64 个字符的 base 64 Unicode字符串.

看起来不错,但是否有更好的方法,例如在 .net 函数中,可以做到这一点?

工作代码:

using System;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Security.Cryptography;
using System.Text;

static class UniqueString
{
    private static SHA512 sha = SHA512.Create();

    public static string Gen()
    {
        NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
        StringBuilder uniqueString = new StringBuilder();

        foreach (NetworkInterface adapter in adapters)
        {
            IPInterfaceStatistics stats = adapter.GetIPStatistics();

            uniqueString.AppendFormat("{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10} {11} {12} {13} {14} {15} {16} {17} ",
                adapter.Description,
                adapter.Id,
                adapter.Name,
                adapter.Speed,
                adapter.GetPhysicalAddress(),
                adapter.NetworkInterfaceType,

                stats.BytesReceived,
                stats.BytesSent,
                stats.IncomingPacketsDiscarded,
                stats.IncomingPacketsWithErrors,
                stats.IncomingUnknownProtocolPackets,
                stats.NonUnicastPacketsReceived,
                stats.NonUnicastPacketsSent,
                stats.OutgoingPacketsDiscarded,
                stats.OutgoingPacketsWithErrors,
                stats.OutputQueueLength,
                stats.UnicastPacketsReceived,
                stats.UnicastPacketsSent);
        }

        uniqueString.AppendFormat("{0} {1} {2} {3}",
            Environment.MachineName,
            Process.GetCurrentProcess().Id,
            Environment.TickCount.ToString(),
            DateTime.UtcNow.Ticks);

        return Convert.ToBase64String(sha.ComputeHash(Encoding.Unicode.GetBytes(uniqueString.ToString())), 0, 48);
    }
}

I need to generate strings that have an extremely high probability of being unique on all machines that they're generated on, and be different every time the code is run as well.

让我先警告一下:

人们会立即告诉您使用 GUID,顾名思义,它是全球唯一的标识符。四类guids随机生成

但是,我反对使用 GUID 作为随机源。 GUID 保证 uniqueness,即 all 它们被记录为保证。实际上,是的,第四类 GUID 实际上是由非加密强度的 PRNG 生成的随机 122 位数字。如果您使用 GUID 作为您的随机字符串,您会没事的。但我不会亲自使用标签外的 GUID;我用它们 生成唯一标识符 ,不多也不少。有更好的方法可以解决您的问题。

有关 GUID 的使用和滥用的更多信息,请参阅 https://ericlippert.com/tag/guids/

Seems sound, but are there any better, as in .net functions for example, ways to do this?

正确的方法是使用 RNGCryptoServiceProvider 生成尽可能多的加密强度随机位,因为您需要确保您的标识符是唯一的,然后将其用作你的种子。

您的系统似乎很合理,但您究竟为什么要自己实施它,因为为 Microsoft 工作的专家已经创建了一个系统,该系统可以为具有大量熵的加密强度随机数生成器播种?不要在这里重新发明轮子。