« Return to Thread: Converting PHP code to C#?

Re: Converting PHP code to C#?

by Symbian :: Rate this Message:

Reply to Author | View in Thread

Mike,

Thanks for the reply and your very useful notes.

I'm unable to workout how to get the same IV as the one generated by the PHP script is random. The thing is that we cant change the PHP script as its readily being used now. Maybe I should look at the encryption routine and reverse that first?

Thanks,
Sym

mike-22 wrote:
I've done it in reverse - something encrypted in .NET and then decrypted in PHP

these were my notes...


To get .NET and PHP to play friendly with two-way encryption, you need
to make sure some things happen in both:
In .NET:
1) You need to set the Padding to PaddingMode.Zeros, i.e.:
 Rijndael alg = Rijndael.Create();
 alg.Padding = PaddingMode.Zeros;
2) You also need to make sure to use System.Text.Encoding.ASCII or
System.Text.Encoding.UTF8; System.Text.Encoding.Unicode will *not*
work (perhaps in PHP6 this might be possible.)
3) Need to make sure the IV and key are the same as defined in PHP.

In PHP:
1) You need the mcrypt extension installed.
2) Need to make sure the IV and key are the same as defined in .NET.
3) You can issue this single line of code to decrypt:
 mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $encrypted_text, "cbc", $iv);

Notes:
1) By default .NET uses a 128-bit cipher in CBC mode when you
initialize Rijndael. That might not be common knowledge.
2) If you're sending this data via a URL or cookie or something else,
be sure to base64 encode on the .NET side, and base64_decode() the
data on the PHP side.


below i would say that:

a) you need to make sure the IV is the same. right now it looks like
you are creating a random one in PHP and a different one in .NET. that
would be my first thing to check.

b) not sure if ECB vs. CBC is any different; i know CBC will work though.

hope that helps some. it took some debugging for us, and it didn't
help that our .NET guy created the IV using low and high ascii
character codes that I had to reproduce in PHP for the IV and the
key... I would get different sizes as well, but once the stars aligned
it worked perfectly. Be sure that any base64 encoding/decoding or
anything like that is done in the proper order (typically start out
with no encoding, get it to work, then add on encoding and decoding on
both ends properly, etc.)

good luck :)

 « Return to Thread: Converting PHP code to C#?