我需要使用PHP API来交换请求和答案。在我这边我是在rails 4.0.0(ruby 2.0),我无法使它工作。
我已经阅读了很多有关此主题的答案,并尝试了解mcrypt的工作原理,例如: http://www.chilkatsoft.com/p/php_aes.asp,但没有成功。我仍然无法解密从PHP加密或加密PHP可以解密的东西
你能帮助我,看看我做错了吗?
PHP代码:
$secretKey = "1234567891234567";
$encrypt = urlencode( base64_encode( mcrypt_encrypt(
MCRYPT_RIJNDAEL_128,
md5($secretKey),
$cleartext,
MCRYPT_MODE_CFB,
$secretKey
) ) );
$input = urldecode($input);
$decrypt = mcrypt_decrypt( MCRYPT_RIJNDAEL_128,
md5($secretKey),
base64_decode($input),
MCRYPT_MODE_CFB,
$secretKey );
Ruby代码:
def self.encode(params = {})
cipher = OpenSSL::Cipher::AES.new(256, :CFB)
cipher.encrypt
cipher.key = Digest::MD5.hexdigest("1234567891234567")
cipher.iv = "1234567891234567"
encrypted = cipher.update(params.to_query) + cipher.final
CGI.escape(Base64.strict_encode64(encrypted))
end
def self.decode(answer)
decrypted = Base64.decode64(CGI.unescape(answer))
decipher = OpenSSL::Cipher::AES.new(256, :CFB)
decipher.decrypt
decipher.key = Digest::MD5.hexdigest("1234567891234567")
decipher.iv = "1234567891234567"
decoded = decipher.update(decrypted) + decipher.final
end
答案 0 :(得分:5)
您必须在PHP代码中使用'ncfb'
而不是MCRYPT_MODE_CFB
。 PHP默认为8位反馈,而不是整个块大小的反馈。
或者,您可以指定:CFB8
与Ruby中的PHP兼容。我在OpenSSL文档中阅读CFB文档后猜到了这一点。
非常感谢this Q/A on IT security,我才发现因为我知道我在寻找什么。
答案 1 :(得分:1)
看看https://github.com/kingpong/ruby-mcrypt
在你的gem文件中添加
gem "ruby-mcrypt", :lib => "mcrypt"
<强>用法强>
crypto = Mcrypt.new(:twofish, :cbc, MY_KEY, MY_IV, :pkcs)
# encryption and decryption in one step
ciphertext = crypto.encrypt(plaintext)
plaintext = crypto.decrypt(ciphertext)
# encrypt in smaller steps
while chunk = $stdin.read(4096)
$stdout << crypto.encrypt_more(chunk)
end
$stdout << crypto.encrypt_finish
# or decrypt:
while chunk = $stdin.read(4096)
$stdout << crypto.decrypt_more(chunk)
end
$stdout << crypto.decrypt_finish