Skip to content

Instantly share code, notes, and snippets.

@bronze1man
Last active July 24, 2024 08:59
Show Gist options
  • Save bronze1man/68f88494c88eb3fc647c447b36138134 to your computer and use it in GitHub Desktop.
Save bronze1man/68f88494c88eb3fc647c447b36138134 to your computer and use it in GitHub Desktop.
c# aes ctr implement works on vs2017/uwp , seen testRun for usage example.
using System.Security.Cryptography;
using System.Diagnostics;
using System;
using System.Runtime.InteropServices.WindowsRuntime;
namespace abc {
public sealed class AesCtr {
public static void testRun() {
for (var i2 = 0; i2 < 3; i2++) {
var outputV = Encrypt(new byte[32], new byte[16], new byte[30]);
for (var i = 0; i < 30; i++) {
Debug.WriteLine("runTest " + i.ToString() + " " + outputV[i].ToString());
}
}
}
public static byte[] Encrypt([ReadOnlyArray]byte[] psk, [ReadOnlyArray]byte[] iv, [ReadOnlyArray]byte[] inData) {
var aesObj = Aes.Create();
aesObj.Mode = CipherMode.ECB;
aesObj.Padding = PaddingMode.None;
var zeroIv = new byte[16];
var Encryptor = aesObj.CreateEncryptor(psk, zeroIv);
var counter = new byte[16]; // copy input iv (do not modify it)
for (var i = 0; i < 16; i++) {
counter[i] = iv[i];
}
var ctrOut = new byte[16];
var output = new byte[inData.Length];
var pos = 0;
while (true) {
if (pos >= inData.Length) {
break;
}
Encryptor.TransformBlock(counter, 0, 16, ctrOut, 0);
for (var i = 0; i < 16; i++) {
if (pos >= inData.Length) {
break;
}
output[pos] = (byte)(inData[pos] ^ ctrOut[i]);
pos++;
}
// increment counter
for (var i = 15; i >= 0; i--) {
counter[i]++;
if (counter[i] != 0) {
break;
}
}
}
return output;
}
}
}
@pbertin-oneex
Copy link

Works nice mate! Thank you for sharing. Did help me a lot!

Sad that CreateEncryptor is not accepting ReadOnlySpan. It would be much cleaner for the Encrypt function's signature. :)

@binbon2d
Copy link

binbon2d commented Mar 8, 2024

Please share Decrypt

@bronze1man
Copy link
Author

bronze1man commented Mar 11, 2024

@binbon2d there is not Decrypt of aes-ctr. Just call Encrypt with the same psk,iv and encrypted data, you will get plain data(or decrypted data)

Warning about aes-ctr:

  • Never repeat the pair of key and iv range even once, or your data will be decrypted very easily by two encrypted datas with same key and iv.
  • Aes-ctr do not have any correct check of your data.You may need hash or hmac to rejected incorrected data. Or others can change the content of your data by change the encrypted data without your software notice. You will get some strange bytes because of this.
  • Try use tls1.3 or aes-gcm or ChaCha20-Poly1305 if you design new software and do not understand what i said or the wiki said. Those algorithms may be safer and faster

https://pkg.go.dev/crypto/cipher#NewCTR
https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation

@binbon2d
Copy link

Ok thank

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