PHP:在一个页面中加密字符串,在另一个页面使用POST解密


PHP: encrypt string in one page and decrypt it in another using POST?

我正在尝试加密一个php页面中的字符串,并使用$_POST[]将其传递到另一个页面,然后再次解密。

加密效果很好,但当我将其发布到另一个页面进行解密时,它根本不会被解密,我又得到了另一个加密字符串!

这是第1页上我加密的代码:

<?php
/*
 * PHP mcrypt - Basic encryption and decryption of a string
 */
$string = "somemails@yahoo.co.uk";
$secret_key = "This is my secret key";
// Create the initialization vector for added security.
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND);
// Encrypt $string
$encrypted_string = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $secret_key, $string, MCRYPT_MODE_CBC, $iv);
// Decrypt $string
$decrypted_string = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $secret_key, $encrypted_string, MCRYPT_MODE_CBC, $iv);
echo "Original string : " . $string . "<br />'n";
echo "Encrypted string : " . $encrypted_string . "<br />'n";
echo "Decrypted string : " . $decrypted_string . "<br />'n";
?>
<form action="2.php" method="post">
<input type="text" id="" name="input" value="<?php echo $encrypted_string; ?>"/>
<button type="submit" >submit</button>
</form>

这是第2页中我试图再次解密的代码:

<?php
    $input = $_POST['input'];
    $secret_key = "This is my secret key";
// Create the initialization vector for added security.
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND);
// Encrypt $string
$encrypted_string = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $secret_key, $input, MCRYPT_MODE_CBC, $iv);
// Decrypt $string
$decrypted_string = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $secret_key, $encrypted_string, MCRYPT_MODE_CBC, $iv);

echo $decrypted_string;
?>

有人能就这个问题提出建议吗?我想做的事情有可能吗?

观察以下行:

$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND);

每次你调用它时,它都会生成随机IV。所以你需要使用与加密它相同的IV。所以我建议你也发布IV值,或者使用特定的IV,例如:

$iv = "My Secret IV"; //On both pages