<?php

namespace App\Services;

class BOBEncryptionService
{
    protected $initVector;

    public function __construct()
    {
        $this->initVector = pack("C*", 0x00, 0x01, 0x02, 0x03,
                                        0x04, 0x05, 0x06, 0x07,
                                        0x08, 0x09, 0x0a, 0x0b,
                                        0x0c, 0x0d, 0x0e, 0x0f);
    }

    public function encrypt(string $plainText, string $key): string
    {
        $key = $this->hextobin(md5($key));
        $encrypted = openssl_encrypt($plainText, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $this->initVector);
        return bin2hex($encrypted);
    }

    public function decrypt(string $encryptedText, string $key): string
    {

        $key = $this->hextobin(md5($key));
        $binaryData = $this->hextobin($encryptedText);
        return openssl_decrypt($binaryData, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $this->initVector);
    }

    private function hextobin(string $hexString): string
    {
        $binString = "";
        $length = strlen($hexString);

        for ($i = 0; $i < $length; $i += 2) {
            $binString .= pack("H*", substr($hexString, $i, 2));
        }

        return $binString;
    }
}
