C# 随机生成十六进制数

发布于 2024-07-26 10:19:01 字数 34 浏览 3 评论 0原文

如何使用 C# 生成具有我选择的长度的随机十六进制数?

How can I generate a random hexadecimal number with a length of my choice using C#?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

绮烟 2024-08-02 10:19:01
static Random random = new Random();
public static string GetRandomHexNumber(int digits)
{
    byte[] buffer = new byte[digits / 2];
    random.NextBytes(buffer);
    string result = String.Concat(buffer.Select(x => x.ToString("X2")).ToArray());
    if (digits % 2 == 0)
        return result;
    return result + random.Next(16).ToString("X");
}
static Random random = new Random();
public static string GetRandomHexNumber(int digits)
{
    byte[] buffer = new byte[digits / 2];
    random.NextBytes(buffer);
    string result = String.Concat(buffer.Select(x => x.ToString("X2")).ToArray());
    if (digits % 2 == 0)
        return result;
    return result + random.Next(16).ToString("X");
}
玻璃人 2024-08-02 10:19:01
Random random = new Random();
int num = random.Next();
string hexString = num.ToString("X");

random.Next() 接受可让您指定最小值和最大值的参数,这样您就可以控制长度。

Random random = new Random();
int num = random.Next();
string hexString = num.ToString("X");

random.Next() takes arguments that let you specify a min and a max value, so that's how you would control the length.

筱果果 2024-08-02 10:19:01

取决于您想要的随机程度,但这里有 3 个替代方案:

  1. 我通常只使用 Guid.NewGuid 并选择其中的一部分(取决于我想要的数字大小)。

  2. 如果您只想“足够随机”,System.Random(请参阅其他回复)很好。

  3. 系统.Security.Cryptography.RNGCryptoServiceProvider

Depends on how random you want it, but here are 3 alternatives:

  1. I usually just use Guid.NewGuid and pick a portion of it (dep. on how large number I want).

  2. System.Random (see other replies) is good if you just want 'random enough'.

  3. System.Security.Cryptography.RNGCryptoServiceProvider

愿得七秒忆 2024-08-02 10:19:01

我需要类似于 Python 的 secrets.token_hex< /a> 函数。

如果您需要加密安全的随机字节,可以使用 System.Security.Cryptography 命名空间中的 RNGCryptoServiceProvider ,如下所示:

using var csprng = new RNGCryptoServiceProvider();
var bytes = new byte[16];

csprng.GetNonZeroBytes(bytes); // or csprng.GetBytes(…)

要将字节数组转换为十六进制字符串,使用 LINQ 似乎是最易读的选项:

string.Join("", bytes.Select(b => b.ToString("x2"))); // or "X2" for upper case

输出可能如下所示:

7fb70c709a5eed32d37ed5771f09c0fe

I needed something similar to Python's secrets.token_hex function.

If you need random bytes that are cryptographically secure, you can use RNGCryptoServiceProvider in the System.Security.Cryptography namespace, like so:

using var csprng = new RNGCryptoServiceProvider();
var bytes = new byte[16];

csprng.GetNonZeroBytes(bytes); // or csprng.GetBytes(…)

To convert the byte array to a hexadecimal string, using LINQ seems like the most readable option:

string.Join("", bytes.Select(b => b.ToString("x2"))); // or "X2" for upper case

The output might look like this:

7fb70c709a5eed32d37ed5771f09c0fe
独自唱情﹋歌 2024-08-02 10:19:01

....使用 LINQ

private static readonly Random _RND = new Random();

public static string GenerateHexString(int digits) {
    return string.Concat(Enumerable.Range(0, digits).Select(_ => _RND.Next(16).ToString("X")));
}

.... with LINQ

private static readonly Random _RND = new Random();

public static string GenerateHexString(int digits) {
    return string.Concat(Enumerable.Range(0, digits).Select(_ => _RND.Next(16).ToString("X")));
}
£噩梦荏苒 2024-08-02 10:19:01

如果您希望它是加密安全的,您应该使用 RNGCryptoServiceProvider。

