Skip to content

Instantly share code, notes, and snippets.

@Srushtika
Last active January 11, 2021 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Srushtika/59ad924e56efb987af5a4eb4529172ac to your computer and use it in GitHub Desktop.
Save Srushtika/59ad924e56efb987af5a4eb4529172ac to your computer and use it in GitHub Desktop.
WebSockets server tutorial
// Allocate somewhere to store the final message data
const data = Buffer.alloc(payloadLength);
// Only unmask the data if the masking bit was set to 1
if (isMasked) {
// Loop through the source buffer one byte at a time, keeping track of which
// byte in the masking key to use in the next XOR calculation
for (let i = 0, j = 0; i < payloadLength; ++i, j = i % 4) {
// Extract the correct byte mask from the masking key
const shift = j == 3 ? 0 : (3 - j) << 3;
const mask = (shift == 0 ? maskingKey : (maskingKey >>> shift)) & 0xFF;
// Read a byte from the source buffer
const source = buffer.readUInt8(currentOffset++);
// XOR the source byte and write the result to the data
buffer.data.writeUInt8(mask ^ source, i);
}
} else {
// Not masked - we can just read the data as-is
buffer.copy(data, 0, currentOffset++);
}
@Kolahzary
Copy link

typo fixes:

line 10:

const mask = (shift = 0 ? maskingKey : (maskingKey >>> shift)) & 0xFF;
should be:
const mask = (shift == 0 ? maskingKey : (maskingKey >>> shift)) & 0xFF;

line 14:

buffer data.writeUInt8(mask ^ source, i);
should be:
buffer.data.writeUInt8(mask ^ source, i);

@Srushtika
Copy link
Author

typo fixes:

line 10:

const mask = (shift = 0 ? maskingKey : (maskingKey >>> shift)) & 0xFF;
should be:
const mask = (shift == 0 ? maskingKey : (maskingKey >>> shift)) & 0xFF;

line 14:

buffer data.writeUInt8(mask ^ source, i);
should be:
buffer.data.writeUInt8(mask ^ source, i);

Fixed, thanks!

@prdaneshi
Copy link

line 9:
const shift = j = 3 ? 0 : (3 - j) << 3;
should be:
const shift = j == 3 ? 0 : (3 - j) << 3;

line 14:
buffer.data.writeUInt8(mask ^ source, i);
should be:
data.writeUInt8(mask ^ source, i);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment