How can I copy 128 CFB in Ruby?

I need to exchange with the PHP API, which encrypts requests and responses. On my side, I am in rails 4.0.0 (ruby 2.0) and I cannot get it to work.

I read a lot of answers on this topic and tried to understand how mcrypt works, for example. http://www.chilkatsoft.com/p/php_aes.asp , but to no avail. I still can not decrypt encrypted with PHP or encrypt something that PHP can decrypt

Could you help me 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 
+5
source share
2 answers

You should use 'ncfb' instead of MCRYPT_MODE_CFB in your PHP code. PHP defaults to 8-bit feedback instead of full block size feedback.

Alternatively, you can specify :CFB8 for PHP compatibility in Ruby. I figured it out after reading the CFB documentation in the OpenSSL documentation.

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

+5
source

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

in your gem file add

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

Using

 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 fooobar.com/questions/1204759 / ...

+1
source

Source: https://habr.com/ru/post/1204758/


All Articles