Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix one-shot AesCtr with default IV #149

Merged
merged 1 commit into from
Jan 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 5 additions & 10 deletions AesExtra/AesCtr.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,23 +97,18 @@ public override int FeedbackSize
}
}

static AesCtrTransform CreateTransform(byte[] rgbKey, byte[]? rgbIV)
{
// ECB.Encrypt === ECB.Decrypt; the transform is entirely symmetric.
// ECB does not use an IV; the IV we received is actually the initial counter for AES-CTR.
return new(rgbKey, rgbIV ?? BlockOfZeros);
}

/// <inheritdoc cref="AesManaged.CreateDecryptor(byte[], byte[])" />
public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[]? rgbIV)
{
return CreateTransform(rgbKey, rgbIV);
// CTR.Encrypt === CTR.Decrypt; the transform is entirely symmetric.
return new AesCtrTransform(rgbKey, rgbIV ?? BlockOfZeros);
}

/// <inheritdoc cref="AesManaged.CreateEncryptor(byte[], byte[])" />
public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV)
{
return CreateTransform(rgbKey, rgbIV);
// CTR.Encrypt === CTR.Decrypt; the transform is entirely symmetric.
return new AesCtrTransform(rgbKey, rgbIV ?? BlockOfZeros);
}

/// <inheritdoc cref="AesManaged.GenerateIV" />
Expand Down Expand Up @@ -142,7 +137,7 @@ bool TryTransformCtr(ReadOnlySpan<byte> input, Span<byte> destination, out int b
bytesWritten = 0;
return false;
}
using var transform = new AesCtrTransform(Key, IV);
using var transform = new AesCtrTransform(Key, IVValue ?? BlockOfZeros);
var inputSlice = input;
var destinationSlice = destination;
while (inputSlice.Length >= BLOCKSIZE)
Expand Down
15 changes: 15 additions & 0 deletions UnitTests/AesCtr_Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,21 @@ public void CreateDecryptor_WithKeyAndDefaultIV()
using var _ = aes.CreateDecryptor(new byte[16], null);
}

[TestMethod]
public void EncryptCtr_WithDefaultIV()
{
using var aes = AesCtr.Create();
aes.Key = new byte[128 / 8];

var fromDefaultIV = aes.EncryptCtr([1, 2, 3]);

aes.IV = new byte[16];

var fromExplicitIV = aes.EncryptCtr([1, 2, 3]);

CollectionAssert.AreEqual(fromExplicitIV, fromDefaultIV);
}

[TestMethod]
public void EncryptCtr_DestinationShort()
{
Expand Down
Loading