-
-
Save hanswolff/8809275 to your computer and use it in GitHub Desktop.
// 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); | |
//} |
@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.
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.
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
@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).