Last active
July 24, 2024 08:59
-
-
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.
This file contains 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; | |
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
Ok thank