Created
January 1, 2022 11:04
-
-
Save reitowo/9c0ae4ea89885d69c385fd2b2138d1ca to your computer and use it in GitHub Desktop.
Stream Crypto AES-256-CTR C# Implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Security.Cryptography; | |
namespace TgServer.Crypto; | |
public sealed class AesCtr { | |
private readonly byte[] _key; | |
private readonly byte[] _counter; | |
private readonly byte[] _blockKey; | |
private readonly ICryptoTransform _encryptor; | |
private long _bytesTransformed = 0; | |
public AesCtr(byte[] key, byte[] iv) { | |
this._key = key; | |
_counter = iv; | |
_blockKey = new byte[16]; | |
var aes = Aes.Create(); | |
aes.Mode = CipherMode.ECB; | |
aes.Padding = PaddingMode.None; | |
_encryptor = aes.CreateEncryptor(key, new byte[16]); | |
} | |
public byte[] Encrypt(byte[] data) { | |
var ret = new byte[data.Length]; | |
for (var i = 0; i < data.Length; ++i) { | |
var keyIdx = _bytesTransformed % 16; | |
if (keyIdx == 0) { | |
_encryptor.TransformBlock(_counter, 0, 16, _blockKey, 0); | |
for (var k = 15; k >= 0; k--) { | |
_counter[k]++; | |
if (_counter[k] != 0) { | |
break; | |
} | |
} | |
} | |
ret[i] = (byte) (data[i] ^ _blockKey[keyIdx]); | |
_bytesTransformed++; | |
} | |
return ret; | |
} | |
public byte[] Decrypt(byte[] data) { | |
return Encrypt(data); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment