Thursday 1 September 2011

Generate Random bytes using C#

There is a quick way to generate random bytes for any given size using .Net framework. Why people would want to do so? I personally find it very handy in case I need to test network flow, encryption and/or do load/stress testing. Here is the code that you can past to your project. It generate a random bytes array for the given size.
 
public static byte[] GenerateRandomBytes(int length)
{
      // Create a buffer
      byte[] randBytes;
 
      if (length >= 1)
       {
            randBytes = new byte[length];
        }
        else
        {
            randBytes = new byte[1];
        }

        // Create a new RNGCryptoServiceProvider.
        System.Security.Cryptography.RNGCryptoServiceProvider rand = 
             new System.Security.Cryptography.RNGCryptoServiceProvider();

        // Fill the buffer with random bytes.
        rand.GetBytes(randBytes);

        // return the bytes.
        return randBytes;
}
 
 

No comments:

Post a Comment