Skip to content

Instantly share code, notes, and snippets.

@hanswolff
Last active December 29, 2023 23:34
Show Gist options
  • Star 30 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hanswolff/8809275 to your computer and use it in GitHub Desktop.
Save hanswolff/8809275 to your computer and use it in GitHub Desktop.
AES Counter Mode implementation in C# (should work for AES 128, 192, 256 -> just initialize with proper key length)
// The MIT License (MIT)
// Copyright (c) 2020 Hans Wolff
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
public class AesCounterMode : SymmetricAlgorithm
{
private readonly ulong _nonce;
private readonly ulong _counter;
private readonly AesManaged _aes;
public AesCounterMode(byte[] nonce, ulong counter)
: this(ConvertNonce(nonce), counter)
{
}
public AesCounterMode(ulong nonce, ulong counter)
{
_aes = new AesManaged
{
Mode = CipherMode.ECB,
Padding = PaddingMode.None
};
_nonce = nonce;
_counter = counter;
}
private static ulong ConvertNonce(byte[] nonce)
{
if (nonce == null) throw new ArgumentNullException(nameof(nonce));
if (nonce.Length < sizeof(ulong)) throw new ArgumentException($"{nameof(nonce)} must have at least {sizeof(ulong)} bytes");
return BitConverter.ToUInt64(nonce);
}
public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] ignoredParameter)
{
return new CounterModeCryptoTransform(_aes, rgbKey, _nonce, _counter);
}
public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] ignoredParameter)
{
return new CounterModeCryptoTransform(_aes, rgbKey, _nonce, _counter);
}
public override void GenerateKey()
{
_aes.GenerateKey();
}
public override void GenerateIV()
{
// IV not needed in Counter Mode
}
}
public class CounterModeCryptoTransform : ICryptoTransform
{
private readonly byte[] _nonceAndCounter;
private readonly ICryptoTransform _counterEncryptor;
private readonly Queue<byte> _xorMask = new Queue<byte>();
private readonly SymmetricAlgorithm _symmetricAlgorithm;
private ulong _counter;
public CounterModeCryptoTransform(SymmetricAlgorithm symmetricAlgorithm, byte[] key, ulong nonce, ulong counter)
{
if (key == null) throw new ArgumentNullException(nameof(key));
_symmetricAlgorithm = symmetricAlgorithm ?? throw new ArgumentNullException(nameof(symmetricAlgorithm));
_counter = counter;
_nonceAndCounter = new byte[16];
BitConverter.TryWriteBytes(_nonceAndCounter, nonce);
BitConverter.TryWriteBytes(new Span<byte>(_nonceAndCounter, sizeof(ulong), sizeof(ulong)), counter);
var zeroIv = new byte[_symmetricAlgorithm.BlockSize / 8];
_counterEncryptor = symmetricAlgorithm.CreateEncryptor(key, zeroIv);
}
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
var output = new byte[inputCount];
TransformBlock(inputBuffer, inputOffset, inputCount, output, 0);
return output;
}
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer,
int outputOffset)
{
for (var i = 0; i < inputCount; i++)
{
if (NeedMoreXorMaskBytes())
{
EncryptCounterThenIncrement();
}
var mask = _xorMask.Dequeue();
outputBuffer[outputOffset + i] = (byte) (inputBuffer[inputOffset + i] ^ mask);
}
return inputCount;
}
private bool NeedMoreXorMaskBytes()
{
return _xorMask.Count == 0;
}
private byte[] _counterModeBlock;
private void EncryptCounterThenIncrement()
{
_counterModeBlock ??= new byte[_symmetricAlgorithm.BlockSize / 8];
_counterEncryptor.TransformBlock(_nonceAndCounter, 0, _nonceAndCounter.Length, _counterModeBlock, 0);
IncrementCounter();
foreach (var b in _counterModeBlock)
{
_xorMask.Enqueue(b);
}
}
private void IncrementCounter()
{
_counter++;
var span = new Span<byte>(_nonceAndCounter, sizeof(ulong), sizeof(ulong));
BitConverter.TryWriteBytes(span, _counter);
}
public int InputBlockSize => _symmetricAlgorithm.BlockSize / 8;
public int OutputBlockSize => _symmetricAlgorithm.BlockSize / 8;
public bool CanTransformMultipleBlocks => true;
public bool CanReuseTransform => false;
public void Dispose()
{
_counterEncryptor.Dispose();
}
}
//public void ExampleUsage()
//{
// var key = new byte[16];
// RandomNumberGenerator.Create().GetBytes(key);
// var nonce = new byte[8];
// RandomNumberGenerator.Create().GetBytes(nonce);
//
// var dataToEncrypt = new byte[12345];
//
// var counter = 0;
// using var counterMode = new AesCounterMode(nonce, counter);
// using var encryptor = counterMode.CreateEncryptor(key, null);
// using var decryptor = counterMode.CreateDecryptor(key, null);
//
// var encryptedData = new byte[dataToEncrypt.Length];
// var bytesWritten = encryptor.TransformBlock(dataToEncrypt, 0, dataToEncrypt.Length, encryptedData, 0);
//
// var decrypted = new byte[dataToEncrypt.Length];
// decryptor.TransformBlock(encryptedData, 0, bytesWritten, decrypted, 0);
//
// //decrypted.Should().BeEquivalentTo(dataToEncrypt);
//}
@AlliterativeAlice
Copy link

Thanks so much for this code! It helped me a lot with a project I was working on using ECIES.

I noticed that the contents of the byte array passed as the IV gets modified when you encrypt or decrypt something. This was unexpected and tripped me up a bit. I would recommend changing _counter = counter; to _counter = counter.ToArray(); on line 45 in order to create a copy of the byte array for the class instance to use so that the original array passed to the constructor doesn't get modified.

@lellis1936
Copy link

AlliterativeAlice I encountered the same issue but I believe this might be intentional so that multiple chunks of the same stream can be encrypted in multiple calls. My solution of course was to clone my own IV before invoking the encryption. Preventing the IV data from being modified inside the class would disallow this kind of streaming, especially since the input does not have to be a multiple of the block size.

@hanswolff
Copy link
Author

Refactored the code (works for .NET Core). I also provided an example how to use it.

@ZeroSkill1
Copy link

Perhaps add support for a BigInteger counter?

@hugoqribeiro
Copy link

Hi @hanswolff.

I received a requirement to implement encryption with AES-CTR with a 128-bit key and 128-bit IV.

I see that in your implementation the nonce is converted to UInt64.

Can you please point me the problem with just customizing the implementation accordingly?

You see that I'm no Crypto expert... :)

Thanks.

@bronze1man
Copy link

@hugoqribeiro my implement is AES-CTR with a 256-bit key 128-bit iv not 64bit iv, it may help you.
Passing a 128-bit key may work as AES-CTR with a 128-bit key 128-bit iv, but i do not tested.
https://gist.github.com/bronze1man/68f88494c88eb3fc647c447b36138134

@hugoqribeiro
Copy link

@hugoqribeiro my implement is AES-CTR with a 256-bit key 128-bit iv not 64bit iv, it may help you.
Passing a 128-bit key may work as AES-CTR with a 128-bit key 128-bit iv, but i do not tested.
https://gist.github.com/bronze1man/68f88494c88eb3fc647c447b36138134

I see the point of your implementation but it confuses me more.

If you adapt it to accept a 64 bit IV... you get different results comparing to the @hanswolff implementation. Only when the input has more than 16 bytes.

You use the IV as the counter, while the original implementation concatenates the nonce (IV) with the counter (that starts at 0).

This is what bugs me. We want an implementation that ensures that other parties decrypting the text... get the text I encrypted. So using the nonce and the counter exactly the same way is crucial, right?

