Skip to content

Commit 8b000d9

Browse files
martincostelloTratcher
authored andcommitted
Use RandomNumberGenerator.Fill() (#18128)
* Use RandomNumberGenerator.Fill() Use the new RandomNumberGenerator.Fill() method instead of maintaining instances of RandomNumberGenerator to use GetBytes(). * Revert RandomNumberGenerator.Fill() Revert usage of RandomNumberGenerator.Fill() as the project still targets netstandard2.0.
1 parent b6b5319 commit 8b000d9

File tree

10 files changed

+10
-25
lines changed

10 files changed

+10
-25
lines changed

src/Antiforgery/src/Internal/BinaryBlob.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ namespace Microsoft.AspNetCore.Antiforgery
1515
[DebuggerDisplay("{DebuggerString}")]
1616
internal sealed class BinaryBlob : IEquatable<BinaryBlob>
1717
{
18-
private static readonly RandomNumberGenerator _randomNumberGenerator = RandomNumberGenerator.Create();
1918
private readonly byte[] _data;
2019

2120
// Generates a new token using a specified bit length.
@@ -92,7 +91,7 @@ public override int GetHashCode()
9291
private static byte[] GenerateNewToken(int bitLength)
9392
{
9493
var data = new byte[bitLength / 8];
95-
_randomNumberGenerator.GetBytes(data);
94+
RandomNumberGenerator.Fill(data);
9695
return data;
9796
}
9897

src/Antiforgery/test/DefaultAntiforgeryTokenGeneratorTest.cs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -149,10 +149,7 @@ public void GenerateRequestToken_ClaimsBasedIdentity()
149149
httpContext.User = new ClaimsPrincipal(identity);
150150

151151
byte[] data = new byte[256 / 8];
152-
using (var rng = RandomNumberGenerator.Create())
153-
{
154-
rng.GetBytes(data);
155-
}
152+
RandomNumberGenerator.Fill(data);
156153
var base64ClaimUId = Convert.ToBase64String(data);
157154
var expectedClaimUid = new BinaryBlob(256, data);
158155

src/Components/Server/src/Circuits/CircuitIdFactory.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ internal class CircuitIdFactory
2020
private const int SecretLength = 64;
2121
private const int IdLength = 32;
2222

23-
private readonly RandomNumberGenerator _generator = RandomNumberGenerator.Create();
2423
private readonly IDataProtector _protector;
2524

2625
public CircuitIdFactory(IDataProtectionProvider provider)
@@ -35,7 +34,7 @@ public CircuitIdFactory(IDataProtectionProvider provider)
3534
public CircuitId CreateCircuitId()
3635
{
3736
var buffer = new byte[SecretLength];
38-
_generator.GetBytes(buffer);
37+
RandomNumberGenerator.Fill(buffer);
3938

4039
var id = new byte[IdLength];
4140
Array.Copy(

src/Hosting/TestHost/src/WebSocketClient.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -109,8 +109,7 @@ public async Task<WebSocket> ConnectAsync(Uri uri, CancellationToken cancellatio
109109
private string CreateRequestKey()
110110
{
111111
byte[] data = new byte[16];
112-
var rng = RandomNumberGenerator.Create();
113-
rng.GetBytes(data);
112+
RandomNumberGenerator.Fill(data);
114113
return Convert.ToBase64String(data);
115114
}
116115

src/Middleware/Session/src/DistributedSession.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ namespace Microsoft.AspNetCore.Session
1616
{
1717
public class DistributedSession : ISession
1818
{
19-
private static readonly RandomNumberGenerator CryptoRandom = RandomNumberGenerator.Create();
2019
private const int IdByteCount = 16;
2120

2221
private const byte SerializationRevision = 2;
@@ -104,7 +103,7 @@ private byte[] IdBytes
104103
if (IsAvailable && _sessionIdBytes == null)
105104
{
106105
_sessionIdBytes = new byte[IdByteCount];
107-
CryptoRandom.GetBytes(_sessionIdBytes);
106+
RandomNumberGenerator.Fill(_sessionIdBytes);
108107
}
109108
return _sessionIdBytes;
110109
}

src/Middleware/Session/src/SessionMiddleware.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ namespace Microsoft.AspNetCore.Session
2020
/// </summary>
2121
public class SessionMiddleware
2222
{
23-
private static readonly RandomNumberGenerator CryptoRandom = RandomNumberGenerator.Create();
2423
private const int SessionKeyLength = 36; // "382c74c3-721d-4f34-80e5-57657b6cbc27"
2524
private static readonly Func<bool> ReturnTrue = () => true;
2625
private readonly RequestDelegate _next;
@@ -91,7 +90,7 @@ public async Task Invoke(HttpContext context)
9190
{
9291
// No valid cookie, new session.
9392
var guidBytes = new byte[16];
94-
CryptoRandom.GetBytes(guidBytes);
93+
RandomNumberGenerator.Fill(guidBytes);
9594
sessionKey = new Guid(guidBytes).ToString();
9695
cookieValue = CookieProtection.Protect(_dataProtector, sessionKey);
9796
var establisher = new SessionEstablisher(context, cookieValue, _options);

src/Security/Authentication/Core/src/RemoteAuthenticationHandler.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,6 @@ public abstract class RemoteAuthenticationHandler<TOptions> : AuthenticationHand
1818
private const string CorrelationMarker = "N";
1919
private const string AuthSchemeKey = ".AuthScheme";
2020

21-
private static readonly RandomNumberGenerator CryptoRandom = RandomNumberGenerator.Create();
22-
2321
protected string SignInScheme => Options.SignInScheme;
2422

2523
/// <summary>
@@ -194,7 +192,7 @@ protected virtual void GenerateCorrelationId(AuthenticationProperties properties
194192
}
195193

196194
var bytes = new byte[32];
197-
CryptoRandom.GetBytes(bytes);
195+
RandomNumberGenerator.Fill(bytes);
198196
var correlationId = Base64UrlTextEncoder.Encode(bytes);
199197

200198
var cookieOptions = Options.CorrelationCookie.Build(Context, Clock.UtcNow);

src/Security/Authentication/MicrosoftAccount/src/MicrosoftAccountHandler.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,6 @@ namespace Microsoft.AspNetCore.Authentication.MicrosoftAccount
2020
{
2121
public class MicrosoftAccountHandler : OAuthHandler<MicrosoftAccountOptions>
2222
{
23-
private static readonly RandomNumberGenerator CryptoRandom = RandomNumberGenerator.Create();
24-
2523
public MicrosoftAccountHandler(IOptionsMonitor<MicrosoftAccountOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
2624
: base(options, logger, encoder, clock)
2725
{ }
@@ -64,7 +62,7 @@ protected override string BuildChallengeUrl(AuthenticationProperties properties,
6462
if (Options.UsePkce)
6563
{
6664
var bytes = new byte[32];
67-
CryptoRandom.GetBytes(bytes);
65+
RandomNumberGenerator.Fill(bytes);
6866
var codeVerifier = Base64UrlTextEncoder.Encode(bytes);
6967

7068
// Store this for use during the code redemption.

src/Security/Authentication/OAuth/src/OAuthHandler.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ namespace Microsoft.AspNetCore.Authentication.OAuth
2222
{
2323
public class OAuthHandler<TOptions> : RemoteAuthenticationHandler<TOptions> where TOptions : OAuthOptions, new()
2424
{
25-
private static readonly RandomNumberGenerator CryptoRandom = RandomNumberGenerator.Create();
2625
protected HttpClient Backchannel => Options.Backchannel;
2726

2827
/// <summary>
@@ -274,7 +273,7 @@ protected virtual string BuildChallengeUrl(AuthenticationProperties properties,
274273
if (Options.UsePkce)
275274
{
276275
var bytes = new byte[32];
277-
CryptoRandom.GetBytes(bytes);
276+
RandomNumberGenerator.Fill(bytes);
278277
var codeVerifier = Base64UrlTextEncoder.Encode(bytes);
279278

280279
// Store this for use during the code redemption.

src/Security/Authentication/OpenIdConnect/src/OpenIdConnectHandler.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,6 @@ public class OpenIdConnectHandler : RemoteAuthenticationHandler<OpenIdConnectOpt
3434
private const string NonceProperty = "N";
3535
private const string HeaderValueEpocDate = "Thu, 01 Jan 1970 00:00:00 GMT";
3636

37-
private static readonly RandomNumberGenerator CryptoRandom = RandomNumberGenerator.Create();
38-
3937
private OpenIdConnectConfiguration _configuration;
4038

4139
protected HttpClient Backchannel => Options.Backchannel;
@@ -371,7 +369,7 @@ private async Task HandleChallengeAsyncInternal(AuthenticationProperties propert
371369
if (Options.UsePkce && Options.ResponseType == OpenIdConnectResponseType.Code)
372370
{
373371
var bytes = new byte[32];
374-
CryptoRandom.GetBytes(bytes);
372+
RandomNumberGenerator.Fill(bytes);
375373
var codeVerifier = Base64UrlTextEncoder.Encode(bytes);
376374

377375
// Store this for use during the code redemption. See RunAuthorizationCodeReceivedEventAsync.

0 commit comments

Comments
 (0)