Skip to content

Commit

Permalink
fix: encryption input with wide characters (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
bdraco authored Jan 10, 2024
1 parent 554330b commit 5dae424
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 6 deletions.
3 changes: 2 additions & 1 deletion src/kasa_crypt/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@

def encrypt(string: str) -> bytes:
"""Encrypt."""
return _pack_header(len(string)) + _encrypt(string)
encoded = string.encode("utf-8")
return _pack_header(len(encoded)) + _encrypt(encoded)


__all__ = ["encrypt", "decrypt"]
3 changes: 1 addition & 2 deletions src/kasa_crypt/_crypt_impl.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,8 @@ cdef void _encrypt(const char *unencrypted, char** encrypted, Py_ssize_t length)
return # malloc failed
_encrypt_into(unencrypted, encrypted[0], length)

def encrypt(string: str) -> bytes:
def encrypt(py_byte_string: bytes) -> bytes:
cdef char* encrypted = NULL
py_byte_string = string.encode('utf-8')
cdef Py_ssize_t length = len(py_byte_string)
_encrypt(py_byte_string, &encrypted, length)
try:
Expand Down
3 changes: 1 addition & 2 deletions src/kasa_crypt/python_impl.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
def encrypt_pure_python(string: str) -> bytearray:
def encrypt_pure_python(unencrypted: bytes) -> bytearray:
"""Encrypt."""
unencrypted = string.encode()
key = 171
unencrypted_len = len(unencrypted)
encrypted = bytearray(unencrypted_len)
Expand Down
25 changes: 24 additions & 1 deletion tests/test_init.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
import struct

from kasa_crypt import decrypt, encrypt

Expand Down Expand Up @@ -34,10 +35,32 @@
)


def test_encrypt():
def test_encrypt_json():
d = json.dumps({"foo": 1, "bar": 2})
encoded = d.encode("utf-8")
encrypted = encrypt(d)
# encrypt adds a 4 byte header
assert struct.unpack(">I", encrypted[:4])[0] == len(encoded)
encrypted = encrypted[4:]
assert d == decrypt(encrypted)


def test_encrypt_utf8_json():
d = json.dumps({"漢字": 1, "bar": 2})
encoded = d.encode("utf-8")
encrypted = encrypt(d)
# encrypt adds a 4 byte header
assert struct.unpack(">I", encrypted[:4])[0] == len(encoded)
encrypted = encrypted[4:]
assert d == decrypt(encrypted)


def test_encrypt_utf8():
d = "漢字"
encoded = d.encode("utf-8")
encrypted = encrypt(d)
# encrypt adds a 4 byte header
assert struct.unpack(">I", encrypted[:4])[0] == len(encoded)
encrypted = encrypted[4:]
assert d == decrypt(encrypted)

Expand Down

0 comments on commit 5dae424

Please sign in to comment.