Encryption in PHP (mcrypt), Decryption in Ruby (OpenSSL :: Cipher)

I am working on a cross-language project that wraps the ruby โ€‹โ€‹/ Sinatra API in PHP, which will be used by another team. None of the information provided by the API is sensitive, but we would prefer it not to be easily accessible to a random observer guessing the URL.

private function generateSliceIDToken($key){ $currentEpoch = time(); $ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); $iv = mcrypt_create_iv($ivSize, MCRYPT_RAND); $encryptedBytes = mcrypt_encrypt( MCRYPT_RIJNDAEL_128, $key, $currentEpoch.**Passcode**, MCRYPT_MODE_CBC, $iv ); $ivAndEncryptedBytes = $iv . $encryptedBytes; return urlencode(urlencode(base64_encode($ivAndEncryptedBytes))); 

Code above Encrypts password and timestamp using mcrypt RIJNDAEL implementation and encodes it for sending to ruby โ€‹โ€‹API

 if identifier.validate_token Base64.decode64(URI.unescape( URI.unescape(params[:token]))) 

Sinatra captures and decodes it

 def validate_token(token) cipher = OpenSSL::Cipher::AES.new(128, 'CBC') cipher.decrypt cipher.key = **key** cipher.iv = token[0,16] plain = cipher.update(token[16..-1]) + cipher.final return plain[10,8] == **Passcode** end 

and transfers it for decryption

The problem is that the decryption failed with the "Bad Decrypt" error

I was fortunate that Mcrypt RIJNDAEL and Cipher AES were compatible, but is this assumption wrong? Any help I can get would be most helpful.

+2
source share
1 answer

I was fortunate that Mcrypt RIJNDAEL and Cipher AES were compatible, but is this an assumption?

You need to tweak the data encoded a bit to ensure AES compatibility. Data should be correctly supplemented, with character and quantity depending on its current width:

 $encode = $currentEpoch.'**Passcode**'; $len = strlen($encode); $pad = 16 - ($len % 16); $encode .= str_repeat(chr($pad), $pad); 

Also remember that $key exactly 16 characters long. If it is shorter, the ruby โ€‹โ€‹throws a CipherError, and the php pads key throws with zero bytes. If it is longer, ruby โ€‹โ€‹uses only the first 16 characters, but php pads it again and uses the last 16 characters.

+3
source

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


All Articles