Search code examples
pythonwebsocketmask

Mask & Unmask websocket data in python


I'm trying to create a python websocket class that can connect to a websocket server and I need help writing a function that can mask and unmask data. I have an similar websocket class in PHP that looks like this:

function unmask($text) {
$length = ord($text[1]) & 127;
if($length == 126) {
    $masks = substr($text, 4, 4);
    $data = substr($text, 8);
}
elseif($length == 127) {
    $masks = substr($text, 10, 4);
    $data = substr($text, 14);
}
else {
    $masks = substr($text, 2, 4);
    $data = substr($text, 6);
}
$text = "";
for ($i = 0; $i < strlen($data); ++$i) {
    $text .= $data[$i] ^ $masks[$i%4];
}
return $text;

}

function mask($text){
$b1 = 0x80 | (0x1 & 0x0f);
$length = strlen($text);

if($length <= 125)
    $header = pack('CC', $b1, $length);
elseif($length > 125 && $length < 65536)
    $header = pack('CCn', $b1, 126, $length);
elseif($length >= 65536)
    $header = pack('CCNN', $b1, 127, $length);
return $header.$text;
}

So I tried to create the same thing in Python:

def mask(text):
    b1 = 0x80 | (0x1 & 0x0f)
    length = len(text)

    if length <= 125:
        header = struct.pack('CC', b1, length)
    if length > 125 & length < 65536:
        header = struct.pack('CCn', b1, 126, length)
    if length <= 65536:
        header = struct.pack('CCNN', b1, 127, length)
    return header + text

And it returns an error:

Bad char in struct format

If anyone could help me write the function that would be great. Thanks!


Solution

  • I found an really helpful script that did exactly what i needed.

    http://sidekick.windforwings.com/2013/03/minimal-websocket-broadcast-server-in.html