Encrypt and decrypt text strings with PHP

May 18, 2020 • edited May 19, 2020

PHP is one of the most popular programming languages ​​thanks to Facebook and Wordpress, but popularity does not indicate that it is the best or the safest to program. However, many low-cost projects are developed in this language.

I leave you an alternative to encrypt text strings. For this occasion we will use OpenSSL .

function openCypher ($action='encrypt',$string=false)
{
    $action = trim($action);
    $output = false;

    $myKey = 'oW%c76+jb2';
    $myIV = 'A)2!u467a^';
    $encrypt_method = 'AES-256-CBC';

    $secret_key = hash('sha256',$myKey);
    $secret_iv = substr(hash('sha256',$myIV),0,16);

    if ( $action && ($action == 'encrypt' || $action == 'decrypt') && $string )
    {
        $string = trim(strval($string));

        if ( $action == 'encrypt' )
        {
            $output = openssl_encrypt($string, $encrypt_method, $secret_key, 0, $secret_iv);
        };

        if ( $action == 'decrypt' )
        {
            $output = openssl_decrypt($string, $encrypt_method, $secret_key, 0, $secret_iv);
        };
    };

    return $output;
};

The first thing we must do is change $myKeyand $myIVby complex text strings to ensure encrypted responses as secure as possible. They can also change the encryption method for $encrypt_methodalthough personally I prefer AES-256-CBC to be one of the safest response and short chains.

$myText = 'This is my secure text';

Let’s see how to encrypt:

$myText_encrypted = openCypher('encrypt',$myText);
echo $myText_encrypted;
// RESPUESTA: xrgFsPYDTxCBQbxbIteSmSJLaHlaGVmlV5oNIqvW9Sk=

Now let’s decrypt the previous answer:

$myText_decrypted = openCypher('decrypt',$myText_encrypted);
echo $myText_decrypted;
// RESPUESTA: This is my secure text

The function converts to SHA256 $myKey and $myIVto triple the security level but it is important to note that nothing guarantees that someone can appear who manages to break our code. The most important thing here is to avoid by all means letting $myKeyy go public $myIV.

PHP

Junihh

Junihh is talk about web-dev and opinion.

Capture parameters passed by url with javascript

Facebook makes me lose money