如何使Ruby AES-256-CBC和PHP MCRYPT_RIJNDAEL_128一起玩得很好

前端之家收集整理的这篇文章主要介绍了如何使Ruby AES-256-CBC和PHP MCRYPT_RIJNDAEL_128一起玩得很好前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在生成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

所以这是我的测试.在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="

然后我用这些密钥进行加密:

>> plain_data = "Hi,Don,this is a string."
>> cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
>> cipher.encrypt
>> cipher.key = Base64.decode64(key64)
>> cipher.iv = Base64.decode64(iv64)
>> encrypted_data = cipher.update(plain_data)
>> encrypted_data << cipher.final
>> crypt64 = [encrypted_data].pack("m").strip
=> "5gfC/kJcnAV2fJI0haxnLcdraIKWgtu54UoznVxf8K0="

这是PHP解密:

$ruby_crypt = "5gfC/kJcnAV2fJI0haxnLcdraIKWgtu54UoznVxf8K0=";
$encrypted_data = base64_decode($ruby_crypt);
$key = base64_decode("RIvFgoi9xZaHS/0Bp0J9WDRyND6Z7jrd3btiAfcQ8Y0=");
$iv = base64_decode("vCkaypm5tPmtP3TF7aWrug==");
$result = mcrypt_decrypt(MCRYPT_RIJNDAEL_128,$key,$encrypted_data,MCRYPT_MODE_CBC,$iv);
$unencrypt = rtrim($result,"\x00..\x1F");
print "\nUnencrypted token:\n'$unencrypt'\n";

RESULT:
Unencrypted token:
'Hi,this is a string.'

我更喜欢使用更长的块大小.显然我误解了API.帮帮我?

解决方法

我不知道PHP,但是阅读侧栏中的相关问题,我看到了 Converting Ruby AES256 decrypt function to PHP.这包括了对 this page的引用,指出MCRYPT_RIJNDAEL_128中的128是指加密的块大小,而不是密钥大小.你会注意到,在这两种情况下,你在ruby和PHP之间传递的关键大小是256位.换句话说,这似乎是预期的行为,而你正在使用较大的密钥.
#!/usr/bin/ruby
require 'base64'

puts((Base64.decode64("RIvFgoi9xZaHS/0Bp0J9WDRyND6Z7jrd3btiAfcQ8Y0=").length * 8).to_s)

HTH

原文链接:https://www.f2er.com/ruby/267122.html

猜你在找的Ruby相关文章