Last active
November 21, 2019 08:00
-
-
Save jonasdw/bddbe8d5256b5a05001db8f9a480923b to your computer and use it in GitHub Desktop.
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
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; | |
} |
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
var crypto = require('crypto'); | |
function encrypt(data, key) { | |
var hash = crypto.createHash('sha1'); | |
hash.update(key); | |
var key = hash.digest().slice(0, 16); | |
var ivBuffer = Buffer.alloc(16); | |
var cipher = crypto.createCipheriv('aes-128-ctr', key, ivBuffer); | |
var crypted = cipher.update(data, 'utf8', 'hex'); | |
crypted += cipher.final('hex'); | |
return crypted; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment