Converting PHP code to C#?

View: New views
8 Messages — Rating Filter:   Alert me  

Converting PHP code to C#?

by Symbian :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hi,

I'm not sure if this is the right place to post this, I have some decryption routines that use mcrypt that I need to decrypt in .NET, does anyone know how why I cant get this to work?

---- PHP
$mcryptSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$mcryptIV = mcrypt_create_iv($mcryptSize, MCRYPT_RAND);
$mcryptData = pack("H*", $data);
$decryptData =
mcrypt_decrypt(MCRYPT_RIJNDAEL_128,$key,$mcryptData,MCRYPT_MODE_ECB,$mcryptIV);
---------

$decryptData should be 2048 in size. Here's my C# converted bits:
------------- C#

RijndaelManaged rj = new RijndaelManaged();
rj.Mode = CipherMode.ECB;
rj.Key = ASCIIEncoding.ASCII.GetBytes(KEY);
rj.KeySize = 128;
rj.GenerateIV();
rj.Padding = PaddingMode.Zeros;
ICryptoTransform trans = rj.CreateDecryptor(rj.Key, rj.IV);
byte[] Buffer = Convert.FromBase64String(DATA);
string dataD =
ASCIIEncoding.ASCII.GetString(trans.TransformFinalBlock(Buffer,0,
Buffer.Length));
-------------

However the length is 3017

Any ideas?

Thanks,
Sym

Re: Converting PHP code to C#?

by Michael Shadle :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

On 9/7/07, Symbian <mail5205772@...> wrote:
>
> Hi,
>
> I'm not sure if this is the right place to post this, I have some decryption
> routines that use mcrypt that I need to decrypt in .NET, does anyone know
> how why I cant get this to work?


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 :)


> ---- PHP
> $mcryptSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
> $mcryptIV = mcrypt_create_iv($mcryptSize, MCRYPT_RAND);
> $mcryptData = pack("H*", $data);
> $decryptData =
> mcrypt_decrypt(MCRYPT_RIJNDAEL_128,$key,$mcryptData,MCRYPT_MODE_ECB,$mcryptIV);
> ---------
>
> $decryptData should be 2048 in size. Here's my C# converted bits:
> ------------- C#
>
> RijndaelManaged rj = new RijndaelManaged();
> rj.Mode = CipherMode.ECB;
> rj.Key = ASCIIEncoding.ASCII.GetBytes(KEY);
> rj.KeySize = 128;
> rj.GenerateIV();
> rj.Padding = PaddingMode.Zeros;
> ICryptoTransform trans = rj.CreateDecryptor(rj.Key, rj.IV);
> byte[] Buffer = Convert.FromBase64String(DATA);
> string dataD =
> ASCIIEncoding.ASCII.GetString(trans.TransformFinalBlock(Buffer,0,
> Buffer.Length));
> -------------
>
> However the length is 3017

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


Re: Converting PHP code to C#?

by Symbian :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

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 :)

Re: Converting PHP code to C#?

by Michael Shadle :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

On 9/7/07, Symbian <mail5205772@...> wrote:
>
> 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?

just hard code the IV in both places.

to make it difficult you can do something like this (basically our
.NET guy took it from
http://www.codeproject.com/dotnet/DotNetCrypto.asp)

public static string Encrypt(string clearText, string Password)
    {
        // First we need to turn the input string into a byte array.
        byte[] clearBytes =
          System.Text.Encoding.UTF8.GetBytes(clearText);

PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
            new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
            0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});

 byte[] encryptedData = Encrypt(clearBytes,
                 pdb.GetBytes(32), pdb.GetBytes(16));

   return Convert.ToBase64String(encryptedData);

}

(make sure to copy that first Encrypt method and set alg.Padding =
PaddingMode.Zeros)

and on PHP side (the IV/key numbers have been changed to protect the
innocent :))

i believe the numbers are the decimal values of the .NET 0x49 etc. you
need 32 of them for the key, and 16 for the IV (to match the
parameters above) - these numbers do not match right now i just
jumbled them up. i would first see if you can use my code to properly
encrypt in .NET and decrypt in PHP. then hopefully you can just
reverse it.

what i should do is actually publish an example with working
instructions + numbers. i'll keep this email around and publish an
article on my blog or something hopefully soon.

