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