62 lines
1.7 KiB
JavaScript
62 lines
1.7 KiB
JavaScript
const crypto = require('crypto');
|
|
|
|
var CHUNICHUNICHUNIC = {};
|
|
|
|
const cccc_key = Buffer.from('CHUNICHUNICHUNIC', 'ascii');
|
|
|
|
CHUNICHUNICHUNIC.encrypt = function (data) {
|
|
var length = data.length;
|
|
if (length % 16 != 0) {
|
|
var padlen = 16-(length%16);
|
|
data = Buffer.concat([data, Buffer.alloc(padlen)]);
|
|
console.warn("Trying to encrypt non-padded data!");
|
|
length += padlen;
|
|
}
|
|
var cipher = crypto.createCipheriv('aes-128-ecb', cccc_key, null);
|
|
cipher.setAutoPadding(false);
|
|
var msg0 = Buffer.alloc(4);
|
|
msg0.writeUInt32LE(length+4, 0);
|
|
var msg1 = cipher.update(data);
|
|
var msg2 = cipher.final();
|
|
return Buffer.concat([msg0, msg1, msg2]);
|
|
}
|
|
|
|
CHUNICHUNICHUNIC.decrypt = function(msg) {
|
|
if (msg.length % 16 != 0 ) {
|
|
console.warn("Bad decrypt length: " + msg.length);
|
|
return;
|
|
}
|
|
var decipher = crypto.createDecipheriv('aes-128-ecb', cccc_key, null);
|
|
decipher.setAutoPadding(false);
|
|
var data1 = decipher.update(msg);
|
|
var data2 = decipher.final();
|
|
return Buffer.concat([data1, data2]);
|
|
}
|
|
|
|
CHUNICHUNICHUNIC.deframe = function(buf, ctx) {
|
|
var data, pending, msg;
|
|
if (!ctx.length) {
|
|
ctx.length = buf.readUInt32LE(0) - 4;
|
|
ctx.current = buf.slice(4);
|
|
if (ctx.length % 16 != 0) {
|
|
console.warn("Received mispadded packet: ", buf.toString('hex'));
|
|
}
|
|
} else {
|
|
ctx.current = Buffer.concat([ctx.current, buf]);
|
|
}
|
|
if (ctx.current.length > ctx.length) {
|
|
pending = ctx.current.slice(ctx.length);
|
|
msg = ctx.current.slice(0, ctx.length);
|
|
} else if (ctx.current.length == ctx.length) {
|
|
msg = ctx.current;
|
|
}
|
|
if (msg) {
|
|
ctx.length = 0;
|
|
data = CHUNICHUNICHUNIC.decrypt(msg);
|
|
ctx.current = null;
|
|
}
|
|
return {data: data, pending: pending};
|
|
}
|
|
|
|
module.exports = CHUNICHUNICHUNIC;
|