mirror of
https://github.com/python-kasa/python-kasa.git
synced 2025-04-27 00:56:23 +00:00
Support Unicode strings in encrypt/decrypt (#125)
This commit is contained in:
parent
e612560b35
commit
a6d515b5cb
@ -86,14 +86,16 @@ class TPLinkSmartHomeProtocol:
|
|||||||
:return: ciphertext request
|
:return: ciphertext request
|
||||||
"""
|
"""
|
||||||
key = TPLinkSmartHomeProtocol.INITIALIZATION_VECTOR
|
key = TPLinkSmartHomeProtocol.INITIALIZATION_VECTOR
|
||||||
buffer = bytearray(struct.pack(">I", len(request)))
|
|
||||||
|
|
||||||
for char in request:
|
plainbytes = request.encode()
|
||||||
cipher = key ^ ord(char)
|
buffer = bytearray(struct.pack(">I", len(plainbytes)))
|
||||||
key = cipher
|
|
||||||
buffer.append(cipher)
|
|
||||||
|
|
||||||
return buffer
|
for plainbyte in plainbytes:
|
||||||
|
cipherbyte = key ^ plainbyte
|
||||||
|
key = cipherbyte
|
||||||
|
buffer.append(cipherbyte)
|
||||||
|
|
||||||
|
return bytes(buffer)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def decrypt(ciphertext: bytes) -> str:
|
def decrypt(ciphertext: bytes) -> str:
|
||||||
@ -106,13 +108,11 @@ class TPLinkSmartHomeProtocol:
|
|||||||
key = TPLinkSmartHomeProtocol.INITIALIZATION_VECTOR
|
key = TPLinkSmartHomeProtocol.INITIALIZATION_VECTOR
|
||||||
buffer = []
|
buffer = []
|
||||||
|
|
||||||
ciphertext_str = ciphertext.decode('latin-1')
|
for cipherbyte in ciphertext:
|
||||||
|
plainbyte = key ^ cipherbyte
|
||||||
|
key = cipherbyte
|
||||||
|
buffer.append(plainbyte)
|
||||||
|
|
||||||
for char in ciphertext_str:
|
plaintext = bytes(buffer)
|
||||||
plain = key ^ ord(char)
|
|
||||||
key = ord(char)
|
|
||||||
buffer.append(chr(plain))
|
|
||||||
|
|
||||||
plaintext = ''.join(buffer)
|
return plaintext.decode()
|
||||||
|
|
||||||
return plaintext
|
|
||||||
|
@ -10,3 +10,23 @@ class TestTPLinkSmartHomeProtocol(TestCase):
|
|||||||
# encrypt adds a 4 byte header
|
# encrypt adds a 4 byte header
|
||||||
encrypted = encrypted[4:]
|
encrypted = encrypted[4:]
|
||||||
self.assertEqual(d, TPLinkSmartHomeProtocol.decrypt(encrypted))
|
self.assertEqual(d, TPLinkSmartHomeProtocol.decrypt(encrypted))
|
||||||
|
|
||||||
|
def test_encrypt_unicode(self):
|
||||||
|
d = "{'snowman': '\u2603'}"
|
||||||
|
|
||||||
|
e = bytes([208, 247, 132, 234, 133, 242, 159, 254, 144, 183,
|
||||||
|
141, 173, 138, 104, 240, 115, 84, 41])
|
||||||
|
|
||||||
|
encrypted = TPLinkSmartHomeProtocol.encrypt(d)
|
||||||
|
# encrypt adds a 4 byte header
|
||||||
|
encrypted = encrypted[4:]
|
||||||
|
|
||||||
|
self.assertEqual(e, encrypted)
|
||||||
|
|
||||||
|
def test_decrypt_unicode(self):
|
||||||
|
e = bytes([208, 247, 132, 234, 133, 242, 159, 254, 144, 183,
|
||||||
|
141, 173, 138, 104, 240, 115, 84, 41])
|
||||||
|
|
||||||
|
d = "{'snowman': '\u2603'}"
|
||||||
|
|
||||||
|
self.assertEqual(d, TPLinkSmartHomeProtocol.decrypt(e))
|
||||||
|
Loading…
x
Reference in New Issue
Block a user