Export (0) Print
Expand All
2 out of 4 rated this helpful - Rate this topic

RNGCryptoServiceProvider Class

Implements a cryptographic Random Number Generator (RNG) using the implementation provided by the cryptographic service provider (CSP). This class cannot be inherited.

Namespace: System.Security.Cryptography
Assembly: mscorlib (in mscorlib.dll)

[ComVisibleAttribute(true)] 
public sealed class RNGCryptoServiceProvider : RandomNumberGenerator
/** @attribute ComVisibleAttribute(true) */ 
public final class RNGCryptoServiceProvider extends RandomNumberGenerator
ComVisibleAttribute(true) 
public final class RNGCryptoServiceProvider extends RandomNumberGenerator

The following code example shows how to create a random number with the RNGCryptoServiceProvider class.

//The following sample uses the Cryptography class to simulate the roll of a dice.

using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

class RNGCSP
{
	// Main method.
    public static void Main()
    {
        // Roll the dice 30 times and display 
        // the results to the console.
        for(int x = 0; x <= 30; x++)
            Console.WriteLine(RollDice(6));
    }
    
	// This method simulates a roll of the dice. The input parameter is the 
	// number of sides of the dice.
    public static int RollDice(int NumSides)
    {
        // Create a byte array to hold the random value.
        byte[] randomNumber = new byte[1];

        // Create a new instance of the RNGCryptoServiceProvider. 
        RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider();

        // Fill the array with a random value.
        Gen.GetBytes(randomNumber);

        // Convert the byte to an integer value to make the modulus operation easier.
        int rand = Convert.ToInt32(randomNumber[0]);

        // Return the random number mod the number
        // of sides.  The possible values are zero-
        // based, so we add one.
        return rand % NumSides + 1;
    }
}


System.Object
   System.Security.Cryptography.RandomNumberGenerator
    System.Security.Cryptography.RNGCryptoServiceProvider
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.