Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 813
Stephanie Avatar asked Oct 15 '14 17:10

Stephanie


2 Answers

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.

like image 182
Maarten Bodewes Avatar answered Oct 21 '22 04:10

Maarten Bodewes


take a look at https://github.com/kingpong/ruby-mcrypt

in your gem file add

gem "ruby-mcrypt", :lib => "mcrypt"

Usage

crypto = Mcrypt.new(:twofish, :cbc, MY_KEY, MY_IV, :pkcs)

# encryption and decryption in one step
ciphertext = crypto.encrypt(plaintext)
plaintext  = crypto.decrypt(ciphertext)

# encrypt in smaller steps
while chunk = $stdin.read(4096)
  $stdout << crypto.encrypt_more(chunk)
end
$stdout << crypto.encrypt_finish

# or decrypt:
while chunk = $stdin.read(4096)
  $stdout << crypto.decrypt_more(chunk)
end
$stdout << crypto.decrypt_finish

you can also check out https://stackoverflow.com/a/21489711/1380867

like image 28
MZaragoza Avatar answered Oct 21 '22 06:10

MZaragoza