"""tests/test_crypto.py""" from tuya_re import crypto def test_crc16_known_answer(): # CRC-16 with init=0xFFFF, poly 0xA001 (MODBUS variant) — matches the # device firmware (verified against ha_tuya_ble's implementation). assert crypto.crc16(b"123456789") == 0x4B37 def test_crc16_empty(): assert crypto.crc16(b"") == 0xFFFF def test_login_key_uses_first_6_chars_only(): import hashlib key = crypto.login_key("abcdef0123456789") assert key == hashlib.md5(b"abcdef").digest() assert len(key) == 16 def test_session_key(): import hashlib srand = bytes(range(6)) key = crypto.session_key("abcdef0123456789", srand) assert key == hashlib.md5(b"abcdef" + srand).digest() def test_encrypt_decrypt_roundtrip(): key = bytes(16) iv = bytes(range(16)) plain = b"A" * 32 # must be 16-aligned ct = crypto.aes_cbc_encrypt(key, iv, plain) assert ct != plain assert crypto.aes_cbc_decrypt(key, iv, ct) == plain def test_aes_ecb_known_vector(): key = b"0123456789abcdef" ct = crypto.aes_ecb_encrypt(key, b"hello tuya 12345") assert ( ct.hex() == "892dc5a803b72acfcbacb4f40ace9064377222e061a924c591cd9c27ea163ed4" ) assert crypto.aes_ecb_decrypt(key, ct) == b"hello tuya 12345" def test_aes_ecb_pkcs7_roundtrip(): key = bytes(16) for n in (0, 1, 15, 16, 17, 32): msg = b"x" * n assert crypto.aes_ecb_decrypt(key, crypto.aes_ecb_encrypt(key, msg)) == msg def test_crc32_matches_zlib(): import zlib data = b"\x00\x00\x55\xaa\x00\x00\x00\x01" assert crypto.crc32(data) == (zlib.crc32(data) & 0xFFFFFFFF)