#region ========================================================================= USING ===================================================================================== using Nemera.Presentation.Web.Common.DTO.Configuration; using Nemera.Presentation.Web.Common.Security; using Nemera.Presentation.Web.Fixtures.Common.DTO.Configuration; using Microsoft.Extensions.Options; using System; using System.Diagnostics.CodeAnalysis; #endregion namespace Nemera.Presentation.Web.UnitTests.Common.Security; /// /// Contains unit tests for the class. /// [ExcludeFromCodeCoverage] public class CryptographyServiceTests { private const string TEST_ENCRYPTION_KEY = "FLYO0QRo6u2VzoFOgNkkEwYNGtqhJ3QGZd7iAHNEJeM="; private readonly EncryptionSettingsDtoFixture _encryptionSettingsDtoFixture = new(); private readonly CryptographyService _sut; /// /// Initializes a new instance of the class. /// public CryptographyServiceTests() { EncryptionSettingsDto settings = _encryptionSettingsDtoFixture.Create(secretKey: TEST_ENCRYPTION_KEY); _sut = new CryptographyService(Options.Create(settings)); } [Fact] public void Encrypt_WhenCalled_ShouldReturnCiphertextThatDecryptsToPlaintext() { // Arrange const string PLAINTEXT = "sensitive-data"; // Act string ciphertext = _sut.Encrypt(PLAINTEXT); // Assert Assert.NotEqual(PLAINTEXT, ciphertext); Assert.Equal(PLAINTEXT, _sut.Decrypt(ciphertext)); } [Fact] public void Encrypt_WhenCalledTwice_ShouldReturnDifferentCiphertexts() { // Arrange const string PLAINTEXT = "sensitive-data"; // Act string firstCiphertext = _sut.Encrypt(PLAINTEXT); string secondCiphertext = _sut.Encrypt(PLAINTEXT); // Assert Assert.NotEqual(firstCiphertext, secondCiphertext); } [Theory] [InlineData(null)] [InlineData("")] public void Encrypt_WhenPlaintextIsNullOrEmpty_ShouldThrowArgumentException(string? plaintext) { // Act ArgumentException exception = Assert.Throws(() => _sut.Encrypt(plaintext!)); // Assert Assert.Equal("plaintext", exception.ParamName); } [Fact] public void Decrypt_WhenCiphertextIsNotValidBase64_ShouldThrowFormatException() { // Act FormatException exception = Assert.Throws(() => _sut.Decrypt("not-valid-base64!!!")); // Assert Assert.Contains("Base-64", exception.Message); } [Fact] public void Decrypt_WhenCiphertextIsTooShort_ShouldThrowArgumentException() { // Act ArgumentException exception = Assert.Throws(() => _sut.Decrypt(Convert.ToBase64String([1, 2, 3]))); // Assert Assert.Equal("Invalid ciphertext", exception.Message); } }