2019-12-08 22:43:49 +01:00
|
|
|
import base64
|
|
|
|
import hashlib
|
|
|
|
from Crypto import Random
|
|
|
|
from Crypto.Cipher import AES
|
|
|
|
|
|
|
|
|
|
|
|
class AESCipher:
|
|
|
|
"""
|
|
|
|
Simple AES cipher used to provide cookie support to the frontend.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, key: str) -> None:
|
|
|
|
self.__padamt = 16
|
2022-10-15 20:56:30 +02:00
|
|
|
self.__key = hashlib.sha256(key.encode("utf-8")).digest()
|
2019-12-08 22:43:49 +01:00
|
|
|
|
2021-05-31 20:09:40 +02:00
|
|
|
def _pad(self, s: str) -> str:
|
2020-01-07 22:29:07 +01:00
|
|
|
intermediate = f"{len(s)}.{s}"
|
2019-12-08 22:43:49 +01:00
|
|
|
while len(intermediate) % self.__padamt != 0:
|
2022-10-15 20:56:30 +02:00
|
|
|
intermediate = intermediate + "-"
|
2019-12-08 22:43:49 +01:00
|
|
|
return intermediate
|
|
|
|
|
2021-05-31 20:09:40 +02:00
|
|
|
def _unpad(self, s: str) -> str:
|
2022-10-15 20:56:30 +02:00
|
|
|
length, string = s.split(".", 1)
|
2019-12-08 22:43:49 +01:00
|
|
|
intlength = int(length)
|
|
|
|
return string[:intlength]
|
|
|
|
|
|
|
|
def encrypt(self, raw: str) -> str:
|
2021-05-31 20:09:40 +02:00
|
|
|
raw = self._pad(raw)
|
2021-05-31 20:07:03 +02:00
|
|
|
random = Random.new()
|
2019-12-08 22:43:49 +01:00
|
|
|
iv = random.read(AES.block_size)
|
|
|
|
cipher = AES.new(self.__key, AES.MODE_CBC, iv)
|
2022-10-15 20:56:30 +02:00
|
|
|
return base64.b64encode(
|
|
|
|
iv + cipher.encrypt(raw.encode("utf-8")), altchars=b"._"
|
|
|
|
).decode("utf-8")
|
2019-12-08 22:43:49 +01:00
|
|
|
|
|
|
|
def decrypt(self, encoded: str) -> str:
|
2022-10-15 20:56:30 +02:00
|
|
|
enc = base64.b64decode(encoded.encode("utf-8"), altchars=b"._")
|
|
|
|
iv = enc[: AES.block_size]
|
2019-12-08 22:43:49 +01:00
|
|
|
cipher = AES.new(self.__key, AES.MODE_CBC, iv)
|
2022-10-15 20:56:30 +02:00
|
|
|
return self._unpad(cipher.decrypt(enc[AES.block_size :]).decode("utf-8"))
|