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
  1. July 12, 2013 at 4:34 AM


  2. C. Barre
    July 15, 2013 at 6:10 PM

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

  3. bmckalip
    August 2, 2013 at 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.)

  4. bmckalip
    August 3, 2013 at 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

    • August 5, 2013 at 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 !

      • bmckalip
        August 6, 2013 at 2:23 AM

        thanks so much! I’l bne using this now🙂

  5. Jason
    August 8, 2013 at 10:58 AM

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

    • August 8, 2013 at 7:04 PM


      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

      • March 26, 2014 at 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!

      • March 26, 2014 at 3:47 PM

        this post has the updated code with AES instead of MD5

      • March 26, 2014 at 7:09 PM

        All I can say is “Duh, I see that now!” Thanks

  6. volumes
    November 12, 2013 at 12:02 PM


    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 12, 2013 at 3:28 PM


      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 12, 2013 at 5:51 PM

        Hi Naveen,

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

        Best regards

      • November 13, 2013 at 3:50 PM


        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 13, 2013 at 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

      • November 13, 2013 at 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

      • volumes
        November 13, 2013 at 4:13 PM

        @Naveen Nayak,


        Now it works nice🙂

        Thank you very much.

        Keep up the good work.

        Best regards

  7. pascal malekela
    December 7, 2013 at 9:15 AM


  8. Peter
    December 14, 2013 at 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

    • December 14, 2013 at 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

  9. January 15, 2014 at 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;


    • January 15, 2014 at 1:30 PM


      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)

  10. January 16, 2014 at 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.

  11. January 31, 2014 at 3:37 PM


  12. Eric
    August 10, 2014 at 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.


    • August 11, 2014 at 1:40 AM

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

  13. Eric
    August 11, 2014 at 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?


  14. Theni N Lingeswaran
    September 8, 2014 at 8:28 AM

    me used md5 encrypt code in php:


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

    so,text me md5 decrypt code;;;;

  15. Manish Pant
    October 16, 2014 at 6:35 AM

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

  16. December 14, 2014 at 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.


  17. April 5, 2015 at 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.

  18. Sumit Bhaskar
    May 3, 2015 at 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?

  19. Sumit Bhaskar
    May 3, 2015 at 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…..🙂

  20. May 4, 2015 at 11:18 AM

    Thanks for quick.

  21. R R
    June 1, 2015 at 12:44 AM

    It helps a lot! Thanks Sir!

  22. GR
    September 6, 2015 at 12:41 PM

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

  23. GR
    September 12, 2015 at 2:43 PM

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

  24. Lance
    October 23, 2015 at 6:12 AM

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

  25. Rio Conales
    January 21, 2016 at 2:06 AM

    Nice code thank you…

  26. February 25, 2016 at 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

  27. February 25, 2016 at 3:51 PM

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

  28. April 5, 2016 at 4:31 PM

    nice post, it help me a lot
    Grettings from barcelona😀

  29. Jayjay
    April 6, 2016 at 3:14 AM

    worked for me. very helpful! thanks!

  30. April 19, 2016 at 11:21 AM


    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 19, 2016 at 3:40 PM


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

  31. Dharmendra Patel
    April 25, 2016 at 5:02 PM

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

  1. November 13, 2013 at 3:45 PM
  2. December 30, 2014 at 12:19 AM
  3. October 25, 2015 at 3:40 PM
  4. May 23, 2016 at 2:15 PM

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: