我正在生成要从Ruby堆栈发送到PHP堆栈的数据.我在Ruby端使用OpenSSL :: Cipher库,在PHP使用'mcrypt'库.当我在Ruby中使用'aes-256-cbc'(256位块大小)进行加密时,我需要在PHP中使用MCRYPT_RIJNDAEL_128(128位块大小)来解密它.我怀疑Ruby代码坏了,因为cipher.iv_len是16; 我相信它应该是32:
>> cipher = OpenSSL::Cipher::Cipher.new('aes-128-cbc')
=> #<OpenSSL::Cipher::Cipher:0x3067c5c>
>> cipher.key_len
=> 16
>> cipher.iv_len
=> 16
>> cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
=> #<OpenSSL::Cipher::Cipher:0x306de18>
>> cipher.key_len
=> 32
>> cipher.iv_len
=> 16
Run Code Online (Sandbox Code Playgroud)
所以这是我的考试.在Ruby方面,首先我生成密钥和iv:
>> cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
>> cipher.encrypt
>> iv = cipher.random_iv
>> iv64 = [iv].pack("m").strip
=> "vCkaypm5tPmtP3TF7aWrug=="
>> key = cipher.random_key
>> key64 = [key].pack("m").strip
=> "RIvFgoi9xZaHS/0Bp0J9WDRyND6Z7jrd3btiAfcQ8Y0="
Run Code Online (Sandbox Code Playgroud)
然后我使用这些密钥进行加密:
>> plain_data = "Hi, Don, this is a string."
>> cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
>> cipher.encrypt
>> cipher.key = Base64.decode64(key64)
>> …Run Code Online (Sandbox Code Playgroud) 这个问题是我最后一个问题的延续,关于如何使Ruby AES-256-CBC和PHP MCRYPT_RIJNDAEL_128一起发挥得很好.我现在已经开始工作,但我仍然在努力朝着另一个方向努力.PHP生成的密码似乎具有提供的所有信息,但是我无法使用Ruby代码来解密它而不会出现错误.
这是我用来生成密码的PHP代码:
$cleartext = "Who's the clever boy?";
$key = base64_decode("6sEwMG/aKdBk5Fa2rR6vVw==\n");
$iv = base64_decode("vCkaypm5tPmtP3TF7aWrug==");
$cryptogram = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $cleartext, MCRYPT_MODE_CBC, $iv);
$result = base64_encode($cryptogram);
print "\n'$result'\n";
RESULT
'JM0OxMINPTnF1vwXdI3XdKI0KlVx210CvpJllFja+GM='
Run Code Online (Sandbox Code Playgroud)
然后这是尝试在Ruby中解密:
>> cipher = OpenSSL::Cipher::Cipher.new('aes-128-cbc')
>> cipher.key = Base64.decode64("6sEwMG/aKdBk5Fa2rR6vVw==\n")
>> cipher.iv = Base64.decode64("vCkaypm5tPmtP3TF7aWrug==")
>> cryptogram = Base64.decode64('JM0OxMINPTnF1vwXdI3XdKI0KlVx210CvpJllFja+GM=')
>> cleartext = cipher.update(cryptogram)
=> "Who's the clever"
>> cleartext << cipher.final
OpenSSL::Cipher::CipherError: bad decrypt
from (irb):100:in `final'
from (irb):100
Run Code Online (Sandbox Code Playgroud)
令人沮丧的是,可以从加密字符串中获取整个明文.重复上述内容,但在密码中添加一个无意义的填充:
>> cleartext = cipher.update(cryptogram + 'pad')
=> "Who's the clever …Run Code Online (Sandbox Code Playgroud)