How to make Ruby AES-256-CBC and PHP MCRYPT_RIJNDAEL_128 play well together

前端 未结 4 642
梦如初夏
梦如初夏 2020-12-05 16:17

I\'m generating data to send from a Ruby stack to a PHP stack. I\'m using the OpenSSL::Cipher library on the Ruby side and the \'mcrypt\' library in PHP. When I encrypt us

4条回答
  •  离开以前
    2020-12-05 16:45

    I had troubles because the PHP was using a password smaller than 8 characters. In this case one needs to add the 0, to make it compatible with PHP:

    mcrypt-encrypt manual page "key

    The key with which the data will be encrypted. If it's smaller than the required keysize, it is padded with '\0'. It is better not to use ASCII strings for keys. http://php.net/manual/en/function.mcrypt-encrypt.php It is recommended to use the mhash functions to create a key from a string."

    require 'openssl'
    cipher = OpenSSL::Cipher.new('DES-ECB')
    cipher.encrypt
    key =  'passwrd'[0...7].ljust(8, 0.chr)  #Pad the key smaller than 8 chars
    cipher.key = key
    encrypted = cipher.update('33')
    encrypted << cipher.final
    dec = Base64.encode64(encrypted).strip()
    

提交回复
热议问题