Home » Programming » PHP » Easy-to-use and strong Encrypt/Decrypt PHP functions

Easy-to-use and strong Encrypt/Decrypt PHP functions

posted in: Cryptography, PHP, Programming 1

I wrote those two following PHP functions to encrypt and decrypt strings easly and with a stronger encryption module than the other examples on the net (please, note that “strong” does not equals “secure”!);

Happy encryption/decryption! 🙂

Max

[sourcecode language=”php”] function encrypt($input_string, $key){
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$h_key = hash(‘sha256’, $key, TRUE);
return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $h_key, $input_string, MCRYPT_MODE_ECB, $iv));
}


function decrypt($encrypted_input_string, $key){
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$h_key = hash(‘sha256’, $key, TRUE);
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $h_key, base64_decode($encrypted_input_string), MCRYPT_MODE_ECB, $iv));
}
[/sourcecode]


  1. Dimitri
    | Reply

    Hi,
    Thank you for this example code.

    Unfortunately, it seems that some php functions that you use in your example will be removed from PHP 7.2.
    http://php.net/manual/en/function.mcrypt-get-iv-size.php

    Do you have an alternative solution?

    Regards

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.