【发布时间】:2009-10-27 02:36:45
【问题描述】:
我在 Ruby 中有以下函数可以解密一些数据:
def decrypt(key, iv, cipher_hex)
cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
cipher.decrypt
cipher.key = key.gsub(/(..)/){|h| h.hex.chr}
cipher.iv = iv.gsub(/(..)/){|h| h.hex.chr}
decrypted_data = cipher.update(cipher_hex.gsub(/(..)/){|h| h.hex.chr})
decrypted_data << cipher.final
return decrypted_data
end
我正在尝试在 PHP 中做同样的事情,但我不确定我做错了什么。这是我得到的:
function decrypt_data($key, $iv, $cipher_hex) {
return mcrypt_decrypt(
MCRYPT_RIJNDAEL_128,
hex_to_str($key),
hex_to_str($cipher_hex),
MCRYPT_MODE_CBC,
hex_to_str($iv)
);
}
function hex_to_str($hex_str) {
preg_match_all('/(..)/', $hex_str, $matches);
$to_return = '';
foreach ($matches[1] as $val)
$to_return .= chr(hexdec($val));
return $to_return;
}
输出最终只是垃圾,而不是我正在寻找的字符串。想法?
在我们开始之前,将其切换到MCRYPT_RIJNDAEL_256 似乎没有帮助,只会导致它抱怨 iv 没有块大小那么长。我相信 128 在这种情况下是正确的,因为 this site 表示 128/256 表示块大小,而不是密钥大小。
【问题讨论】:
-
请问您为什么要这样做?纯娱乐?因为您真的不应该编写自己的加密库以供生产使用。它们很容易搞砸,而且很难做到正确。
-
呃...我不是,我正在使用内置插件。请参阅上面的 OpenSSL 和 mcrypt 参考资料。
-
我只看什么都看不到。也许尝试对每个 iv、key 和 text hexes 进行解码,然后直接进行比较,看看那里是否有问题。 Rijndael_256 应该是正确的密码 - IV 可能是错误的,而 ruby 只是没有抱怨吗?