Last active
November 21, 2019 08:27
-
-
Save ChrisPritchard/ed66b6083ad756d92a886e529934c537 to your computer and use it in GitHub Desktop.
straight one-for-one conversion of https://gist.github.com/jonasdw/bddbe8d5256b5a05001db8f9a480923b
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
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 () |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.