Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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);
//}
@ghost

This comment has been minimized.

Copy link

@ghost ghost commented Oct 5, 2014

Any chance you can give a call-example (from a main of a console app.) of how to encrypt/decrypt a plain text with your code?
And how to use it if there is actually a random IV present?
Thanks

@masantiago

This comment has been minimized.

Copy link

@masantiago masantiago commented Feb 14, 2015

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

@anzun

This comment has been minimized.

Copy link

@anzun anzun commented Oct 16, 2015

Hello, could you please give me a hint how to call the Aes128CounterMode?

Aes128CounterMode aes128 = new Aes128CounterMode(Counter);
aes128.GenerateKey(); // this is not generating a key? is it?
aes128.GenerateIV();
byte[] byteKey = aes128.Key; // aes128.Key is Null
byte[] byteIV = aes128.IV;
aes128.CreateEncryptor(byteKey, byteIV);

@anzun

This comment has been minimized.

Copy link

@anzun anzun commented Oct 16, 2015

2nd question: what has to be adjusted in the above code to create an Aes256CounterMode

@mochasoft

This comment has been minimized.

Copy link

@mochasoft mochasoft commented Nov 5, 2015

try

Aes128CounterMode am;
ICryptoTransform ict;
am = new Aes128CounterMode(iv);
ict = am.CreateEncryptor(key, null);
ict.TransformBlock(input, 0, input.Length, result, 0);

Good job making the class. It works correct when accessing a Mac running as a SSH2 server.

@martinprikryl

This comment has been minimized.

Copy link

@martinprikryl martinprikryl commented Jul 5, 2018

Despite some previous comments, the code works correctly.

For a compact standalone code based on this, see https://stackoverflow.com/q/6374437/850848#51188472

@ramiz-shahid

This comment has been minimized.

Copy link

@ramiz-shahid ramiz-shahid commented May 12, 2019

can you please give me example with data and key only ? i am confused with is counter now ?

@bronze1man

This comment has been minimized.

Copy link

@bronze1man bronze1man commented Jun 5, 2019

As the class AesManaged no exist vs2017 and uwp environment, i wrote a new one that works on that environment, it may help me and others .
https://gist.github.com/bronze1man/68f88494c88eb3fc647c447b36138134

@bigphil2048

This comment has been minimized.

Copy link

@bigphil2048 bigphil2048 commented Sep 12, 2019

Could you please assist. So far I've tried various code samples but yours seems to get the closest to the answer. I need to decrypt a received message to further use the information stored therein.

static string AesKey = "BF79381658C20F2886A280E3358F12EA"; static string AesIV = "2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b2b"; static string EncText = "F85C9646B3E57B1F1F46"; static string ExpectedResult = "8000fd10000000002426";
I can get to the result using: [http://www.cryptogrium.com/aes-ctr.html]

With your code I'm getting this result: 3F-00-3F-10-00-00-00-00-24-26

Code to call this lib:
` static string DecryptStringFromBytes_AesCtr(byte[] cipherText, byte[] Key, byte[] IV)
{
string Result = "";

        try
        {
            using (Aes128CounterMode aesAlg = new Aes128CounterMode(IV))
            {

                ICryptoTransform decryptor = aesAlg.CreateDecryptor(Key, IV);

                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            Result = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Result = "Error: " + ex.Message;
        }
        return Result;
    }

`

Code I'm using to build byte arrays from hex values:
` static byte[] HexValuesToBytes(string HexValues)
{
byte[] Result = new byte[HexValues.Length / 2];

        for (int i = 0; i < (HexValues.Length / 2); i++)
        {
            string tStr = HexValues.Substring(i * 2, 2);
            uint hval = Convert.ToUInt32(tStr, 16);
            Result[i] = Convert.ToByte(hval);
        }

        return Result;

    }

`
Any help will be appreciated.

Thanks
Philip

@lellis1936

This comment has been minimized.

Copy link

@lellis1936 lellis1936 commented Oct 9, 2019

Been a while since the question was posted, but...

bigphil2048, the encryption class is working. Your problem is that you are trying to pass a CryptoStream (binary data) through a StreamReader. Not a good idea because there are code translations that happen which garble the result.

Instead of returning a string from your decryption you must return a byte array, e.g. replace

                       using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            Result = srDecrypt.ReadToEnd();
                        }

with

                         using (BinaryReader srDecrypt = new BinaryReader(csDecrypt))
                        {
                            Result = srDecrypt.ReadBytes(10);
                        }

(other coding changes are needed to make this compile, but you should get the drift)

@lellis1936

This comment has been minimized.

Copy link

@lellis1936 lellis1936 commented Oct 17, 2019

The encryption/decryption speed can be about doubled by using some UNSAFE C# code (if acceptable in your project). I have code if anyone is interested.

@AlliterativeAlice

This comment has been minimized.

Copy link

@AlliterativeAlice AlliterativeAlice commented Nov 9, 2019

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

This comment has been minimized.

Copy link

@lellis1936 lellis1936 commented Nov 9, 2019

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

This comment has been minimized.

Copy link
Owner Author

@hanswolff hanswolff commented Jun 23, 2020

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.