Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling a list with random bytes

I'm trying to fill a buffer with random bytes. The buffer is defined as a list of bytes. This is something that I want to keep as it is. Here is the definition:

namespace NameofProject
{
    public partial class Form1 : Form
    {
    List<byte> buff = new List<byte>();
    }

}

And my first attempt is

public static void RandomFillBuffer()
{
   Random rnd = new Random();
   rnd.NextBytes(buff);
}

Yet this gives such an error for buff: An object reference is required for the non-static field, method, or property 'Form1.buff'

Then I just deleted the word "static" (I am not sure whether this is true) and it becomes "public void RandomFillBuffer()", but this time I am getting this error for buff: Argument 1: cannot convert from 'System.Collections.Generic.List' to 'byte[]'

I'd appreciate any help to solve any of the 2 errors if they make sense.

like image 889
mrq Avatar asked Aug 30 '17 15:08

mrq


People also ask

How do you generate Random bytes in Python?

urandom() method is used to generate a string of size random bytes suitable for cryptographic use or we can say this method generates a string containing random characters. Return Value: This method returns a string which represents random bytes suitable for cryptographic use.

How do you generate a Random byte array?

util. Random. nextBytes() method generates random bytes and provides it to the user defined byte array. where bytes is the byte array.

What are Random bytes?

random-bytes()The number of bytes of the generated string. Use a value in the range 1 - 2000000000.

How Random function works in c#?

How does C# random Work? Whenever there is a need to generate random integers by making use of predefined methods, we make use of Random class in C#. The next () method is the most commonly used method in the Random class to generate random integers which can be overloaded in three forms.


2 Answers

You're getting that problem because NextBytes() expects an array, but you're trying to pass a List<>. One way to solve it would be to change your List<> to an array:

byte[] buff = new byte[someSize];

You're going to have to figure out what someSize should be (it's up to you). You can't fill something without it having a size. Otherwise, how would it know when it's done?

like image 160
itsme86 Avatar answered Oct 03 '22 07:10

itsme86


The problem you are having is that NextBytes fills an array[] not a list. You need to define an array with an index of its size

    // Put random bytes into this array.
    byte[] array = new byte[8];
    // Fill array with random bytes.
    Random random = new Random();
    random.NextBytes(array);
like image 20
Sam Marion Avatar answered Oct 03 '22 06:10

Sam Marion