Hi! Could we please enable some services and cookies to improve your experience and our website?

PHPize Online / SQLize Online  /  SQLtest Online

A A A
Login    Share code      Blog   FAQ

Online Sandbox for SQL and PHP: Write, Run, Test, and Share SQL Queries and PHP Code

Copy Format Clear

Stuck with a problem? Got Error? Ask AI support!

Copy Clear
Copy Format Clear
<?php class Foo { const CIPHER = 'AES-256-CBC'; const SEPARATOR = '::'; public static function encrypt(string $data, string $key): string { // Remove the base64 encoding from the key. $encryptionKey = base64_decode($key); // Generate an initialization vector. $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length(self::CIPHER)); // Encrypt the data using our encryption key and initialization vector. $encrypted = openssl_encrypt($data, self::CIPHER, $encryptionKey, 0, $iv); // The $iv is appended to our encrypted data using a unique separator (::) so we can later retrieve it when decrypting. return base64_encode($encrypted . self::SEPARATOR . $iv); } public static function decrypt(string $data, string $key) { // Remove the base64 encoding from the key and password. $encryptionKey = base64_decode($key); $passwordData = base64_decode($data); // To decrypt, split encrypted data from the IV using the unique separator. [$encryptedData, $iv] = explode(self::SEPARATOR, $passwordData, 2); return openssl_decrypt($encryptedData, self::CIPHER, $encryptionKey, 0, $iv); } } $key = base64_encode('Ly9mUm15cWdpZkxZTFR0SFZiQVJaUT09Ojofx2tzUsctyLy0ti28SDBA'); var_dump( $enc = Foo::encrypt('hello', "world"), Foo::decrypt($enc, 'world') );
Copy Clear