Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use the built-in CSPRNG GetInt32 #663

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The one built in to .NET has an exclusive upper bound, while the previous one was inclusive, hence the upper bound of 1_000_000_000.

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);
}
}
}
}