Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Openssl encrypted in PHP needs to be decrypted in Ruby

In our application we are getting encrypted text from external server. This text have been encrypted using openssl in php.

When I am trying to decrypt the text in my Ruby code, I am getting following error message:

OpenSSL::Cipher::CipherError: wrong final block length

I read couple of solutions on Stackoverflow and was suggest to add following line to the code cipher.padding = 0. But after adding padding = 0, I am getting different error:

OpenSSL::Cipher::CipherError: data not multiple of block length

Below is my rough script I have written to decrypt the code.

require 'openssl'
require 'digest/sha1'
require 'base64'

encrypted = "VaZYJzn9QVEQIH4fmtA1Cg=="
key = "my_secret_key"

cipher = OpenSSL::Cipher::Cipher.new("aes-128-ecb")

cipher.decrypt
cipher.padding = 0

cipher.key = key

decrypted = cipher.update(encrypted)
decrypted << cipher.final
puts Base64.decode64(decrypted)

If I encrypt the text using Ruby then I can easily decrypt it. I am having problem to decrypt the code which are encrypted in php. Is there any way I can make encryption and decryption compatible between php and Ruby.

like image 930
r3b00t Avatar asked Nov 08 '22 21:11

r3b00t


1 Answers

Simply change the way you call it.

From decrypted << cipher.final to decrypted = cipher.update(encrypted) + cipher.final

could get the string like

<GF\x8F\xDC\x91\xE1ew\xB1\x1C\xE8\xF8V\xA0\x99g\x01C\xCDF\xD6\v\x841l\x13\xA6\x9496{

Last, quote from Ruby Doc You should never use ECB mode unless you are absolutely sure that you absolutely need it

like image 172
abookyun Avatar answered Nov 14 '22 22:11

abookyun