我正在尝试使用 php 中的函数加密一些文本

Im trying encrypt some text using a fucntion in php

我在 php 中找到了一个关于如何加密字符串的在线教程,但是当我调用该函数并尝试回显处理后的数据时,我遇到了 500 内部错误。下面是我的代码。

 <?php



    $iv_to_pass_to_decryption = 'mysecretpass';
    function encrypt($text, $key)
    {
        $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC), MCRYPT_RAND); 
        $iv_to_pass_to_decryption = base64_encode($iv);
        return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $iv); 
    }




    function decrypt($text, $key, $iv)
    { 
        $text = base64_decode($text);
        $iv = base64_decode($iv);
        return mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $iv);
    }


    $txt = "hello";
    $mykey = "mysecretkey";
    $somedata = encrypt($txt, $mykey);

    echo $somedata;




    ?>

第一个问题是,你在第 8 行漏掉了一个 )

第二个问题是mcrypt_decrypt()函数已弃用。

第三个问题是mcrypt_encrypt():本算法不支持大小为11的密钥。仅支持大小为 16、24 或 32 的键。 'mysecretkey'键错了。

我可以推荐使用 crypt() 函数:http://php.net/manual/en/function.crypt.php

When validating passwords, a string comparison function that isn't vulnerable to timing attacks should be used to compare the output of crypt() to the previously known hash. PHP 5.6 onwards provides hash_equals() for this purpose.

使用下面的代码希望对你有帮助

    $iv_to_pass_to_decryption = 'mysecretpass';
    function encrypt($text, $key)
    {
        $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC), MCRYPT_RAND); 
        $iv_to_pass_to_decryption = base64_encode($iv);
        return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $iv));
    }




    function decrypt($text, $key, $iv)
    { 
        $text = base64_decode($text);
        $iv = base64_decode($iv);
        return mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $iv);
    }


    $txt = "hello";
    $mykey = "mysecretkey12345";
    $somedata = encrypt($txt, $mykey);

    echo $somedata;