简体   繁体   中英

SecureRandom in 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.

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

According to the MSDN docs for RNGCryptoServiceProvider there doesn't appear to be a way to manually seed it with values yourself. There are constructors that take a byte[] and string , but both of those arguments are ignored .

This doesn't matter, because any random number generator worth its weight in salt will properly seed itself upon creation. Any value you provide is unlikely to be any better than the internal seeding mechanism (which is probably a high-resolution time-derived value).

RNGCryptoServiceProvider类不需要手动播种。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM