【发布时间】:2016-02-03 21:18:21
【问题描述】:
我正在尝试使用 mcrypt 加密一个 PHP 站点上的值并在另一个站点上解密它。有时它有效(比如 80% 的时间),有时它不起作用。 现在我发现用相同的密钥加密相同的值时,加密的文本是不同的。这怎么可能? 我错过了什么?
这是加密的代码:
# key is always the same
$key = "mysimplekey";
# text is always the same
$plaintext = "text_to_encrypt";
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plaintext, MCRYPT_MODE_CBC, $iv);
$ciphertext = $iv . $ciphertext;
$ciphertext_base64 = base64_encode($ciphertext);
$ciphertext_url = rawurlencode($ciphertext_base64);
# gives different values for the same key & encryption text:
echo $ciphertext_url;
解密代码:
$key = 'mysimplekey';
$ciphertext_dec = base64_decode($_REQUEST['u']);
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
# retrieves the IV, iv_size should be created using mcrypt_get_iv_size()
$iv_dec = substr($ciphertext_dec, 0, $iv_size);
# retrieves the cipher text (everything except the $iv_size in the front)
$ciphertext_dec = substr($ciphertext_dec, $iv_size);
# may remove 00h valued characters from end of plain text
$ciphertext_dec = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec));
【问题讨论】:
-
URL 有一个最大输入(我相信是 2048),这可能是原因吗?
-
$iv- 你每次都在生成新的初始化向量 -
是的,但是向量被附加到字符串中,这不应该是解密的问题吗?但是,从技术上讲,你是对的,我的问题是以错误的方式提出的。
-
解密器如何知道最终 url 的哪一部分是 iv 以及什么是文本?
-
你是如何构造 URL 以发送到解密脚本的?如果您是在 javascript 中执行此操作,则可能会添加额外的编码层。
标签: php encryption base64 urlencode