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.
This commit is contained in:
Martin Costello 2020-01-04 23:52:07 +00:00 committed by Chris Ross
parent b6b5319bab
commit 8b000d961c
10 changed files with 10 additions and 25 deletions

View File

@ -15,7 +15,6 @@ namespace Microsoft.AspNetCore.Antiforgery
[DebuggerDisplay("{DebuggerString}")] [DebuggerDisplay("{DebuggerString}")]
internal sealed class BinaryBlob : IEquatable<BinaryBlob> internal sealed class BinaryBlob : IEquatable<BinaryBlob>
{ {
private static readonly RandomNumberGenerator _randomNumberGenerator = RandomNumberGenerator.Create();
private readonly byte[] _data; private readonly byte[] _data;
// Generates a new token using a specified bit length. // Generates a new token using a specified bit length.
@ -92,7 +91,7 @@ namespace Microsoft.AspNetCore.Antiforgery
private static byte[] GenerateNewToken(int bitLength) private static byte[] GenerateNewToken(int bitLength)
{ {
var data = new byte[bitLength / 8]; var data = new byte[bitLength / 8];
_randomNumberGenerator.GetBytes(data); RandomNumberGenerator.Fill(data);
return data; return data;
} }

View File

@ -149,10 +149,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
httpContext.User = new ClaimsPrincipal(identity); httpContext.User = new ClaimsPrincipal(identity);
byte[] data = new byte[256 / 8]; byte[] data = new byte[256 / 8];
using (var rng = RandomNumberGenerator.Create()) RandomNumberGenerator.Fill(data);
{
rng.GetBytes(data);
}
var base64ClaimUId = Convert.ToBase64String(data); var base64ClaimUId = Convert.ToBase64String(data);
var expectedClaimUid = new BinaryBlob(256, data); var expectedClaimUid = new BinaryBlob(256, data);

View File

@ -20,7 +20,6 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits
private const int SecretLength = 64; private const int SecretLength = 64;
private const int IdLength = 32; private const int IdLength = 32;
private readonly RandomNumberGenerator _generator = RandomNumberGenerator.Create();
private readonly IDataProtector _protector; private readonly IDataProtector _protector;
public CircuitIdFactory(IDataProtectionProvider provider) public CircuitIdFactory(IDataProtectionProvider provider)
@ -35,7 +34,7 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits
public CircuitId CreateCircuitId() public CircuitId CreateCircuitId()
{ {
var buffer = new byte[SecretLength]; var buffer = new byte[SecretLength];
_generator.GetBytes(buffer); RandomNumberGenerator.Fill(buffer);
var id = new byte[IdLength]; var id = new byte[IdLength];
Array.Copy( Array.Copy(

View File

@ -109,8 +109,7 @@ namespace Microsoft.AspNetCore.TestHost
private string CreateRequestKey() private string CreateRequestKey()
{ {
byte[] data = new byte[16]; byte[] data = new byte[16];
var rng = RandomNumberGenerator.Create(); RandomNumberGenerator.Fill(data);
rng.GetBytes(data);
return Convert.ToBase64String(data); return Convert.ToBase64String(data);
} }

View File

@ -16,7 +16,6 @@ namespace Microsoft.AspNetCore.Session
{ {
public class DistributedSession : ISession public class DistributedSession : ISession
{ {
private static readonly RandomNumberGenerator CryptoRandom = RandomNumberGenerator.Create();
private const int IdByteCount = 16; private const int IdByteCount = 16;
private const byte SerializationRevision = 2; private const byte SerializationRevision = 2;
@ -104,7 +103,7 @@ namespace Microsoft.AspNetCore.Session
if (IsAvailable && _sessionIdBytes == null) if (IsAvailable && _sessionIdBytes == null)
{ {
_sessionIdBytes = new byte[IdByteCount]; _sessionIdBytes = new byte[IdByteCount];
CryptoRandom.GetBytes(_sessionIdBytes); RandomNumberGenerator.Fill(_sessionIdBytes);
} }
return _sessionIdBytes; return _sessionIdBytes;
} }

View File

@ -20,7 +20,6 @@ namespace Microsoft.AspNetCore.Session
/// </summary> /// </summary>
public class SessionMiddleware public class SessionMiddleware
{ {
private static readonly RandomNumberGenerator CryptoRandom = RandomNumberGenerator.Create();
private const int SessionKeyLength = 36; // "382c74c3-721d-4f34-80e5-57657b6cbc27" private const int SessionKeyLength = 36; // "382c74c3-721d-4f34-80e5-57657b6cbc27"
private static readonly Func<bool> ReturnTrue = () => true; private static readonly Func<bool> ReturnTrue = () => true;
private readonly RequestDelegate _next; private readonly RequestDelegate _next;
@ -91,7 +90,7 @@ namespace Microsoft.AspNetCore.Session
{ {
// No valid cookie, new session. // No valid cookie, new session.
var guidBytes = new byte[16]; var guidBytes = new byte[16];
CryptoRandom.GetBytes(guidBytes); RandomNumberGenerator.Fill(guidBytes);
sessionKey = new Guid(guidBytes).ToString(); sessionKey = new Guid(guidBytes).ToString();
cookieValue = CookieProtection.Protect(_dataProtector, sessionKey); cookieValue = CookieProtection.Protect(_dataProtector, sessionKey);
var establisher = new SessionEstablisher(context, cookieValue, _options); var establisher = new SessionEstablisher(context, cookieValue, _options);

View File

@ -18,8 +18,6 @@ namespace Microsoft.AspNetCore.Authentication
private const string CorrelationMarker = "N"; private const string CorrelationMarker = "N";
private const string AuthSchemeKey = ".AuthScheme"; private const string AuthSchemeKey = ".AuthScheme";
private static readonly RandomNumberGenerator CryptoRandom = RandomNumberGenerator.Create();
protected string SignInScheme => Options.SignInScheme; protected string SignInScheme => Options.SignInScheme;
/// <summary> /// <summary>
@ -194,7 +192,7 @@ namespace Microsoft.AspNetCore.Authentication
} }
var bytes = new byte[32]; var bytes = new byte[32];
CryptoRandom.GetBytes(bytes); RandomNumberGenerator.Fill(bytes);
var correlationId = Base64UrlTextEncoder.Encode(bytes); var correlationId = Base64UrlTextEncoder.Encode(bytes);
var cookieOptions = Options.CorrelationCookie.Build(Context, Clock.UtcNow); var cookieOptions = Options.CorrelationCookie.Build(Context, Clock.UtcNow);

View File

@ -20,8 +20,6 @@ namespace Microsoft.AspNetCore.Authentication.MicrosoftAccount
{ {
public class MicrosoftAccountHandler : OAuthHandler<MicrosoftAccountOptions> public class MicrosoftAccountHandler : OAuthHandler<MicrosoftAccountOptions>
{ {
private static readonly RandomNumberGenerator CryptoRandom = RandomNumberGenerator.Create();
public MicrosoftAccountHandler(IOptionsMonitor<MicrosoftAccountOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) public MicrosoftAccountHandler(IOptionsMonitor<MicrosoftAccountOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
: base(options, logger, encoder, clock) : base(options, logger, encoder, clock)
{ } { }
@ -64,7 +62,7 @@ namespace Microsoft.AspNetCore.Authentication.MicrosoftAccount
if (Options.UsePkce) if (Options.UsePkce)
{ {
var bytes = new byte[32]; var bytes = new byte[32];
CryptoRandom.GetBytes(bytes); RandomNumberGenerator.Fill(bytes);
var codeVerifier = Base64UrlTextEncoder.Encode(bytes); var codeVerifier = Base64UrlTextEncoder.Encode(bytes);
// Store this for use during the code redemption. // Store this for use during the code redemption.

View File

@ -22,7 +22,6 @@ namespace Microsoft.AspNetCore.Authentication.OAuth
{ {
public class OAuthHandler<TOptions> : RemoteAuthenticationHandler<TOptions> where TOptions : OAuthOptions, new() public class OAuthHandler<TOptions> : RemoteAuthenticationHandler<TOptions> where TOptions : OAuthOptions, new()
{ {
private static readonly RandomNumberGenerator CryptoRandom = RandomNumberGenerator.Create();
protected HttpClient Backchannel => Options.Backchannel; protected HttpClient Backchannel => Options.Backchannel;
/// <summary> /// <summary>
@ -274,7 +273,7 @@ namespace Microsoft.AspNetCore.Authentication.OAuth
if (Options.UsePkce) if (Options.UsePkce)
{ {
var bytes = new byte[32]; var bytes = new byte[32];
CryptoRandom.GetBytes(bytes); RandomNumberGenerator.Fill(bytes);
var codeVerifier = Base64UrlTextEncoder.Encode(bytes); var codeVerifier = Base64UrlTextEncoder.Encode(bytes);
// Store this for use during the code redemption. // Store this for use during the code redemption.

View File

@ -34,8 +34,6 @@ namespace Microsoft.AspNetCore.Authentication.OpenIdConnect
private const string NonceProperty = "N"; private const string NonceProperty = "N";
private const string HeaderValueEpocDate = "Thu, 01 Jan 1970 00:00:00 GMT"; private const string HeaderValueEpocDate = "Thu, 01 Jan 1970 00:00:00 GMT";
private static readonly RandomNumberGenerator CryptoRandom = RandomNumberGenerator.Create();
private OpenIdConnectConfiguration _configuration; private OpenIdConnectConfiguration _configuration;
protected HttpClient Backchannel => Options.Backchannel; protected HttpClient Backchannel => Options.Backchannel;
@ -371,7 +369,7 @@ namespace Microsoft.AspNetCore.Authentication.OpenIdConnect
if (Options.UsePkce && Options.ResponseType == OpenIdConnectResponseType.Code) if (Options.UsePkce && Options.ResponseType == OpenIdConnectResponseType.Code)
{ {
var bytes = new byte[32]; var bytes = new byte[32];
CryptoRandom.GetBytes(bytes); RandomNumberGenerator.Fill(bytes);
var codeVerifier = Base64UrlTextEncoder.Encode(bytes); var codeVerifier = Base64UrlTextEncoder.Encode(bytes);
// Store this for use during the code redemption. See RunAuthorizationCodeReceivedEventAsync. // Store this for use during the code redemption. See RunAuthorizationCodeReceivedEventAsync.