Friday 6 July 2012

.Net Tips , C# tip : Create a Cryptographic Random Number with C# Examples and VB.Net Examples

We can generate cryptographic random number using RNGCryptoServiceProvider class.
This class is available in System.Security.Cryptography namespace.
The System.Random class is a random number generator , the algorithm it uses is deterministic, meaning that you can always calculate what the next number will be based on the previously generated number. This means that numbers generated by the Random class are unsuitable for security is a priority, like generating encryption keys and passwords.

Important : The numbers generated by the RNGCryptoServiceProvider class are not truly random. However, they are sufficiently random to meet the requirements of cryptography and security applications in most government and commercial Applications.


C# Example :
        // Create a byte array to store the random data.
        byte[] objNumber = new byte[32];

        // Generate random number.
        System.Security.Cryptography.RandomNumberGenerator objRNG = System.Security.Cryptography.RandomNumberGenerator.Create();

        // Generate 32 bytes random data.
        objRNG.GetBytes(objNumber);

        // Get byte data into string
        string strRandomNumber = BitConverter.ToString(objNumber);

VB.net Example :
        ' Create a byte array to store the random data.
        Dim objNumber As Byte() = New Byte(31) {}

        ' Generate random number.
        Dim objRNG As System.Security.Cryptography.RandomNumberGenerator = System.Security.Cryptography.RandomNumberGenerator.Create()

        ' Generate 32 bytes random data.
        objRNG.GetBytes(objNumber)

        ' Get byte data into string
        Dim strRandomNumber As String = BitConverter.ToString(objNumber)

Output :

(To view original image , click on image)

Important Note : The computational effort required by RNGCryptoServiceProvider to generate a random number is greater than required by Random class. For everyday routine purposes, the use of RNGCryptoServiceProvider is not suitable. Excessive and unnecessary use of the RNGCryptoServiceProvider class could degrade the application performance.

This is very useful .Net Tips.

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.


 

No comments:

Post a Comment