| 1 |
"""Module concerned with encryption of the data""" |
| 2 |
import base64 |
| 3 |
|
| 4 |
from Crypto.Cipher import AES |
| 5 |
from Crypto import Random |
| 6 |
|
| 7 |
from aioairq.exceptions import InvalidAuth |
| 8 |
|
| 9 |
|
| 10 |
class AESCipher: |
| 11 |
_bs = AES.block_size # 16 |
| 12 |
|
| 13 |
def __init__(self, passw: str): |
| 14 |
"""Class responsible for decryption of AirQ responses |
| 15 |
|
| 16 |
Main idea of the class is to expose convenience methods |
| 17 |
``encode`` and ``decode`` while the key is stored as a private attribute, |
| 18 |
conveniently computed from the password upon initialisation |
| 19 |
of the class' instance |
| 20 |
|
| 21 |
Parameters |
| 22 |
---------- |
| 23 |
passw : str |
| 24 |
Device's password |
| 25 |
""" |
| 26 |
self._key = self._pass2aes(passw) |
| 27 |
|
| 28 |
def encode(self, data: str) -> str: |
| 29 |
iv = Random.new().read(AES.block_size) |
| 30 |
cipher = AES.new(self._key, AES.MODE_CBC, iv) |
| 31 |
|
| 32 |
encoded = data.encode("utf-8") |
| 33 |
encrypted = iv + cipher.encrypt(self._pad(encoded)) |
| 34 |
|
| 35 |
return base64.b64encode(encrypted).decode("utf-8") |
| 36 |
|
| 37 |
def decode(self, encrypted: str) -> str: |
| 38 |
decoded = base64.b64decode(encrypted) |
| 39 |
iv = decoded[: self._bs] |
| 40 |
cipher = AES.new(self._key, AES.MODE_CBC, iv) |
| 41 |
decrypted = cipher.decrypt(decoded[self._bs :]) |
| 42 |
try: |
| 43 |
# Currently the device does not support proper authentication. |
| 44 |
# The success or failure of the authentication based on the ability |
| 45 |
# to decode the response from the device. |
| 46 |
decoded = decrypted.decode("utf-8") |
| 47 |
except UnicodeDecodeError: |
| 48 |
raise InvalidAuth( |
| 49 |
"Failed to decode a message. Incorrect password" |
| 50 |
) from None |
| 51 |
return self._unpad(decoded) |
| 52 |
|
| 53 |
@staticmethod |
| 54 |
def _pad(data: bytes) -> bytes: |
| 55 |
length = 16 - (len(data) % 16) |
| 56 |
return data + bytes(chr(length) * length, "utf-8") |
| 57 |
|
| 58 |
@staticmethod |
| 59 |
def _unpad(data: str) -> str: |
| 60 |
return data[: -ord(data[-1])] |
| 61 |
|
| 62 |
@staticmethod |
| 63 |
def _pass2aes(passw: str) -> str: |
| 64 |
"""Derive the key for AES256 from the device password |
| 65 |
|
| 66 |
The key for AES256 is derived from the password by appending |
| 67 |
zeros to a total key length of 32. |
| 68 |
""" |
| 69 |
key = passw.encode("utf-8") |
| 70 |
if len(key) < 32: |
| 71 |
key += b"0" * (32 - len(key)) |
| 72 |
elif len(key) > 32: |
| 73 |
key = key[:32] |
| 74 |
return key |