Web DevelopmentSimple PHP encrypt and decrypt

Simple PHP encrypt and decrypt

You need to have openssl encrypt installed and running. Check this thread if you dont have it already

 * simple method to encrypt or decrypt a plain text string
 * initialization vector(IV) has to be the same when encrypting and decrypting
 * PHP 5.4.9 ( check your PHP version for function definition changes )
 * this is a beginners template for simple encryption decryption
 * before using this in production environments, please read about encryption
 * use at your own risk
 * @param string $action: can be 'encrypt' or 'decrypt'
 * @param string $string: string to encrypt or decrypt
 * @return string
function encrypt_decrypt($action, $string) {
    $output = false;

    $encrypt_method = "AES-256-CBC";
    $secret_key = 'This is my secret key';
    $secret_iv = 'This is my secret iv';

    // hash
    $key = hash('sha256', $secret_key);
    // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
    $iv = substr(hash('sha256', $secret_iv), 0, 16);

    if( $action == 'encrypt' ) {
        $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
        $output = base64_encode($output);
    else if( $action == 'decrypt' ){
        $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);

    return $output;

$plain_txt = "This is my plain text";
echo "Plain Text = $plain_txt\n";

$encrypted_txt = encrypt_decrypt('encrypt', $plain_txt);
echo "Encrypted Text = $encrypted_txt\n";

$decrypted_txt = encrypt_decrypt('decrypt', $encrypted_txt);
echo "Decrypted Text = $decrypted_txt\n";

if( $plain_txt === $decrypted_txt ) echo "SUCCESS";
else echo "FAILED";

echo "\n";

Categories: Web Development


  1. Manuel

    October 15, 2018 10:34 pm

  2. Mike

    April 13, 2018 5:24 am

    Very good and simple article and coding about encryption and decryption with PHP. Just what I needed, thanks!
  3. ankit

    September 12, 2017 9:38 am

    i am using php 5.5.12 and i got following error openssl_decrypt(): Failed to base64 decode the input your code perfectly encrypt decrypt value in same page but not working if we decrypt value in different page. i have used your code with cookie. can you explain how to solve this error
    1. Naveen Nayak

      September 26, 2017 12:39 pm

      @ankit What do you mean by - decrypt value in a different page ? This has nothing to do with cookies or different pages. The code will work the same anywhere as long as you provide the correct secret, iv and the correct base 64 encoded string. Check what encoded string are you passing back to the function to decode If you are not able to base 64 decode, it might be that the string you are passing back is not a properly encoded string or it may be double encoded or it might have been modified If you can show me some code it would be easier
  4. Naveen Nayak

    August 14, 2017 11:30 am

    @Manoj Bharat Sagar http://search.cpan.org/~dparis/Crypt-DES-2.07/DES.pm
  5. Manoj Bharat Sagar

    June 22, 2017 7:12 am

    I am trying to follow similar concept in Perl, but the key being 64 characters (after sha256) is causing an issue, any idea how to proceed in this case
  6. Sajal Suraj

    May 11, 2017 2:54 am

    What is secret key and secret iv in this code ?
    1. May 11, 2017 8:57 am

      @Sajal - read up on Cryptography - a good starting point would be https://en.wikipedia.org/wiki/Initialization_vector
  7. Andy

    April 4, 2017 10:17 am

    Works fine!! thanks for sharing
  8. peter

    December 16, 2016 5:02 am

    Nice Script.........works great........ :)
  9. November 29, 2016 3:02 am

    echo "Org : Z4Bl5kYFQLupQ "; salt is 'z4' and how to get original string
  10. May 23, 2016 2:15 pm

    […] Fuente: https://naveensnayak.wordpress.com/2013/03/12/simple-php-encrypt-and-decrypt/ […]
  11. Dharmendra Patel

    April 25, 2016 5:02 pm

    After searching lot of links I found your solution and its working fine. thanks
  12. April 19, 2016 11:21 am

    Hi. I am triying this method but not working this line in my project: #37 $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv); The output is boolean(false) #65 $password = $decrypted_pass->encrypt_decrypt(‘decrypt’, $upass);
    1. April 19, 2016 3:40 pm

      @Raul What version of PHP are you using ? - the example uses 5.4 - have you checked the openssl function definition for your php version ?
  13. Jayjay

    April 6, 2016 3:14 am

    worked for me. very helpful! thanks!
  14. April 5, 2016 4:31 pm

    nice post, it help me a lot Thanks Grettings from barcelona :D
  15. February 25, 2016 3:51 pm

    @Lance you can also use openssl_random_pseudo_bytes( 16 ) function; the integer param determines the length of the string returned
  16. February 25, 2016 1:42 pm

    Hi Naveen, Nice post - thanks for sharing. I've read elsewhere that the same IV should never be used more than once. What are your thoughts on this? Thanks, Mike
    1. February 25, 2016 4:25 pm

      @Mike, Yes having a new IV each time definitely increases security and is also recommended. If you want to use random IV's then you can look at the answer from blaze in this stackoverflow post. Suggestion is to store the IV besides the encrypted data if you need the decrypt the data in the future http://stackoverflow.com/questions/5108607/encryption-use-of-initialization-vector-vs-key
  17. Rio Conales

    January 21, 2016 2:06 am

    Nice code thank you...
  18. October 25, 2015 3:40 pm

    […] *EDIT:  Original Code Located here.. (I modified it to accept files) http://naveensnayak.wordpress.com/2013/03/12/simple-php-encrypt-and-decrypt/ […]
  19. Lance

    October 23, 2015 6:12 am

    Does anyone know here how and where will I get the $secret_key and $secret_iv?
    1. October 23, 2015 3:55 pm

      @Lance you need to generate your own secret keys - this might help https://www.random.org/strings/
  20. GR

    September 12, 2015 2:43 pm

    You mean so it won't disrupt a query string?
  21. GR

    September 6, 2015 12:41 pm

    Thanks, this is great. One question, why do you encode it in base64 after you encrypt?
    1. September 8, 2015 4:03 pm

      @GR http://stackoverflow.com/questions/4070693/what-is-the-purpose-of-base-64-encoding-and-why-it-used-in-http-basic-authentica mainly to safely transport data for example to a web page or storing to a database
  22. R R

    June 1, 2015 12:44 am

    It helps a lot! Thanks Sir!
  23. May 4, 2015 11:18 am

    Thanks for quick.
  24. Sumit Bhaskar

    May 3, 2015 7:44 am

    ok, got it by myself. I guess, all i needed was, to ask "the right question", which i did, and got the solution..... :-) thanks in advance anyways, as your simple solution gave me the confidence to ask "simple" question and thus get the simple answer..... :)
  25. Sumit Bhaskar

    May 3, 2015 12:26 am

    This code is working on my server. However I have an unrelated problem. I just want to know the simplest way to open a text file from inside a directory. I want to structure my files, so I want to put text files in different directory, include files in different directory etc. I have been searching for a solution since two days now, mainly on google, stackoverflow and php.net, but I don't seem to get any solutions that I understand. I am very very new to PHP but because of having a programming background, I have been able to write a small web appliacation but simple problems like these have been keeping me from completing it. Can you help please......? what i am trying to do $file = fopen("/dir/file.txt", "r"); it is working fine without the /dir/ part but not with it, giving all sorts of error that i don't understand...... also can i encrypt and decrypt these text files too? Any solutions?
  26. April 5, 2015 12:04 am

    Nice work! Simple and works really well. I was pulling my hair out using the "standard" mcrypt_encrypt method which for me at least was unreliable. You code works well on windows 7, 8 mac and ubuntu so far. openssl_encrypt seems much better.
  27. December 30, 2014 12:19 am

    […] http://naveensnayak.wordpress.com/2013/03/12/simple-php-encrypt-and-decrypt/ […]
  28. December 14, 2014 4:47 pm

    Here is a good PHP library that can help you encrypt and decrypt strings with a key. It's available in Composer and super easy to use too. https://github.com/CoreProc/crypto-guard
  29. Manish Pant

    October 16, 2014 6:35 am

    On running this program i have got an error : Fatal error: Call to undefined function openssl_encrypt() in C:wampwwwPHPcrypt.php on line 16
    1. October 16, 2014 3:23 pm

      @manish - check this http://stackoverflow.com/questions/11525524/why-cant-i-use-openssl-encrypt
      1. Manish Pant

        October 16, 2014 4:37 pm

        oooo.. great thanx buddy :)
  30. Theni N Lingeswaran

    September 8, 2014 8:28 am

    me used md5 encrypt code in php: $password=md5($mypass); i got encrypted code,but "i don't know decrypt code"; so,text me md5 decrypt code;;;;
    1. September 8, 2014 4:15 pm

      MD5 is a hashing algorithm and there is no way to get the original string back unless you use a brute force attack or a dictionary. Here is a stackoverflow post http://stackoverflow.com/questions/1240852/is-it-possible-to-decrypt-md5-hashes If your password is simple enough, you can try one of these - there are many other sites like these http://www.md5online.org/
  31. Eric

    August 11, 2014 2:08 am

    Thanks for our reply, Naveen. I read about some changes in posts after the March 12, 2013 date of your original posting, but no subsequent 'Edited Date' beyond March 12, 2013 and assumed the main script did not contain any necessary revisions. But also in some research, apparently some major companies are deprecating Aes-256-CBC in favor of other options. Is there a particular alternative you might recommend now? Eric
    1. August 11, 2014 4:12 am

      I would hesitate to recommend any algorithm as it relates to security - there are some threads here http://security.stackexchange.com/questions/26289/strongest-cryptographic-algorithm-available-in-php-5-3 I would also recommend asking a question in that forum as i am pretty sure you will get a much better answer than mine :)
  32. Eric

    August 10, 2014 1:05 pm

    Hi, Naveen: Is there a fully corrected edition of your very useful encrypt/decrypt script available, and if so where ? Thanks very much. Eric
    1. August 11, 2014 1:40 am

      Eric - this is the most updated version - are you facing problems with it ?
  33. January 31, 2014 3:37 pm

  34. January 16, 2014 3:55 am

    Dear Naveen Thanks for your quick response. However, the above code was found in our function file. We do not have decrypt text or key and we do not know how to decrypt it. Please help on this.
  35. January 15, 2014 1:01 pm

    Hello Naveen, We have the below code in our function file, how to decrypt it so that all files which are encrypted can open. function encrypt_decrypt($action, $string, $key) { $output = false; $iv = md5(md5($key)); if ($action == 'encrypt') { $output = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, $iv); $output = base64_encode($output); } else if ($action == 'decrypt') { $output = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, $iv); $output = rtrim($output, ""); } return $output; } Thanks
    1. January 15, 2014 1:30 pm

      @luvvips This is an older version of the function - you should update your code and avoid using MD5 you should be able to decrypt the code using something like $decrypted_string = encrypt_decrypt('decrypt', $encrypted_string, $secret_key_used_to_encrypt)
  36. Peter

    December 14, 2013 2:07 pm

    Dont works ! Warning: openssl_encrypt() expects at most 4 parameters, 5 given Warning: openssl_decrypt() expects at most 4 parameters, 5 given
    1. December 14, 2013 6:10 pm

      check your php version - openssl function params are different - i have mentioned in the comments that i am on php 5.4
  37. pascal malekela

    December 7, 2013 9:15 am

  38. November 13, 2013 3:45 pm

    […] See http://naveensnayak.wordpress.com/2013/03/12/simple-php-encrypt-and-decrypt/ […]
  39. volumes

    November 12, 2013 12:02 pm

    Hi, Im getting this error twice: Notice: A non well formed numeric value encountered in (...) first error: $output = openssl_encrypt($string, $encrypt_method, $key, $iv); second error: $output = $decryptedMessage = openssl_decrypt(base64_decode($string), $encrypt_method, $key, $iv); Can you help me please ? Best regards
    1. November 12, 2013 3:28 pm

      @ruimiguelsilva@gmail.com, without knowing what exactly you are trying to pass to the function, it is difficult to tell. Have you tried with simple strings first ?
      1. volumes

        November 12, 2013 5:51 pm

        Hi Naveen, Actually, i didnt changed a thing, just copy paste your code : Best regards
      2. November 13, 2013 3:50 pm

        @volumes, what OS and what php version are you using this on ? I just tried it on Ubuntu 12.04 , PHP Version => 5.4.9-4ubuntu2.3 and it is working fine
        1. volumes

          November 13, 2013 3:54 pm

          @Naveen Nayak, PHP Version 5.4.16 System Windows 7 Ultimate Edition Service Pack 1 Apache Version Apache/2.4.4 (Win32) OpenSSL/0.9.8y PHP/5.4.16
      3. November 13, 2013 4:07 pm

        Yes i see the warnings - i have updated the post - it should work now - 2 changes 1. openssl_encrypt and decrypt have an additional parameter $options 2. AES-256-CBC expects exactly 16 bytes of iv Thanks for bringing it to my notice
        1. volumes

          November 13, 2013 4:13 pm

          @Naveen Nayak, hehe. Now it works nice :) Thank you very much. Keep up the good work. Best regards
      4. JAY

        May 10, 2017 6:20 am

        Can you give a php code which executes a encryption and decryption? Because I’m having a problem with it .. I mean the full code please .. ?
        1. May 10, 2017 11:36 am

          @JAY I don't understand what you mean by full code - this is a full example and you can modify as you like. What problem are you having ?
  40. Jason

    August 8, 2013 10:58 am

    this doesnt work if the string has really strong characters like #+.. is there a work around from here?
    1. August 8, 2013 7:04 pm

      Jason, Check this http://pastebin.com/2mv4W5jA - the plain text i used has a lot of special characters and it works well Without knowing what string you are referring to, its difficult to say why it is not working
      1. March 26, 2014 3:41 pm

        Hi Naveen, Your paste at http://pastebin.com/2mv4W5jA has been deleted. Can you update this post instead? Or is it updated? Thanks, exactly what I was looking for!
        1. March 26, 2014 3:47 pm

          this post has the updated code with AES instead of MD5
      2. March 26, 2014 7:09 pm

        All I can say is "Duh, I see that now!" Thanks
  41. bmckalip

    August 3, 2013 9:37 pm

    I brought this up on another forum, heres the link. it has examples tek syndicate dot com /forum/code/well-has-officially-stumped-me/148387
    1. August 5, 2013 7:57 pm

      the problem was with the rtrim() function. I had typed in an empty string as a second argument. So it was not stripping out the padded '' mistyped code => $output = rtrim($output, ""); correct code => $output = rtrim($output); If the size of the data that will be decrypted with the given cipher and mode is not n * blocksize, the data will be padded with ''. it has been corrected now and i have tried out this example - http://pastebin.com/Z2daVm2j thank you for notifying me !
      1. bmckalip

        August 6, 2013 2:23 am

        thanks so much! I'l bne using this now :)
  42. bmckalip

    August 2, 2013 6:55 pm

    It seems that even though the value this retuns IS on face value a string, i can't compare it with an if statement for instance to something with the same "value" anyone else have this issue? (decrpted string doesnt equal what it should.)
    1. August 2, 2013 8:01 pm

      can you provide an example ?
  43. C. Barre

    July 15, 2013 6:10 pm

    Nice! I used Decrypt for my php decoding for big files (mainly Ioncube).
  44. July 12, 2013 4:34 am


Post a comment

Your email address will not be published. Required fields are marked *