0

我从 Internet 获得了一段代码来使用 TripleDES 加密我的数据。

$key = "ThisIsTheKey"; // 24 bit Key
$iv = "fYfhHeDm"; // 8 bit IV
$bit_check = 8; // bit amount for diff algor.


//function to encrypt
function encrypt($text) {
    global $key,$iv,$bit_check;
    $text_num = str_split($text, $bit_check);
    $text_num = $bit_check - strlen($text_num[count($text_num) - 1]);
    for ($i = 0; $i < $text_num; $i++) {
        $text = $text . chr($text_num);
    }
    $cipher = mcrypt_module_open(MCRYPT_TRIPLEDES, '', 'cbc', '');
    mcrypt_generic_init($cipher, $key, $iv);
    $decrypted = mcrypt_generic($cipher, $text);
    mcrypt_generic_deinit($cipher);
    return base64_encode($decrypted);
}

问题是即使我将变量称为全局变量,在顶部(我声明变量的地方)显示变量未使用。以及当我尝试运行它时,它给出了一个错误。但是,当我在函数内部声明相同的变量集时,它会起作用。

4

1 回答 1

11

作为一般说明,强烈不建议使用全局变量。当我查看您的函数时,我发现它只需要$text,但是,它实际上需要$text$key$iv$bit_check

让我们尝试不使用全局变量:

$key = "ThisIsTheKey"; // 24 bit Key
$iv = "fYfhHeDm"; // 8 bit IV
$bit_check = 8; // bit amount for diff algor.


//function to encrypt
function encrypt($text, $key, $iv, $bit_check) {
    $text_num = str_split($text, $bit_check);
    $text_num = $bit_check - strlen($text_num[count($text_num) - 1]);
    for ($i = 0; $i < $text_num; $i++) {
        $text = $text . chr($text_num);
    }
    $cipher = mcrypt_module_open(MCRYPT_TRIPLEDES, '', 'cbc', '');
    mcrypt_generic_init($cipher, $key, $iv);
    $decrypted = mcrypt_generic($cipher, $text);
    mcrypt_generic_deinit($cipher);
    return base64_encode($decrypted);
}

并使用它调用它

encrypt("Hello World!", $key, $iv, $bit_check);

另一种解决方案涉及使用 CONSTANTS,假设 key、iv 和 bit_check在整个执行时间内永远不会改变,您可以将它们定义为常量,并且它们将在整个应用程序中全局可用,并且无法更改

像这样:

const KEY = "ThisIsTheKey"; // 24 bit Key
const IV = "fYfhHeDm"; // 8 bit IV
const BIT_CHECK = 8; // bit amount for diff algor.


//function to encrypt
function encrypt($text) {
    $text_num = str_split($text, BIT_CHECK);
    $text_num = BIT_CHECK - strlen($text_num[count($text_num) - 1]);
    for ($i = 0; $i < $text_num; $i++) {
        $text = $text . chr($text_num);
    }
    $cipher = mcrypt_module_open(MCRYPT_TRIPLEDES, '', 'cbc', '');
    mcrypt_generic_init($cipher, KEY, IV);
    $decrypted = mcrypt_generic($cipher, $text);
    mcrypt_generic_deinit($cipher);
    return base64_encode($decrypted);
}
于 2012-09-25T12:47:27.467 回答