35

I cannot find the System.Security.Cryptography.RNGCryptoServiceProvider class in .NetCore.

It is essential to the application I am trying to port from .Net Framework, as it is being used to generate an initialisation vector for encryption.

Does it exist under a different name, or is there another way of achieving this functionality?

demonplus
  • 5,613
  • 12
  • 49
  • 68
Hughgo
  • 1,319
  • 5
  • 17
  • 26

3 Answers3

54

System.Security.Cryptography.RandomNumberGenerator is the base class for Cryptographically-Secure Pseudo-Random Number Generator (CSPRNG) implementations. In .NET Framework RandomNumberGenerator.Create() returns an RNGCryptoServiceProvider instance (unless configured differently by CryptoConfig). In .NET Core RandomNumberGenerator.Create() returns an opaque type which is based on BCryptGenRandom (Windows) or OpenSSL's random number generator (!Windows).

RandomNumberGenerator.Create() is the only way to get an RNG instance on .NET Core, and since it works on both .NET Core and .NET Framework is the most portable.

Of course, if you're generating an IV, you can also just call the instance method SymmetricAlgorithm.GenerateIV() to have it use the CSPRNG internally; though as the documentation says, calling it is unnecessary as a random IV is created with the instance (GenerateIV can be used to force it to generate a new one before the next call to CreateEncryptor).

VMAtm
  • 27,943
  • 17
  • 79
  • 125
bartonjs
  • 30,352
  • 2
  • 71
  • 111
8

One of the solutions suggested is to use RandomNumberGenerator.Create() https://github.com/dotnet/corefx/issues/2881

Ivan Zaruba
  • 4,236
  • 5
  • 20
  • 29
  • 1
    This is probably the correct answer, but you need to specify *why* this is the case. E.g. does `RandomNumberGenerator` return cryptographically secure random numbers? And if so, why and how? Note that link only answers are generally "frowned upon". – Maarten Bodewes Jul 28 '16 at 17:26
3

We can do it like this in .Net core. It worked for me.

RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
var byteArray = new byte[4];
provider.GetBytes(byteArray);

//convert 4 bytes to an integer
var randomInteger = BitConverter.ToUInt32(byteArray, 0);

It is present under the namespace : System.Security.Cryptography

add this in your class to use the method : using System.Security.Cryptography;

Hope it is Helpful. Thanks

kara
  • 3,205
  • 4
  • 20
  • 34