Search code examples
phprubyencryptionaesmcrypt

How can I mcrypt 128 CFB to Ruby?


I need to exchange with a PHP API which crypts the requests and answers. On my side I am in rails 4.0.0 (ruby 2.0) and I cannot make it work.

I have read a lot of answers on this subject and have tried to understand how mcrypt works, e.g. http://www.chilkatsoft.com/p/php_aes.asp, but without success. I still cannot decrypt the encrypted from PHP or encrypt something that the PHP can decrypt

Could you help me please and see what I am doing wrong?

PHP code:

$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 code:

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

Solution

  • You have to use 'ncfb' instead of MCRYPT_MODE_CFB in the PHP code. PHP defaults to an 8 bit feed back instead of a feed back of the full block size.

    Alternatively you can specify :CFB8 to be compatible with PHP in Ruby. This one I guessed after reading the documentation for CFB in the OpenSSL documentation.

    Many thanks to this Q/A on IT security which I only found because I knew what I was looking for.