Encryption example in PHP

<?php
    
    public function encrypt($text, $key) {
        if (strlen($key) !== 32) {
            throw new Exception("Key must be 32 bytes long.");
        }
    
        $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
        $encrypted = openssl_encrypt($text, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
    
        if ($encrypted === false) {
            throw new Exception("Encryption failed.");
        }
    
        $data = $iv . $encrypted;
        return base64_encode($data);
    }
    
    public function decrypt($data, $key) {
        if (strlen($key) !== 32) {
            throw new Exception("Key must be 32 bytes long.");
        }
    
        $data = base64_decode($data);
        $iv = substr($data, 0, openssl_cipher_iv_length('aes-256-cbc'));
        $encrypted = substr($data, openssl_cipher_iv_length('aes-256-cbc'));
    
        $decrypted = openssl_decrypt($encrypted, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
    
        if ($decrypted === false) {
            throw new Exception("Decryption failed.");
        }
    
        return $decrypted;
    }