@lellis1936
Copy link

lellis1936 commented Nov 30, 2020

Excuse me for coming in but I find this exchange interesting. "So using the nonce and the counter exactly the same way is crucial, right?". Yes, of course. AES-CTR, regardless of the key size, uses a 128-bit block size and that is always the size of the initial counter block. Take a look at Section 6.5 and Appendix B of this document: https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38a.pdf

The key is both the encryptor and decryptor must use the same rules for the construction of the counter block. Section B.2 of the NIST document goes into detail. So you must know what the choices are to be compatible with a peer system, or perhaps you can set the rules and dictate them to the other side. However the implementation in which we are posting these comments has made those choices: the counter block is split in to pieces, comprised of the nonce and a block counter field. You say you need to support 128-bit IVs. That may be as simple as thinking of the 128-bits as opaque, splitting those 128-bits in half and passing one half in as the nonce and the other half as the counter in the implementation here. Whether this will work for your peer depends on implementation details you have not provided. Clearly both sides must do it exactly the same way. Some number of those bits will be the counter in the internal AES implementation. You cannot have a 128-bit nonce because it leaves no room for the counter.

@hugoqribeiro
Copy link

Excuse me for coming in but I find this exchange interesting. "So using the nonce and the counter exactly the same way is crucial, right?". Yes, of course. AES-CTR, regardless of the key size, uses a 128-bit block size and that is always the size of the initial counter block. Take a look at Section 6.5 and Appendix B of this document:https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38a.pdf.

The key is both the encryptor and decryptor must use the same rules for the construction of the counter block. Section B.2 of the NIST document goes into detail. So you must know what the choices are to be compatible with a peer system, or perhaps you can set the rules and dictate them to the other side. However the implementation in which we are posting these comments has made those choices: the counter block is split in to pieces, comprised of the nonce and a block counter field. You say you need to support 128-bit IVs. That may be as simple as thinking of the 128-bits as opaque, splitting those 128-bits in half and passing one half in as the nonce and the other half as the counter in the implementation here. Whether this will work for your peer depends on implementation details you have not provided. Clearly both sides must do it exactly the same way. Some number of those bits will be the counter in the internal AES implementation. You cannot have a 128-bit nonce because it leaves no room for the counter.

Great help! You really shed some light for me on these concepts (given my lack of experience on such matters).

The problem here is that my requirements are coming from the Portuguese Tax Authority. So, I have no power whatsoever to even influence their part, and they have an history of not being clear about their implementation details. They're simply saying that the documents need to be encrypted with AES-CTR and a key/IV pair they provide.

I need to clarify these details before attempting to solve them. But now I see the questions that need to be answered.

Thanks again.

@lellis1936
Copy link

@hanswolff, I may be wrong but it appears to me recent versions of this gist are now using a non-standard incrementing function.

I believe by convention the incrementing function uses big-endian order so that the first byte incremented should be byte 15 of the counter block with overflow to byte 14. Earlier versions of the gist did it in that fashion, byte by byte. The newer version increments a .Net ulong and copies it to the counter block, so the little-Endian order is used for the counter portion (which is non-standard).

@lellis1936
Copy link

@hugoqribeiro, you're quite welcome.

You may find that the Feb 5, 2014 version of this gist does exactly what you want, since it features a constructor which accepts the initial full counter block directly rather than a nonce and counter. It may work immediately for your scenario. It also avoids a possible anomaly in later gists which I just commented about.

@bronze1man
Copy link

This is what bugs me. We want an implementation that ensures that other parties decrypting the text... get the text I encrypted. So using the nonce and the counter exactly the same way is crucial, right?

Sorry, but you need to understand other parties' code or their document, you may do some experiment to make it work. My version match my other parties from golang, and it works well.

@ammar-ahmed
Copy link

Thank you very much! It works perfect. I've even compared it to openssl implementation and it yields the same result. Good job!

Hi can you please share the working example, Many Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment