SecretAssert.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // Copyright (c) .NET Foundation. All rights reserved.
  2. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  3. using System;
  4. using Xunit;
  5. namespace Microsoft.AspNetCore.DataProtection
  6. {
  7. /// <summary>
  8. /// Helpful ISecret-based assertions.
  9. /// </summary>
  10. public static class SecretAssert
  11. {
  12. /// <summary>
  13. /// Asserts that two <see cref="ISecret"/> instances contain the same material.
  14. /// </summary>
  15. public static void Equal(ISecret secret1, ISecret secret2)
  16. {
  17. Assert.Equal(SecretToBase64String(secret1), SecretToBase64String(secret2));
  18. }
  19. /// <summary>
  20. /// Asserts that <paramref name="secret"/> has the length specified by <paramref name="expectedLengthInBits"/>.
  21. /// </summary>
  22. public static void LengthIs(int expectedLengthInBits, ISecret secret)
  23. {
  24. Assert.Equal(expectedLengthInBits, checked(secret.Length * 8));
  25. }
  26. /// <summary>
  27. /// Asserts that two <see cref="ISecret"/> instances do not contain the same material.
  28. /// </summary>
  29. public static void NotEqual(ISecret secret1, ISecret secret2)
  30. {
  31. Assert.NotEqual(SecretToBase64String(secret1), SecretToBase64String(secret2));
  32. }
  33. private static string SecretToBase64String(ISecret secret)
  34. {
  35. byte[] secretBytes = new byte[secret.Length];
  36. secret.WriteSecretIntoBuffer(new ArraySegment<byte>(secretBytes));
  37. return Convert.ToBase64String(secretBytes);
  38. }
  39. }
  40. }