Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create byte array and fill it with random data [duplicate]

Tags:

c#

.net

I want to create a byte array against the given size filled with random data.How can I do that?Signature of my method would be like this:

private byte[]  GetByteArray(int sizeInKb)
    {


    }

This is what I have tried:

private  byte[]  GetByteArray(int sizeInKb)
    {

        var rnd = new Random();
        var bytes = new Byte[sizeInKb*1024];
        rnd.NextBytes(bytes);
        return bytes;
    }

Here I want to return byte array conataining random data against value of sizeInKb. Is my array size correct , when user inputs value in kb e.g. 10 KB.

like image 701
Kumar Avatar asked Aug 24 '26 01:08

Kumar


1 Answers

Try the Random.NextBytes method https://learn.microsoft.com/en-us/dotnet/api/system.random.nextbytes?view=netframework-4.7.2

private byte[] GetByteArray(int sizeInKb)
{
    Random rnd = new Random();
    byte[] b = new byte[sizeInKb * 1024]; // convert kb to byte
    rnd.NextBytes(b);
    return b;
}

If you need cryptographically safe random bytes, use System.Security.Cryptography.RNGCryptoServiceProvider instead.

like image 161
pkatsourakis Avatar answered Aug 25 '26 15:08

pkatsourakis