3v4l.org

run code in 300+ PHP versions simultaneously
<?php error_reporting(1); ini_set('display_errors', 1); class Encryption { private $key; protected $iv_size; protected $iv; public function __construct() { # --- ENCRYPTION --- # the key should be random binary, use scrypt, bcrypt or PBKDF2 to # convert a string into a key # key is specified using hexadecimal $this->key = pack("H*", "myKeyIsGreaterth2nanndbestofall04nkdsdffsd546754sdfvsdg6efflsdfs"); # create a random IV to use with CBC encoding $this->iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC); $this->iv = mcrypt_create_iv($this->iv_size, MCRYPT_RAND); } public function encryptData($input) { $output = $this->encrypt($input); return $output; } public function decryptData($input) { $input = base64_decode($input); $output = $this->decrypt($input); return $output; } protected function decrypt($string) { # retrieves the IV, iv_size should be created using mcrypt_get_iv_size() $iv_dec = substr($string, 0, $this->iv_size); # retrieves the cipher text (everything except the $iv_size in the front) $string = substr($string, $this->iv_size); # may remove 00h valued characters from end of plain text $output = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->key, $string, MCRYPT_MODE_CBC, $iv_dec); return $output; } protected function encrypt($string) { # creates a cipher text compatible with AES (Rijndael block size = 128) # to keep the text confidential # only suitable for encoded input that never ends with value 00h # (because of default zero padding) $output = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->key, $string, MCRYPT_MODE_CBC, $this->iv); # prepend the IV for it to be available for decryption $output = $this->iv . $output; # encode the resulting cipher text so it can be represented by a string $output = base64_encode($output); # === WARNING === # Resulting cipher text has no integrity or authenticity added # and is not protected against padding oracle attacks. return $output; } } $test = new Encryption(); $encrypted = $test->encryptData("Narendra"); echo "This is encrypted text of a string Narendra $encrypted \n"; echo "This is decrypted text ".$test->decryptData($encrypted);

preferences:
40.79 ms | 402 KiB | 5 Q