#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import base64
import hashlib
import Cryptodome.Random as Random
import Cryptodome.Cipher.AES as AES
import io


class AESCipher(object):

    def __init__(self, key):
        self.bs = AES.block_size
        self.key = hashlib.sha256(key.encode()).digest()

    def _pad(self, s):
        return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)

    @ staticmethod
    def _unpad(s):
        return s[:-ord(s[len(s)-1:])]

    def encrypt(self, raw):
        raw = self._pad(raw)
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return iv + cipher.encrypt(raw.encode("utf-8"))

    def decrypt(self, byte):
        iv = byte[:AES.block_size]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return self._unpad(
            cipher.decrypt(byte[AES.block_size:])).decode('utf-8')

    def encrypt_base64(self, raw):
        return base64.b64encode(self.encrypt(raw))

    def decrypt_base64(self, enc):
        enc = base64.b64decode(enc)
        return self.decrypt(enc)

    def encrypt_byte(self, plain_bytes) -> bytes:
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CFB, iv)
        return iv + cipher.encrypt(plain_bytes)

    def decrypt_byte(self, encrypted_byte) -> bytes:
        iv = encrypted_byte[:AES.block_size]
        cipher = AES.new(self.key, AES.MODE_CFB, iv)
        return cipher.decrypt(encrypted_byte[AES.block_size:])

    def encrypt_file(self, in_file, out_file):
        with open(in_file, 'rb') as inf, open(out_file, 'wb') as outf:
            outf.write(self.encrypt_byte(inf.read()))

    def decrypt_file2bytesio(self, crypted_file):
        with open(crypted_file, 'rb') as inf:
            return io.BytesIO(self.decrypt_byte(inf.read()))
