<?php

final class Encryption {
    private $key;

    public function __construct($key) {
        $this->key = hash('sha256', $key, true);
    }

    public function encrypt($value) {
        $encryption_key = base64_decode($this->key);
        $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
        $encrypted = openssl_encrypt($value, 'aes-256-cbc', $encryption_key, 0, $iv);
        return base64_encode($encrypted . '::' . $iv);
    }

    public function decrypt($value) {
        $encryption_key = base64_decode($this->key);
        $result = base64_decode($value);
        $resultValue = substr($result, 0, strlen($result) - openssl_cipher_iv_length('aes-256-cbc') - 2);
        $resultIV = substr($result, -openssl_cipher_iv_length('aes-256-cbc'));
        return openssl_decrypt($resultValue, 'aes-256-cbc', $encryption_key, 0, $resultIV);
    }
}