Can I use AES in CTR mode in .NET?
A compact standalone implementation based on the code by @quadfinity.
(Despite naming of the class in the original code) It can work with any key size: 128, 192 and 256. Just provide a key
of a correct size. salt
must have 128 bits (16 bytes).
The method works both for encryption and decryption.
public static void AesCtrTransform(
byte[] key, byte[] salt, Stream inputStream, Stream outputStream)
{
SymmetricAlgorithm aes =
new AesManaged { Mode = CipherMode.ECB, Padding = PaddingMode.None };
int blockSize = aes.BlockSize / 8;
if (salt.Length != blockSize)
{
throw new ArgumentException(
"Salt size must be same as block size " +
$"(actual: {salt.Length}, expected: {blockSize})");
}
byte[] counter = (byte[])salt.Clone();
Queue<byte> xorMask = new Queue<byte>();
var zeroIv = new byte[blockSize];
ICryptoTransform counterEncryptor = aes.CreateEncryptor(key, zeroIv);
int b;
while ((b = inputStream.ReadByte()) != -1)
{
if (xorMask.Count == 0)
{
var counterModeBlock = new byte[blockSize];
counterEncryptor.TransformBlock(
counter, 0, counter.Length, counterModeBlock, 0);
for (var i2 = counter.Length - 1; i2 >= 0; i2--)
{
if (++counter[i2] != 0)
{
break;
}
}
foreach (var b2 in counterModeBlock)
{
xorMask.Enqueue(b2);
}
}
var mask = xorMask.Dequeue();
outputStream.WriteByte((byte)(((byte)b) ^ mask));
}
}
If you want to encrypt or decrypt a file, use File.OpenRead
for inputStream
and File.Create
for the outputStream
:
using (Stream inputStream = File.OpenRead("file.in"))
using (Stream outputStream = File.Create("file.out"))
{
AesCtrTransform(key, salt, inputStream, outputStream);
}
See also PowerShell version of the code.
Yes, you can build a CTR using .NET's AES in ECB mode and a counter, that you yourself initialize and increment, for each block encrypted.
An example of this is the WinZipAes encryption stream, which is part of the open-source DotNetZip.
WinZip specifies the use of AES encryption for encrypted ZIP files, using AES in CTR mode. DotNetZip implements the CTR mode using ECB and the counter.
See here for some comments.