Reputation: 1880
I'm look at algorithms and ways to generating a 10 digit security token. I've tried the following:
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
var buffer = new byte[4];
rng.GetBytes(buffer);
int result = BitConverter.ToInt32(buffer, 0);
var token = Math.Abs(result).ToString();
The problem is RNGCryptoServiceProvider seems to return around 9 to 10 digits. I've consider add an extra random numbers if it contains less than 10 digits however I not convinced this is the best approach.
appreciate any advice or recommendations.
Upvotes: 1
Views: 2082
Reputation: 65156
Just pad the result with zeros to get 10 digits. Also, you should rather use a ulong
to get the full range of 10 digits.
var buffer = new byte[8]; // 8 bytes for a long
rng.GetBytes(buffer);
ulong result = BitConverter.ToUInt64(buffer, 0); // unsigned to avoid having to use Abs
var token = result.ToString("D10"); // pads the result to 10 digits
token = token.Substring(token.Length - 10); // strip out extra digits, if any
Upvotes: 1