BCryptUtilTests.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. using System;
  4. using System.Linq;
  5. using Microsoft.AspNetCore.DataProtection.Test.Shared;
  6. using Microsoft.AspNetCore.InternalTesting;
  7. using Xunit;
  8. namespace Microsoft.AspNetCore.Cryptography.Cng;
  9. public unsafe class BCryptUtilTests
  10. {
  11. [ConditionalFact]
  12. [ConditionalRunTestOnlyOnWindows]
  13. public void GenRandom_PopulatesBuffer()
  14. {
  15. // Arrange
  16. byte[] bytes = new byte[sizeof(Guid) + 6];
  17. bytes[0] = 0x04; // leading canary
  18. bytes[1] = 0x10;
  19. bytes[2] = 0xE4;
  20. bytes[sizeof(Guid) + 3] = 0xEA; // trailing canary
  21. bytes[sizeof(Guid) + 4] = 0xF2;
  22. bytes[sizeof(Guid) + 5] = 0x6A;
  23. fixed (byte* pBytes = &bytes[3])
  24. {
  25. for (int i = 0; i < 100; i++)
  26. {
  27. // Act
  28. BCryptUtil.GenRandom(pBytes, (uint)sizeof(Guid));
  29. // Check that the canaries haven't changed
  30. Assert.Equal(0x04, bytes[0]);
  31. Assert.Equal(0x10, bytes[1]);
  32. Assert.Equal(0xE4, bytes[2]);
  33. Assert.Equal(0xEA, bytes[sizeof(Guid) + 3]);
  34. Assert.Equal(0xF2, bytes[sizeof(Guid) + 4]);
  35. Assert.Equal(0x6A, bytes[sizeof(Guid) + 5]);
  36. // Check that the buffer was actually filled.
  37. // This check will fail once every 2**128 runs, which is insignificant.
  38. Guid newGuid = new Guid(bytes.Skip(3).Take(sizeof(Guid)).ToArray());
  39. Assert.NotEqual(Guid.Empty, newGuid);
  40. // Check that the first and last bytes of the buffer are not zero, which indicates that they
  41. // were in fact filled. This check will fail around 0.8% of the time, so we'll iterate up
  42. // to 100 times, which puts the total failure rate at once every 2**700 runs,
  43. // which is insignificant.
  44. if (bytes[3] != 0x00 && bytes[18] != 0x00)
  45. {
  46. return; // success!
  47. }
  48. }
  49. }
  50. Assert.True(false, "Buffer was not filled as expected.");
  51. }
  52. }