Created
March 18, 2020 03:39
-
-
Save nathankellenicki/ae0f16dd5ea95f31f1285e74dae2a1bd to your computer and use it in GitHub Desktop.
HWid Decryption Functions
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
private _parseHandshake (handshake: Buffer) { | |
const publicKey = handshake.slice(25, 58); | |
const salt = handshake.slice(132, 136); | |
this._theirPublicKey = publicKey; | |
this._theirSalt = salt; | |
} | |
private _sendHandshake () { | |
const ecdh = crypto.createECDH("prime256v1"); | |
ecdh.generateKeys(); | |
// @ts-ignore | |
const publicKey = Buffer.from(ecdh.getPublicKey("binary", "compressed"), "binary"); | |
const sharedSecret = ecdh.computeSecret(this._theirPublicKey as Buffer); | |
const salt = Buffer.allocUnsafe(4); // TODO NK: Randomise this later | |
this._mySalt = salt; | |
this._secretKey = this._deriveSecretKey(sharedSecret); | |
this._bleDevice.writeToCharacteristic(Consts.BLECharacteristic.SESSION, Buffer.concat([publicKey, salt])); | |
} | |
private _deriveSecretKey (sharedSecret: Buffer) { | |
const iv = Buffer.concat([Buffer.alloc(9), Buffer.from("mattel"), Buffer.alloc(1)]); | |
let secretKey = sharedSecret.slice(0, 16); | |
const cipher = crypto.createCipheriv("aes-128-ctr", secretKey, iv); | |
while (iv[7] < 99) { | |
secretKey = cipher.update(secretKey); | |
iv[7]++; | |
} | |
return secretKey; | |
} | |
private _decryptMessage(data: Buffer) { | |
const len = data.readUInt16BE(5); | |
const encrypted = data.slice(8, len); | |
// @ts-ignore | |
const iv = Buffer.concat([data.slice(1, 5), this._theirSalt, this._mySalt, Buffer.alloc(4)]); | |
// @ts-ignore | |
const cipher = crypto.createDecipheriv("aes-128-ctr", this._secretKey.slice(0, 16), iv); | |
return cipher.update(encrypted); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment