<?php 

namespace App\Bundle\Crypt;

class AES
{
    private static $cipher = 'aes-128-cbc';
    private static $cryptKey = 'Yahve89';

    public static function encrypt($plaintext)
    {
        $ivlen = openssl_cipher_iv_length(self::$cipher);
        $iv = openssl_random_pseudo_bytes($ivlen);
        $ciphertext_raw = openssl_encrypt(
            $plaintext, self::$cipher, self::$cryptKey, $options = OPENSSL_RAW_DATA, $iv);
        $hmac = hash_hmac('sha256', $ciphertext_raw, self::$cryptKey, $as_binary = true);
        $ciphertext = base64_encode( $iv.$hmac.$ciphertext_raw );

        return $ciphertext;
    }

    public static function decrypt($ciphertext)
    {
        $c = base64_decode($ciphertext);
        $ivlen = openssl_cipher_iv_length(self::$cipher);
        $iv = substr($c, 0, $ivlen);
        $hmac = substr($c, $ivlen, $sha2len=32);
        $ciphertext_raw = substr($c, $ivlen+$sha2len);
        $plainText = openssl_decrypt(
            $ciphertext_raw, self::$cipher, self::$cryptKey, $options = OPENSSL_RAW_DATA, $iv);
        $calcmac = hash_hmac('sha256', $ciphertext_raw, self::$cryptKey, $as_binary = true);
        
        if (hash_equals($hmac, $calcmac))
            return $plainText;

        return NULL;
    }
}