shizbiz
shizbiz

Reputation: 577

Randomly generated hexadecimal number in C#

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

Upvotes: 39

Views: 44415

Answers (9)

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.

Upvotes: 1

womp
womp

Reputation: 116977

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.

Upvotes: 23

KristoferA
KristoferA

Reputation: 12397

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

Upvotes: 10

grooveplex
grooveplex

Reputation: 2529

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

Upvotes: 6

auser8y
auser8y

Reputation: 72

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.

Upvotes: -1

Dave
Dave

Reputation: 10924

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

Upvotes: 3

Rüdiger
Rüdiger

Reputation: 1763

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

Upvotes: 4

Vippy
Vippy

Reputation: 1422

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

Upvotes: 2

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422076

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

Upvotes: 63

Related Questions