Skip to content

Instantly share code, notes, and snippets.

@analogrelay
Last active December 4, 2017 20:51
Show Gist options
  • Save analogrelay/7640498bbfb545240409b582ce7fd137 to your computer and use it in GitHub Desktop.
Save analogrelay/7640498bbfb545240409b582ce7fd137 to your computer and use it in GitHub Desktop.
WebSocket Decoder Script
document.writeln('<input style="width: 600px" id="hexcode" type="text" placeholder="hex values" />');
document.writeln('<button onclick="decode()">Decode</button>');
document.writeln('<div id="result" />');
var opcodes = [
'Continuation',
'Text',
'Binary',
'RESERVED',
'RESERVED',
'RESERVED',
'RESERVED',
'RESERVED',
'Close',
'Ping',
'Pong',
'RESERVED',
'RESERVED',
'RESERVED',
'RESERVED',
'RESERVED'
];
function decode() {
var result = '';
var hexCode : string = document.getElementById('hexcode').value;
hexCode = hexCode.replace(/Message Offset: \d+/, '').trim();
result += `<p>HEXCODE=${hexCode}`;
var bytes = [];
for (var i = 0; i < hexCode.length; i += 2) {
bytes.push(parseInt(hexCode.substr(i, 2), 16));
}
result += `<p>RAW BYTES=${bytes.map(n => n.toString(16)).join()}</p>`;
let fin = (bytes[0] & 0x80) != 0;
let opcode = bytes[0] & 0x0F;
result += `<p>FIN=${fin}, OPCODE=${opcodes[opcode]} (${opcode})</p>`;
let mask = (bytes[1] & 0x80) != 0;
let len = bytes[1] & 0x7F;
result += `<p>MASK=${mask}, LEN=${len}</p>`;
let cursor = 2;
let maskKey = [];
if(mask) {
let end = cursor + 4;
maskKey = bytes.slice(cursor, end)
cursor = end;
result += `<p>MASKKEY=${maskKey.map(n => n.toString(16)).join()}</p>`;
}
let payload = bytes.slice(cursor);
result += `<p>RAW PAYLOAD=${payload.map(n => n.toString(16)).join()}</p>`;
if(mask) {
// Unmask
payload = payload.map((byte, index) => byte ^ maskKey[index % maskKey.length]);
result += `<p>UNMASKED PAYLOAD=${payload.map(n => n.toString(16)).join()}</p>`;
}
result += `<p>PAYLOAD ASCII=${payload.map(n => String.fromCharCode(n)).join('')}</p>`;
document.getElementById('result').innerHTML = result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment