Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SecureRandom in C#

Tags:

java

c#

Here is the java code:

SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(someBytes);//someBytes is the seed

Is there any equal method in C#? What I have get is not correct:

RandomNumberGenerator rng = RNGCryptoServiceProvider.Create();
rng.GetBytes(someBytes);// out someBytes

I do need the seed, because the java code did, I have to translate the java code into C#. When I pass the same seed, the sequence I get from C# must equal with the java.

like image 294
user1654475 Avatar asked Nov 20 '12 01:11

user1654475


People also ask

What is SecureRandom?

public SecureRandom(byte[] seed) Constructs a secure random number generator (RNG) implementing the default random number algorithm. The SecureRandom instance is seeded with the specified seed bytes. This constructor traverses the list of registered security Providers, starting with the most preferred Provider.

How does SecureRandom work?

Every instance of SecureRandom is created with an initial seed. It works as a base for providing random values and changes every time we generate a new value. Using the new operator or calling SecureRandom. getInstance() will get the default seed from /dev/urandom.

What library is rand () in C?

1.1. The rand function, declared in stdlib. h, returns a random integer in the range 0 to RAND_MAX (inclusive) every time you call it. On machines using the GNU C library RAND_MAX is equal to INT_MAX or 231-1, but it may be as small as 32767.

How do you randomize a value in C?

The rand() and srand() functions are used to generate random numbers in C/C++ programming languages. The rand() function gives same results on every execution because the srand() value is fixed to 1.


1 Answers

The abstract class System.Security.Cryptography.RandomNumberGenerator and its concrete implementations do not expose a method for setting a seed to the developer (though internally, I suspect they do in fact use one.)

The design rationale there was, I suspect, that repeatability does not make for a 'cryptographically strong' stream of random values.

If you look at the concrete implementation, RNGCryptoServiceProvider, while it does expose a constructor accepting a byte[] to presumably initialize the PRNG, its documentation says

This value is ignored.

And the remarks go on to say

This method does not directly initialize the RNGCryptoServiceProvider class. Calling this method is equivalent to calling the RNGCryptoServiceProvider constructor and passing null.

For information on the sort of stuff that goes into the seed that's used, see the MSDN documentation for CryptGenRandom

like image 148
Nicholas Carey Avatar answered Sep 25 '22 08:09

Nicholas Carey