简体   繁体   中英

Encrypt & Decrypt String - PHP

I have file1.php & file2.php , in file1.php have some links, example :

<a href="http://google.com/">Open google site</a>
<a href="http://facebook.com/">Open facebook site</a>

I try to make safelink on file1.php , I'm use this function to encrypt

function enc_safelink($url_target){
    $key = '1q2w3e4r5t'; 
    $iv = mcrypt_create_iv(
    mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC),
    MCRYPT_DEV_URANDOM
    );

    $encrypted = base64_encode(
        $iv .
        mcrypt_encrypt(
            MCRYPT_RIJNDAEL_128,
            hash('sha256', $key, true),
            $url_target,
            MCRYPT_MODE_CBC,
            $iv
        )
    );
    return $encrypted;
}

So all link on file1.php will be like this :

<a href="file2.php?link=D6/thGZQ3MpUf6ePqqDBrXdQC3rAVQHMHGm9KOn6GVjB3CNyDqljwt7DIwkWU6HV">Open google site</a>
<a href="file2.php?link=HYOyBzxnpd1MrzN4YMF1qpWSg4KMlE1mz2HTxOl+ZGdS3zUSQymoMIPoBMVu3Mpm">Open facebook site</a>

In file2.php I want to show a link and get permalink from parameter

 <?php
  function dnc_safelink($params_code){
    $key = '1q2w3e4r5t';
    $data = base64_decode($params_code);
    $iv = substr($data, 0, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));

    $decrypted = rtrim(
       mcrypt_decrypt(
       MCRYPT_RIJNDAEL_128,
       hash('sha256', $key, true),
       substr($data, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC)),
       MCRYPT_MODE_CBC,
       $iv
    ),
    "\0"
    );
    return $decrypted;
  }
  if ( isset($_GET["link"]) ) :
    $dnc_url = dnc_safelink($_GET['link']);
    echo '<div style="text-align:center" id="aDivSafeLink"><a href="'.$dnc_url.'">Download Here</a></div>';
  endif;
 ?>

But the output like this :

<a href="�uJ�`*���_����gyܥ�w�W�X�#">Download Here</a>

I'm sure, I have tested on the same page the encrypt & decrypt function works perfectly. How can I use encryption & decryption a string with different page or different site?

Source of function : https://stackoverflow.com/a/1289114

How can I use encryption & decryption a string with different page or different site?

If you find yourself encrypting URL parameters, you've made a mistake.

What People Want To Do Here

某些加密函数用于确定性地检索ID

What People Should Do Instead

使用单独的列


Instead of encryption, use random_bytes() in conjunction with either bin2hex() or base64_encode() . If you use Base64, make the number of bytes you generate an even multiple of 3 (eg random_bytes(24) for a 32-character string).

You can also use URL-safe base64 like so:

<?php
use ParagonIE\ConstantTime\Base64UrlSafe;

$token = Base64UrlSafe::encode(random_bytes(24));

But encryption is simply the wrong tool for the job .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM