EphemeralDataProtectionProviderTests.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 System.Security.Cryptography;
  5. using System.Text;
  6. using Xunit;
  7. namespace Microsoft.AspNetCore.DataProtection
  8. {
  9. public class EphemeralDataProtectionProviderTests
  10. {
  11. [Fact]
  12. public void DifferentProvider_SamePurpose_DoesNotRoundTripData()
  13. {
  14. // Arrange
  15. var dataProtector1 = new EphemeralDataProtectionProvider().CreateProtector("purpose");
  16. var dataProtector2 = new EphemeralDataProtectionProvider().CreateProtector("purpose");
  17. byte[] bytes = Encoding.UTF8.GetBytes("Hello there!");
  18. // Act & assert
  19. // Each instance of the EphemeralDataProtectionProvider has its own unique KDK, so payloads can't be shared.
  20. byte[] protectedBytes = dataProtector1.Protect(bytes);
  21. Assert.ThrowsAny<CryptographicException>(() =>
  22. {
  23. byte[] unprotectedBytes = dataProtector2.Unprotect(protectedBytes);
  24. });
  25. }
  26. [Fact]
  27. public void SingleProvider_DifferentPurpose_DoesNotRoundTripData()
  28. {
  29. // Arrange
  30. var dataProtectionProvider = new EphemeralDataProtectionProvider();
  31. var dataProtector1 = dataProtectionProvider.CreateProtector("purpose");
  32. var dataProtector2 = dataProtectionProvider.CreateProtector("different purpose");
  33. byte[] bytes = Encoding.UTF8.GetBytes("Hello there!");
  34. // Act & assert
  35. byte[] protectedBytes = dataProtector1.Protect(bytes);
  36. Assert.ThrowsAny<CryptographicException>(() =>
  37. {
  38. byte[] unprotectedBytes = dataProtector2.Unprotect(protectedBytes);
  39. });
  40. }
  41. [Fact]
  42. public void SingleProvider_SamePurpose_RoundTripsData()
  43. {
  44. // Arrange
  45. var dataProtectionProvider = new EphemeralDataProtectionProvider();
  46. var dataProtector1 = dataProtectionProvider.CreateProtector("purpose");
  47. var dataProtector2 = dataProtectionProvider.CreateProtector("purpose"); // should be equivalent to the previous instance
  48. byte[] bytes = Encoding.UTF8.GetBytes("Hello there!");
  49. // Act
  50. byte[] protectedBytes = dataProtector1.Protect(bytes);
  51. byte[] unprotectedBytes = dataProtector2.Unprotect(protectedBytes);
  52. // Assert
  53. Assert.Equal(bytes, unprotectedBytes);
  54. }
  55. }
  56. }