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
http://stackoverflow.com/questions/11525524/why-cant-i-use-openssl-encrypt

/**
 * 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. Naveen Nayak
  2. Manoj Bharat Sagar
    June 22nd, 2017 at 07:12 | #2

    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

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

    What is secret key and secret iv in this code ?

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

    Works fine!!

    thanks for sharing

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

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

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

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

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

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

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

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

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

      @Raul

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

  9. Jayjay
    April 6th, 2016 at 03:14 | #11

    worked for me. very helpful! thanks!

  10. April 5th, 2016 at 16:31 | #12

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

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

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

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

    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

  13. Rio Conales
    January 21st, 2016 at 02:06 | #16

    Nice code thank you…

  14. Lance
    October 23rd, 2015 at 06:12 | #17

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

  15. GR
    September 12th, 2015 at 14:43 | #19

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

  16. GR
    September 6th, 2015 at 12:41 | #20

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

  17. R R
    June 1st, 2015 at 00:44 | #22

    It helps a lot! Thanks Sir!

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

    Thanks for quick.

  19. Sumit Bhaskar
    May 3rd, 2015 at 07:44 | #24

    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. Sumit Bhaskar
    May 3rd, 2015 at 00:26 | #25

    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?

  21. April 5th, 2015 at 00:04 | #26

    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.

  22. December 14th, 2014 at 16:47 | #27

    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

  23. Manish Pant
    October 16th, 2014 at 06:35 | #28

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

  24. Theni N Lingeswaran
    September 8th, 2014 at 08:28 | #31

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

  25. Eric
    August 11th, 2014 at 02:08 | #33

    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

  26. Eric
    August 10th, 2014 at 13:05 | #35

    Hi, Naveen:

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

    Thanks very much.

    Eric

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

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

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

    Thanks!

  28. January 16th, 2014 at 03:55 | #38

    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.

  29. January 15th, 2014 at 13:01 | #39

    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

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

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

  30. Peter
    December 14th, 2013 at 14:07 | #41

    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 | #42

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

  31. pascal malekela
    December 7th, 2013 at 09:15 | #43

    thanks.

  32. volumes
    November 12th, 2013 at 12:02 | #44

    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

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

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

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

        Hi Naveen,

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

        Best regards

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

        @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

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

          @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 | #49

        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 | #50

          @Naveen Nayak,

          hehe.

          Now it works nice πŸ™‚

          Thank you very much.

          Keep up the good work.

          Best regards

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

        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 | #52

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

  33. Jason
    August 8th, 2013 at 10:58 | #53

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

  34. bmckalip
    August 3rd, 2013 at 21:37 | #58

    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 | #59

      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 | #60

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

  35. bmckalip
    August 2nd, 2013 at 18:55 | #61

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

  36. C. Barre
    July 15th, 2013 at 18:10 | #63

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

  37. July 12th, 2013 at 04:34 | #64

    Good!

  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