Skip to content

Instantly share code, notes, and snippets.

@ChrisPritchard
Last active November 21, 2019 08:27
Show Gist options
  • Save ChrisPritchard/ed66b6083ad756d92a886e529934c537 to your computer and use it in GitHub Desktop.
Save ChrisPritchard/ed66b6083ad756d92a886e529934c537 to your computer and use it in GitHub Desktop.
open System.Security.Cryptography
let encrypt psk (iv: byte[]) (inData: byte[]) =
use aesObj = Aes.Create ()
aesObj.Mode <- CipherMode.ECB
aesObj.Padding <- PaddingMode.None
let zeroIv = Array.create 16 0uy
let encryptor = aesObj.CreateEncryptor (psk, zeroIv)
let counter = Array.init 16 (fun i -> iv.[i])
let rec incrementCounter i =
counter.[i] <- counter.[i] + 1uy
if counter.[i] <> 0uy || i = 0 then ()
else incrementCounter (i - 1)
let ctrOut = Array.create 16 0uy
let output = Array.create inData.Length 0uy
let mutable pos = 0
let rec encrypt () =
if pos >= inData.Length then
output
else
encryptor.TransformBlock (counter, 0, 16, ctrOut, 0) |> ignore
for i = 0 to 15 do
if pos < inData.Length then
output.[pos] <- inData.[pos] ^^^ ctrOut.[i]
pos <- pos + 1
incrementCounter 15
encrypt ()
encrypt ()
@ChrisPritchard
Copy link
Author

apparently implements AES 128 CTR mode, intended for compatibility with something in the nodejs world. dotnet doesnt support CTR (counter mode) encryption natively, but its basically ECB no padding with a counter buffer thing, like above.

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