function decrypt($text, $key) {
        $enc_key_array = Array(24,91,81,138,122,etc);
        $chrs = "";
        foreach(array_values($enc_key_array) as $chr) {
                $chrs .= chr($chr);
        }
        $enc_key = $chrs;
        $enc_iv_array = Array(35,56,103,81,77,etc);
        $chrs = "";
        foreach(array_values($enc_iv_array) as $chr) {
                $chrs .= chr($chr);
        }
        $enc_iv = $chrs;
        $text = base64_decode($text);
        $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $enc_key,
$text, "cbc", $enc_iv);
        return $decrypted."\n";
}

remember to base64 encode/decode at the proper times. we use this to
encrypt information in a cookie so it needs to be encoded for transit.
it also helps when you are copy/pasting it back and forth to test
encrypt/decrypt :)

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


Re: Converting PHP code to C#?

by Symbian :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message


mike-22 wrote:
just hard code the IV in both places.
Thanks for the link, that was most useful, especially the commented bits!

RE: The IV, reading the php manual it states that the IV is not used when ECB mode is used (which is what we are using). So knowing this does the use of IV matter? I stripped the decrypt routine from the PHP file (big file!) and tried it on a seperate PHP page without parsing a IV like so:

mcrypt_decrypt(MCRYPT_RIJNDAEL_128,$key,$mcryptData,MCRYPT_MODE_ECB,"");

While i got an error from the module:

Warning:  mcrypt_decrypt() [function.mcrypt-decrypt]: The IV parameter must be as long as the blocksize in crypto.php on line 38

It still decrypted it fine on the php page.

Re: Converting PHP code to C#?

by Michael Shadle :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

i'm pretty sure the IV mattered in our stuff.

and remember i used CBC i think not EBC, and it worked fine. not sure
if you want to try that and make it work for you or not without any
warnings :)

On 9/8/07, Symbian <mail5205772@...> wrote:

>
>
>
> mike-22 wrote:
> >
> > just hard code the IV in both places.
> >
>
> Thanks for the link, that was most useful, especially the commented bits!
>
> RE: The IV, reading the php manual it states that the IV is not used when
> ECB mode is used (which is what we are using). So knowing this does the use
> of IV matter? I stripped the decrypt routine from the PHP file (big file!)
> and tried it on a seperate PHP page without parsing a IV like so:
>
> mcrypt_decrypt(MCRYPT_RIJNDAEL_128,$key,$mcryptData,MCRYPT_MODE_ECB,"");
>
> While i got an error from the module:
>
> Warning:  mcrypt_decrypt() [function.mcrypt-decrypt]: The IV parameter must
> be as long as the blocksize in crypto.php on line 38
>
> It still decrypted it fine on the php page.
> --
> View this message in context: http://www.nabble.com/Converting-PHP-code-to-C---tf4397727.html#a12575594
> Sent from the PHP - General mailing list archive at Nabble.com.
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


Re: Converting PHP code to C#?

by Symbian :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message


mike-22 wrote:
i'm pretty sure the IV mattered in our stuff.

and remember i used CBC i think not EBC, and it worked fine. not sure
if you want to try that and make it work for you or not without any
warnings :)
Ah! We're using EBC, also I realised that I needed to implement the eqivalent of the pack function in PHP which we use, so I finally have the correct (MD5'd both the PHP and C# bits) string going *into* the function.

Now I have to wrestle with the Rijndael class again:(

            Rijndael r = Rijndael.Create();
            r.Mode = CipherMode.ECB;
            r.Padding = PaddingMode.None;
            r.Key = Encoding.ASCII.GetBytes(KEY);
            ICryptoTransform de = r.CreateDecryptor();
            byte[] output = CryptoTransform(input, de);

Sym

Re: Converting PHP code to C#?

by ariki :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

I go the same problem as well, how could I hardcode the iv and key, if iv="abc" and key="123" in C#, what are the iv and key in PHP?

Symbian wrote:
mike-22 wrote:
i'm pretty sure the IV mattered in our stuff.

and remember i used CBC i think not EBC, and it worked fine. not sure
if you want to try that and make it work for you or not without any
warnings :)
Ah! We're using EBC, also I realised that I needed to implement the eqivalent of the pack function in PHP which we use, so I finally have the correct (MD5'd both the PHP and C# bits) string going *into* the function.

Now I have to wrestle with the Rijndael class again:(

            Rijndael r = Rijndael.Create();
            r.Mode = CipherMode.ECB;
            r.Padding = PaddingMode.None;
            r.Key = Encoding.ASCII.GetBytes(KEY);
            ICryptoTransform de = r.CreateDecryptor();
            byte[] output = CryptoTransform(input, de);

Sym