Skip to content
Advertisement

How to properly call openssl_decrypt method if I have base64 string which contains from IV and encrypted data?

I have code in C# which encrypts and decrypts string:

JavaScript

If you check Decrypt(byte[] buffer), I take first 16 bytes which is IV.

Now I similar want to implement in PHP (imagine, that I will encode on C# side and send it to server which runs on php, where I want to decrypt it back). As the param to my PHP decrypt function will be output of C# public string Encrypt(string unencrypted). I somehow need to get those 16 bytes to get IV and the rest part, which I respectively will pass as $data and $iv params to $decrypted_data = openssl_decrypt($data, $cipher, $encryption_key, 0, $iv); function

I have tried to use something like this (using unpack):

JavaScript

and then tried to take 16 first numbers and somehow convert them back with pack method. But probably I have lack of knowledge.

Could you please help me with this?

P.S. This one I have tried based on Ilya’s answer and comments.

JavaScript

also if I debug code and check which bytes are in $iv using this code:

JavaScript

and comparing with C# this byte array byte[] iv = buffer.Take(16).ToArray(); , they are equals, then I expect, that I am using wrongly openssl_decrypt method

Advertisement

Answer

Firstly, I was having an issue how to correct retrieve 16 first bytes from string, because I thought I was doing it incorrectly. Thanks from @Ilia Yatsenko for his answer:

JavaScript

But then I have realised, that I am wrongly using openssl_decrypt() method. After having conversation in comments, particularly with @Topaco, we found what was the proble. Here is working code:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement