From 3eff61d4cc3b1fea7f44471e571264f75da6790c Mon Sep 17 00:00:00 2001 From: Gerard Smit Date: Thu, 22 Jan 2026 00:13:41 +0100 Subject: [PATCH] Add polyfills for `RandomNumberGenerator.Fill(...)` --- .../NetCore21/RandomNumberGeneratorTests.cs | 24 ++++++++++++++++++ PolyShim/NetCore21/RandomNumberGenerator.cs | 25 +++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 PolyShim.Tests/NetCore21/RandomNumberGeneratorTests.cs create mode 100644 PolyShim/NetCore21/RandomNumberGenerator.cs diff --git a/PolyShim.Tests/NetCore21/RandomNumberGeneratorTests.cs b/PolyShim.Tests/NetCore21/RandomNumberGeneratorTests.cs new file mode 100644 index 0000000..09422e7 --- /dev/null +++ b/PolyShim.Tests/NetCore21/RandomNumberGeneratorTests.cs @@ -0,0 +1,24 @@ +using System; +using System.Security.Cryptography; +using FluentAssertions; +using Xunit; + +namespace PolyShim.Tests.NetCore21; + +public class RandomNumberGeneratorTests +{ + [Fact] + public void Fill_Span_Test() + { + // Arrange + Span buffer = stackalloc byte[16]; + + // Act + RandomNumberGenerator.Fill(buffer); + + // Assert + // Since cryptographic random data is non-deterministic, + // we can only verify that the buffer contains some non-zero bytes + buffer.ToArray().Should().Contain(b => b != 0); + } +} diff --git a/PolyShim/NetCore21/RandomNumberGenerator.cs b/PolyShim/NetCore21/RandomNumberGenerator.cs new file mode 100644 index 0000000..bd49461 --- /dev/null +++ b/PolyShim/NetCore21/RandomNumberGenerator.cs @@ -0,0 +1,25 @@ +#if (NETCOREAPP && !NETCOREAPP2_1_OR_GREATER) || (NETFRAMEWORK && NET45_OR_GREATER) +#nullable enable +// ReSharper disable RedundantUsingDirective +// ReSharper disable CheckNamespace +// ReSharper disable InconsistentNaming +// ReSharper disable PartialTypeWithSinglePart + +using System; +using System.Security.Cryptography; + +internal static partial class PolyfillExtensions +{ + extension(RandomNumberGenerator) + { + // https://learn.microsoft.com/dotnet/api/system.security.cryptography.randomnumbergenerator.fill + public static void Fill(Span data) + { + var buffer = new byte[data.Length]; + using var rng = RandomNumberGenerator.Create(); + rng.GetBytes(buffer); + buffer.CopyTo(data); + } + } +} +#endif