# Is it safe to combine System.Random with cryptographically secure pseudo-random number generators?

Have a look at the following codesample written in C#:

private static byte[] GetRandomBytes(int size)
{
byte[] buff = new byte[size];
// Create an array of crypto-secure random numbers
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
rng.GetBytes(buff);
}

// Gets a random byte from a non-crypto-secure RNG and xors each element with it
// Alternatively, xor each element with a new random number
int unsafeRand = (byte)_random.Next(0, 255);
for (int i = 0; i < size; i++)
buff[i] ^= unsafeRand;

return buff;
}


Is it safe to combine the .NET cryptographically secure random number generators with an imperfect random number generator, for example via XOR?

• You do understand that the code you provided, wouldn't actually generate proper pseudo-random generated numbers, right? There are several reasons for that, far to many to list, even in an answer honestly. How you fix this code wouldn't be far to complicated for an answer here. – Ramhound Jul 3 '16 at 21:10
• in theory, yes, mixing different source of randomness, one of which could weak/compromised, can still be secure: a bad apple does NOT spoil the whole bunch, provided the data is mixed appropriately. – dandavis Jul 4 '16 at 0:09
• it would be better to concat two chunks and use SHA3 to generate new bytes, if you're not trying to stretch. – dandavis Jul 4 '16 at 0:52
• I have to ask what is the point? What are you trying to do? – otus Jul 4 '16 at 6:56
• An interesting reading about mixing random sources: blog.cr.yp.to/20140205-entropy.html (Daniel J. Berstein) – ddddavidee Jul 4 '16 at 10:17

• I was going to comment: if you have any additional entropy you can use it to reseed RNGCryptoServiceProvider but apparently the user isn't allowed to reseed instances of that class at all - which is weird (it's definitely not the only thing weird about the MS implementation). – Maarten Bodewes Jul 4 '16 at 10:14