public static string BuildSecureHexString(int hexCharacters)
{
    var byteArray = new byte[(int)Math.Ceiling(hexCharacters / 2.0)];
    using (var rng = new RNGCryptoServiceProvider())
    {
        rng.GetBytes(byteArray);
    }
    return String.Concat(Array.ConvertAll(byteArray, x => x.ToString("X2")));
}

If you want it to be a cryptographically secure you should use RNGCryptoServiceProvider.

public static string BuildSecureHexString(int hexCharacters)
{
    var byteArray = new byte[(int)Math.Ceiling(hexCharacters / 2.0)];
    using (var rng = new RNGCryptoServiceProvider())
    {
        rng.GetBytes(byteArray);
    }
    return String.Concat(Array.ConvertAll(byteArray, x => x.ToString("X2")));
}
白云悠悠 2024-08-02 10:19:01

下面的代码将返回 256 位十六进制字符串 (8x8=256):

private static string RandomHexString()
{
    // 64 character precision or 256-bits
    Random rdm = new Random();
    string hexValue = string.Empty;
    int num;

    for (int i = 0; i < 8; i++)
    {
        num = rdm.Next(0, int.MaxValue);
        hexValue += num.ToString("X8");
    }

    return hexValue;
}

Here's one that would return a 256-bit hex string (8x8=256):

private static string RandomHexString()
{
    // 64 character precision or 256-bits
    Random rdm = new Random();
    string hexValue = string.Empty;
    int num;

    for (int i = 0; i < 8; i++)
    {
        num = rdm.Next(0, int.MaxValue);
        hexValue += num.ToString("X8");
    }

    return hexValue;
}
谁许谁一生繁华 2024-08-02 10:19:01

从 2023 年 11 月 14 日至 16 日发布的 .NET 8 开始,您可以使用 System.Security.Cryptography 中的新方法:

RandomNumberGenerator.GetHexString(int stringLength, bool lowercase = false);

Microsoft 声明:

创建一个由加密随机十六进制字符填充的字符串。

这应该是前进的最佳方法。

As of .NET 8, which releases Nov. 14-16, 2023, you can use the new method from System.Security.Cryptography:

RandomNumberGenerator.GetHexString(int stringLength, bool lowercase = false);

Microsoft states that:

Creates a string filled with cryptographically random hexadecimal characters.

This should be the best method moving forward.

月依秋水 2024-08-02 10:19:01

创建一个 n 字符(~n/2 字节),随机的十六进制字符串:

var randBytes = new byte[n/2 + n%2>0?1:0];
new Random().NextBytes(randBytes);
var hex = BitConverter.ToString(randBytes).Replace("-", string.Empty).Substring(0,n);

您考虑过 Base64 字符串吗? 根据您的应用程序,它们通常更有用。 它们保证是 ASCII 并为每个输入字节提供约 4/3 个字符。 要创建 n 个字符的字符串:

var randBytes = new byte[(n/4 + n%4>0?1:0)*3];
new Random().NextBytes(randBytes);
var base64 = Convert.ToBase64String(randBytes).Substring(0,n);

显然,如果您的应用程序不需要奇数个十六进制字符或不是 4 个字符的倍数的 Base64,则可以省略 .Substring(0,n)。

正如其他海报所建议的那样,可以通过将 Random() 静态化来随意扩展示例。

Create an n character (~n/2 byte), random string of hex:

var randBytes = new byte[n/2 + n%2>0?1:0];
new Random().NextBytes(randBytes);
var hex = BitConverter.ToString(randBytes).Replace("-", string.Empty).Substring(0,n);

Have you considered Base64 strings? Depending on your application, they can often more useful. They're guaranteed to be ASCII and provide ~4/3 characters per input byte. To create an n character string:

var randBytes = new byte[(n/4 + n%4>0?1:0)*3];
new Random().NextBytes(randBytes);
var base64 = Convert.ToBase64String(randBytes).Substring(0,n);

Obviously, you can omit the .Substring(0,n) if your application does not require either an odd number of hex characters or a Base64 that is not a multiple of 4 characters.

Feel free to extend the examples by making Random() static, as other posters have suggested.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文