Skip to content

Commit

Permalink
Avoid temp array during encrypt and decrypt (#204)
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
bdraco and rytilahti committed Sep 23, 2021
1 parent 36c412a commit b3c8f97
Showing 1 changed file with 19 additions and 19 deletions.
38 changes: 19 additions & 19 deletions kasa/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,24 +89,32 @@ async def query(host: str, request: Union[str, Dict], retry_count: int = 3) -> D
# make mypy happy, this should never be reached..
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
def encrypt(request: str) -> bytes:
"""Encrypt a request for a TP-Link Smart Home Device.
:param request: plaintext request data
:return: ciphertext to be send over wire, in bytes
"""
key = TPLinkSmartHomeProtocol.INITIALIZATION_VECTOR

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:
cipherbyte = key ^ plainbyte
@staticmethod
def _xor_encrypted_payload(ciphertext):
key = TPLinkSmartHomeProtocol.INITIALIZATION_VECTOR
for cipherbyte in ciphertext:
plainbyte = key ^ cipherbyte
key = cipherbyte
buffer.append(cipherbyte)

return bytes(buffer)
yield plainbyte

@staticmethod
def decrypt(ciphertext: bytes) -> str:
Expand All @@ -115,14 +123,6 @@ def decrypt(ciphertext: bytes) -> str:
:param ciphertext: encrypted response data
:return: plaintext response
"""
key = TPLinkSmartHomeProtocol.INITIALIZATION_VECTOR
buffer = []

for cipherbyte in ciphertext:
plainbyte = key ^ cipherbyte
key = cipherbyte
buffer.append(plainbyte)

plaintext = bytes(buffer)

return plaintext.decode()
return bytes(
TPLinkSmartHomeProtocol._xor_encrypted_payload(ciphertext)
).decode()

0 comments on commit b3c8f97

Please sign in to comment.