Merge pull request #3580 from MathieuBordere/mathieu/3567-ReplaceMasker

websockets: replace masker with more optimized one
This commit is contained in:
Maximilian Hils 2019-07-17 22:38:49 +02:00 committed by GitHub
commit 386772f8fc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 10 additions and 6 deletions

View File

@ -1,3 +1,6 @@
import sys
class Masker:
"""
Data sent from the server must be masked to prevent malicious clients
@ -12,12 +15,13 @@ class Masker:
self.offset = 0
def mask(self, offset, data):
result = bytearray(data)
for i in range(len(data)):
result[i] ^= self.key[offset % 4]
offset += 1
result = bytes(result)
return result
datalen = len(data)
offset_mod = offset % 4
data = int.from_bytes(data, sys.byteorder)
num_keys = (datalen + offset_mod + 3) // 4
mask = int.from_bytes((self.key * num_keys)[offset_mod:datalen +
offset_mod], sys.byteorder)
return (data ^ mask).to_bytes(datalen, sys.byteorder)
def __call__(self, data):
ret = self.mask(self.offset, data)