PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
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('foobar'); var_dump( $enc = Foo::encrypt('hello', "world"), Foo::decrypt($enc, 'world') );
Show:  
Copy Clear