Reputation: 624
after attempting to connect to a websocket server and send information to it i am running in to an encoding issue.
i have a string and the encoded(hex) version of this string. Lets say my string is 'getpremium'
how do I convert that string into an array of these hex values?
[0x81, 0x8c, 0x86, 0x78, 0xe3, 0xc6, 0xe1, 0x1d,
0x97, 0xb6, 0xf4, 0x1d, 0x8e, 0xaf, 0xf3, 0x15,
0xee, 0xcc]
I can decode these values back in to the original string, but I am at a loss as to how they are encoded in to these hex values. Basically how can i encode that string 'getpremium' to get those encoded values as to send them to this websocket server. Any method using either python or node.js is applicable.
javascript decoding method:
var _ = require("underscore");
function decode(data){
if (typeof data === 'string') {
data = _.map(data, function(chr){ return chr.charCodeAt(0); });
}
var datalength = data[1] & 127;
var indexFirstMask = 2;
if (datalength == 126) {
indexFirstMask = 4;
} else if (datalength == 127) {
indexFirstMask = 10;
}
var masks = data.slice(indexFirstMask,indexFirstMask + 4);
var i = indexFirstMask + 4;
var index = 0;
var output = "";
while (i < data.length) {
x = data[i++] ^ masks[index++ % 4];
output += String.fromCharCode(x);
}
return output;
}
Upvotes: 1
Views: 699
Reputation: 995
Try this:
import os
def encode(rawBytes):
data = [ord(i) for i in rawBytes]
length = len(rawBytes) + 128
Bytes = [0x81, length]
index = 2
masks = os.urandom(4)
for i in range(len(masks)):
Bytes.insert(i + index, masks[i])
for i in range(len(data)):
data[i] ^= masks[i % 4]
Bytes.insert(i + index + 4, data[i])
return [hex(i) for i in Bytes]
Upvotes: 2