Avoid temp array during encrypt and decrypt (#204)

* Avoid temp array during encrypt

* black

* Update kasa/protocol.py

Co-authored-by: Teemu R. <tpr@iki.fi>

* Update kasa/protocol.py

* update decrypt as well

Co-authored-by: Teemu R. <tpr@iki.fi>
This commit is contained in:
J. Nick Koston 2021-09-23 11:11:16 -05:00 committed by GitHub
parent 36c412a9c2
commit b3c8f9769c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -89,6 +89,13 @@ class TPLinkSmartHomeProtocol:
# make mypy happy, this should never be reached.. # make mypy happy, this should never be reached..
raise SmartDeviceException("Query reached somehow to unreachable") raise SmartDeviceException("Query reached somehow to unreachable")
@staticmethod
def _xor_payload(unencrypted):
key = TPLinkSmartHomeProtocol.INITIALIZATION_VECTOR
for unencryptedbyte in unencrypted:
key = key ^ unencryptedbyte
yield key
@staticmethod @staticmethod
def encrypt(request: str) -> bytes: def encrypt(request: str) -> bytes:
"""Encrypt a request for a TP-Link Smart Home Device. """Encrypt a request for a TP-Link Smart Home Device.
@ -96,17 +103,18 @@ class TPLinkSmartHomeProtocol:
:param request: plaintext request data :param request: plaintext request data
:return: ciphertext to be send over wire, in bytes :return: ciphertext to be send over wire, in bytes
""" """
key = TPLinkSmartHomeProtocol.INITIALIZATION_VECTOR
plainbytes = request.encode() plainbytes = request.encode()
buffer = bytearray(struct.pack(">I", len(plainbytes))) return struct.pack(">I", len(plainbytes)) + bytes(
TPLinkSmartHomeProtocol._xor_payload(plainbytes)
)
for plainbyte in plainbytes: @staticmethod
cipherbyte = key ^ plainbyte def _xor_encrypted_payload(ciphertext):
key = TPLinkSmartHomeProtocol.INITIALIZATION_VECTOR
for cipherbyte in ciphertext:
plainbyte = key ^ cipherbyte
key = cipherbyte key = cipherbyte
buffer.append(cipherbyte) yield plainbyte
return bytes(buffer)
@staticmethod @staticmethod
def decrypt(ciphertext: bytes) -> str: def decrypt(ciphertext: bytes) -> str:
@ -115,14 +123,6 @@ class TPLinkSmartHomeProtocol:
:param ciphertext: encrypted response data :param ciphertext: encrypted response data
:return: plaintext response :return: plaintext response
""" """
key = TPLinkSmartHomeProtocol.INITIALIZATION_VECTOR return bytes(
buffer = [] TPLinkSmartHomeProtocol._xor_encrypted_payload(ciphertext)
).decode()
for cipherbyte in ciphertext:
plainbyte = key ^ cipherbyte
key = cipherbyte
buffer.append(plainbyte)
plaintext = bytes(buffer)
return plaintext.decode()