Quickly create a 12-digit Number Generator Securely in C#

Step 1:

Add Reference to your project to System.Security

Step 2:

In you class add:

using System.Security.Cryptography;

Step 3:

In your class add the following  method using RNG encryption service provider to enforce secuity on your random number:

public long GetNextInt64()
{
var bytes = new byte[sizeof(Int64)];
RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider();
Gen.GetBytes(bytes);

long random = BitConverter.ToInt64(bytes, 0);

//Remove any possible negative generator numbers and shorten the generated number to 12-digits
string pos = random.ToString().Replace(“-“, “”).Substring(0, 12);

return Convert.ToInt64(pos);
}

 

Easy huh??