Ruby代码是
require 'base64'
require 'openssl'
def ruby_dec iv, key, encrypted
decipher = OpenSSL::Cipher::AES.new(128, :CBC)
#decipher.padding = 0
decipher.decrypt
decipher.key = key
decipher.iv = iv
ciphertext = Base64.decode64 encrypted
decipher.update(ciphertext) + decipher.final
end
def ruby_enc iv, key, plaintext
enc = OpenSSL::Cipher.new 'aes-128-cbc'
enc.encrypt
enc.key = key
enc.iv = iv
Base64.encode64(enc.update(plaintext) + enc.final)
end
iv = Base64.decode64("TOB+9YNdXSbkSYIU7D/IpQ==")
key = Base64.decode64("7DxoShENB0D+8xrwOwSbi1TPQBiIaFq2yveoUkutCpM=")
plaintext = "testtesttest"
encrypted = ruby_enc iv, key, plaintext
puts "encrypted is #{encrypted}"
ruby_dec iv, key, encrypted
puts "plaintext is #{plaintext}"
然后
$ ruby enc_dec.rb #the above code
encrypted is LXJmnM7t+HGKi2iI51ethA==
plaintext is testtesttest
现在PHP代码
function php_dec($iv, $key, $encrypted) {
$cipher_algorithm = 'rijndael-128';
$cipher_mode = 'cbc';
$key = base64_decode($key);
$iv = base64_decode($iv);
$ciphertext = base64_decode($enctypted);
return $ciphertext;
}
function php_enc($iv, $key, $plaintext){
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
$mcrypt_key = base64_decode($key);
$iv = base64_decode($iv);
mcrypt_generic_init($td, $mcrypt_key, $iv);
$ciphertext = mcrypt_generic($td, $plaintext);
retun base64_encode($ciphertext);
}
$iv = base64_decode("TOB+9YNdXSbkSYIU7D/IpQ==");
$key = base64_decode("7DxoShENB0D+8xrwOwSbi1TPQBiIaFq2yveoUkutCpM=");
$plaintext = "testtesttest";
$encrypted = php_enc($iv, $key, $plaintext);
echo "encrypted is ".$encrypted."\n";
php_dec($iv, $key, $encrypted);
echo "plaintext is ".$plaintext."\n";
$ruby_encrypted = base64_encode("LXJmnM7t+HGKi2iI51ethA==");
php_dec($iv, $key, $ruby_encrypted);
echo "plaintext is ".$plaintext."\n";
然后我得到
$ php enc_dec.php
encrypted is SUR33tXu32JjR9JAKIGL7w==
plaintext is testtesttest
plaintext is testtesttest
密文与红宝石不同。 现在我尝试使用PHP制作的密文来解密ruby。
$ pry
[1] pry(main)> load 'enc_dec.rb'
[2] pry(main)> iv = Base64.decode64("TOB+9YNdXSbkSYIU7D/IpQ==")
=> "L\xE0~\xF5\x83]]&\xE4I\x82\x14\xEC?\xC8\xA5"
[3] pry(main)> key = Base64.decode64("7DxoShENB0D+8xrwOwSbi1TPQBiIaFq2yveoUkutCpM=")
=> "\xEC<hJ\x11\r\a@\xFE\xF3\x1A\xF0;\x04\x9B\x8BT\xCF@\x18\x88hZ\xB6\xCA\xF7\xA8RK\xAD\n\x93"
[4] pry(main)> ruby_dec iv, key, Base64.decode64("SUR33tXu32JjR9JAKIGL7w==")
OpenSSL::Cipher::CipherError: data not multiple of block length
from enc_dec.rb:12:in `final'
[5] pry(main)>
Ruby'AES-128-CBC'和PHP'rindnda-128'加密之间有什么区别吗? 我怎么能用ruby解密?
答案 0 :(得分:4)
AES和Rijndael之间的区别在于128的含义,在AES中,128是密钥大小,在Rijndael中它是块大小。
你使用的密钥大于128位,我相信。
看到这篇文章: http://www.leaseweblabs.com/2014/02/aes-php-mcrypt-key-padding/