Home > Web Development > Simple 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 Tags:
  1. ankit
    September 12th, 2017 at 09:38 | #1

    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

    • Naveen Nayak
      September 26th, 2017 at 12:39 | #2


      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

  2. Naveen Nayak
  3. Manoj Bharat Sagar
    June 22nd, 2017 at 07:12 | #4

    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

  4. Sajal Suraj
    May 11th, 2017 at 02:54 | #5

    What is secret key and secret iv in this code ?

  5. Andy
    April 4th, 2017 at 10:17 | #7

    Works fine!!

    thanks for sharing

  6. peter
    December 16th, 2016 at 05:02 | #8

    Nice Script………works great…….. πŸ™‚

  7. November 29th, 2016 at 03:02 | #9

    echo “Org : Z4Bl5kYFQLupQ “; salt is ‘z4’ and how to get original string

  8. Dharmendra Patel
    April 25th, 2016 at 17:02 | #10

    After searching lot of links I found your solution and its working fine. thanks

  9. April 19th, 2016 at 11:21 | #11


    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);

    • April 19th, 2016 at 15:40 | #12


      What version of PHP are you using ? – the example uses 5.4 – have you checked the openssl function definition for your php version ?

  10. Jayjay
    April 6th, 2016 at 03:14 | #13

    worked for me. very helpful! thanks!

  11. April 5th, 2016 at 16:31 | #14

    nice post, it help me a lot
    Grettings from barcelona πŸ˜€

  12. February 25th, 2016 at 15:51 | #15

    @Lance you can also use openssl_random_pseudo_bytes( 16 ) function; the integer param determines the length of the string returned

  13. February 25th, 2016 at 13:42 | #16

    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

  14. Rio Conales
    January 21st, 2016 at 02:06 | #18

    Nice code thank you…

  15. Lance
    October 23rd, 2015 at 06:12 | #19

    Does anyone know here how and where will I get the $secret_key and $secret_iv?

  16. GR
    September 12th, 2015 at 14:43 | #21

    You mean so it won’t disrupt a query string?

  17. GR
    September 6th, 2015 at 12:41 | #22

    Thanks, this is great. One question, why do you encode it in base64 after you encrypt?

  18. R R
    June 1st, 2015 at 00:44 | #24

    It helps a lot! Thanks Sir!

  19. May 4th, 2015 at 11:18 | #25

    Thanks for quick.

  20. Sumit Bhaskar
    May 3rd, 2015 at 07:44 | #26

    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….. πŸ™‚

  21. Sumit Bhaskar
    May 3rd, 2015 at 00:26 | #27

    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?

  22. April 5th, 2015 at 00:04 | #28

    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.

  23. December 14th, 2014 at 16:47 | #29

    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.


  24. Manish Pant
    October 16th, 2014 at 06:35 | #30

    On running this program i have got an error :
    Fatal error: Call to undefined function openssl_encrypt() in C:wampwwwPHPcrypt.php on line 16

  25. Theni N Lingeswaran
    September 8th, 2014 at 08:28 | #33

    me used md5 encrypt code in php:


    i got encrypted code,but “i don’t know decrypt code”;

    so,text me md5 decrypt code;;;;

  26. Eric
    August 11th, 2014 at 02:08 | #35

    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?


  27. Eric
    August 10th, 2014 at 13:05 | #37

    Hi, Naveen:

    Is there a fully corrected edition of your very useful encrypt/decrypt script available, and if so where ?

    Thanks very much.


    • August 11th, 2014 at 01:40 | #38

      Eric – this is the most updated version – are you facing problems with it ?

  28. January 31st, 2014 at 15:37 | #39


  29. January 16th, 2014 at 03:55 | #40

    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.

  30. January 15th, 2014 at 13:01 | #41

    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;


    • January 15th, 2014 at 13:30 | #42


      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)

  31. Peter
    December 14th, 2013 at 14:07 | #43

    Dont works !
    Warning: openssl_encrypt() expects at most 4 parameters, 5 given
    Warning: openssl_decrypt() expects at most 4 parameters, 5 given

    • December 14th, 2013 at 18:10 | #44

      check your php version – openssl function params are different – i have mentioned in the comments that i am on php 5.4

  32. pascal malekela
    December 7th, 2013 at 09:15 | #45


  33. volumes
    November 12th, 2013 at 12:02 | #46


    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

    • November 12th, 2013 at 15:28 | #47


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

      • volumes
        November 12th, 2013 at 17:51 | #48

        Hi Naveen,

        Actually, i didnt changed a thing, just copy paste your code :

        Best regards

      • November 13th, 2013 at 15:50 | #49


        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

        • volumes
          November 13th, 2013 at 15:54 | #50

          @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

      • November 13th, 2013 at 16:07 | #51

        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

        • volumes
          November 13th, 2013 at 16:13 | #52

          @Naveen Nayak,


          Now it works nice πŸ™‚

          Thank you very much.

          Keep up the good work.

          Best regards

      • JAY
        May 10th, 2017 at 06:20 | #53

        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 .. ?

        • May 10th, 2017 at 11:36 | #54


          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 ?

  34. Jason
    August 8th, 2013 at 10:58 | #55

    this doesnt work if the string has really strong characters like #+.. is there a work around from here?

  35. bmckalip
    August 3rd, 2013 at 21:37 | #60

    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

    • August 5th, 2013 at 19:57 | #61

      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 !

      • bmckalip
        August 6th, 2013 at 02:23 | #62

        thanks so much! I’l bne using this now πŸ™‚

  36. bmckalip
    August 2nd, 2013 at 18:55 | #63

    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.)

  37. C. Barre
    July 15th, 2013 at 18:10 | #65

    Nice! I used Decrypt for my php decoding for big files (mainly Ioncube).

  38. July 12th, 2013 at 04:34 | #66


  1. November 13th, 2013 at 15:45 | #1
  2. December 30th, 2014 at 00:19 | #2
  3. October 25th, 2015 at 15:40 | #3
  4. May 23rd, 2016 at 14:15 | #4