C#中随机生成的十六进制数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1054076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 07:07:02  来源:igfitidea点击:

Randomly generated hexadecimal number in C#

c#randomhex

提问by shizbiz

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

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

采纳答案by Mehrdad Afshari

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");
}

回答by womp

    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.

random.Next() 接受让您指定最小值和最大值的参数,因此您将如何控制长度。

回答by KristoferA

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).

取决于您想要它的随机程度,但这里有 3 种选择:1)我通常只使用 Guid.NewGuid 并选择其中的一部分(取决于我想要的数量)。

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

2)System.Random(见其他回复)如果你只是想要“足够随机”就很好。

3) System.Security.Cryptography.RNGCryptoServiceProvider

3) System.Security.Cryptography.RNGCryptoServiceProvider

回答by Vippy

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

这是一个将返回 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;
}

回答by Rüdiger

.... with LINQ

.... 使用 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")));
}

回答by Dave

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

如果您希望它是加密安全的,您应该使用 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")));
}

回答by auser8y

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

创建一个 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);

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:

你考虑过 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);

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.

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

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

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

回答by grooveplex

I needed something similar to Python's secrets.token_hexfunction.

我需要类似于 Pythonsecrets.token_hex函数的东西。

If you need random bytes that are cryptographically secure, you can use RNGCryptoServiceProviderin the System.Security.Cryptographynamespace, like so:

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

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:

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

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

The output might look like this:

输出可能如下所示:

7fb70c709a5eed32d37ed5771f09c0fe