Skip to content

Commit

Permalink
Merge pull request #663 from vcsjones/use-runtime-random-int32
Browse files Browse the repository at this point in the history
Use the built-in CSPRNG GetInt32
  • Loading branch information
leastprivilege authored Jan 24, 2022
2 parents 457310c + 8048cf5 commit f1d2be7
Showing 1 changed file with 1 addition and 21 deletions.
22 changes: 1 addition & 21 deletions src/IdentityServer/Services/Default/NumericUserCodeGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,27 +36,7 @@ public class NumericUserCodeGenerator : IUserCodeGenerator
/// <returns></returns>
public Task<string> GenerateAsync()
{
var next = Next(100000000, 999999999);
var next = RandomNumberGenerator.GetInt32(100000000, 1000000000);
return Task.FromResult(next.ToString());
}

private int Next(int minValue, int maxValue)
{
if (minValue > maxValue) throw new ArgumentOutOfRangeException(nameof(minValue));
if (minValue == maxValue) return minValue;
long diff = maxValue - minValue;

while (true)
{
var uint32Buffer = RandomNumberGenerator.GetBytes(8);
var rand = BitConverter.ToUInt32(uint32Buffer, 0);

const long max = 1 + (long) uint.MaxValue;
var remainder = max % diff;
if (rand < max - remainder)
{
return (int) (minValue + rand % diff);
}
}
}
}

0 comments on commit f1d2be7

Please sign in to comment.