tplink-smarthome-crypto
Version:
TP-Link Smarthome Crypto
78 lines • 2.46 kB
JavaScript
;
/**
* TP-Link Smarthome Crypto
*
* TCP communication includes a 4 byte header, UDP does not.
* @packageDocumentation
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.decryptWithHeader = exports.decrypt = exports.encryptWithHeader = exports.encrypt = void 0;
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Encrypts input where each byte is XOR'd with the previous encrypted byte.
*
* @param input - Data to encrypt
* @param firstKey - Value to XOR first byte of input
* @returns encrypted buffer
*/
function encrypt(input, firstKey = 0xab) {
const buf = Buffer.from(input);
let key = firstKey;
for (let i = 0; i < buf.length; i += 1) {
// eslint-disable-next-line no-bitwise
buf[i] ^= key;
key = buf[i];
}
return buf;
}
exports.encrypt = encrypt;
/**
* Encrypts input that has a 4 byte big-endian length header;
* each byte is XOR'd with the previous encrypted byte.
*
* @param input - Data to encrypt
* @param firstKey - Value to XOR first byte of input
* @returns encrypted buffer with header
*/
function encryptWithHeader(input, firstKey = 0xab) {
const msgBuf = encrypt(input, firstKey);
const outBuf = Buffer.alloc(msgBuf.length + 4);
outBuf.writeUInt32BE(msgBuf.length, 0);
msgBuf.copy(outBuf, 4);
return outBuf;
}
exports.encryptWithHeader = encryptWithHeader;
/**
* Decrypts input where each byte is XOR'd with the previous encrypted byte.
*
* @param input - Encrypted Buffer
* @param firstKey - Value to XOR first byte of input
* @returns decrypted buffer
*/
function decrypt(input, firstKey = 0xab) {
const buf = Buffer.from(input);
let key = firstKey;
for (let i = 0; i < buf.length; i += 1) {
const nextKey = buf[i];
// eslint-disable-next-line no-bitwise
buf[i] ^= key;
key = nextKey;
}
return buf;
}
exports.decrypt = decrypt;
/**
* Decrypts input that has a 4 byte big-endian length header;
* each byte is XOR'd with the previous encrypted byte
*
* @param input - Encrypted Buffer with header
* @param firstKey - Value to XOR first byte of input
* @returns decrypted buffer
*/
function decryptWithHeader(input, firstKey = 0xab) {
if (input instanceof Buffer)
return decrypt(input.subarray(4), firstKey);
return decrypt(input.slice(4), firstKey);
}
exports.decryptWithHeader = decryptWithHeader;
//# sourceMappingURL=index.js.map