Skip to content

Instantly share code, notes, and snippets.

@bronze1man bronze1man/AesCtr.cs
Last active Jun 5, 2019

Embed
What would you like to do?
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;
}
}
}
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.