Advertisement
miguelcl

OPENSSL ENCRYPT DECRYPT

Oct 2nd, 2018
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.36 KB | None | 0 0
  1. <?php
  2. /**
  3.  * simple method to encrypt or decrypt a plain text string
  4.  * initialization vector(IV) has to be the same when encrypting and decrypting
  5.  *
  6.  * @param string $action: can be 'encrypt' or 'decrypt'
  7.  * @param string $string: string to encrypt or decrypt
  8.  *
  9.  * @return string
  10.  */
  11. function encrypt_decrypt($action, $string) {
  12.     $output = false;
  13.     $encrypt_method = "AES-256-CBC";
  14.     $secret_key = 'This is my secret key';
  15.     $secret_iv = 'This is my secret iv';
  16.     // hash
  17.     $key = hash('sha256', $secret_key);
  18.    
  19.     // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
  20.     $iv = substr(hash('sha256', $secret_iv), 0, 16);
  21.     if ( $action == 'encrypt' ) {
  22.         $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
  23.         $output = base64_encode($output);
  24.     } else if( $action == 'decrypt' ) {
  25.         $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
  26.     }
  27.     return $output;
  28. }
  29. $plain_txt = "This is my plain text";
  30. echo "Plain Text =" .$plain_txt. "\n";
  31. $encrypted_txt = encrypt_decrypt('encrypt', $plain_txt);
  32. echo "Encrypted Text = " .$encrypted_txt. "\n";
  33. $decrypted_txt = encrypt_decrypt('decrypt', $encrypted_txt);
  34. echo "Decrypted Text =" .$decrypted_txt. "\n";
  35. if ( $plain_txt === $decrypted_txt ) echo "SUCCESS";
  36. else echo "FAILED";
  37. echo "\n";
  38. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement