<?php

namespace App\Helpers;

class AesHelper
{
    public static function encrypt($plaintext): string
    {
        $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
        return base64_encode($iv . openssl_encrypt($plaintext, 'aes-256-cbc', config('app.key'), OPENSSL_RAW_DATA, $iv));
    }

    public static function decrypt($encryptedData): false|string
    {
        $encryptedData = base64_decode($encryptedData);
        $ivLength = openssl_cipher_iv_length('aes-256-cbc');
        $iv = substr($encryptedData, 0, $ivLength);
        return openssl_decrypt(substr($encryptedData, $ivLength), 'aes-256-cbc', config('app.key'), OPENSSL_RAW_DATA, $iv);
    }
}
