简体   繁体   中英

PHP MD5/base64 encryption to C# md5/base64 encryption

I am in the process of try to integrate some C# ASP.NET webservice into my PHP application however there is a big problem. The way the C# webservice does the encryption is not compatible with the way PHP does the MD5 encryption. I have found solution for converting the C# MD5 to PHP MD5 however I can't change the C# code. Is there a way to change the way that PHP does its MD5 encryption to match C#? The c# encryption works like this:

MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(stringToEncrypt);
String myString = Convert.ToBase64String(MD5.ComputeHash(bs));

Since MD5 is a published algorithm, the implementations in PHP and c# are identical. The only difference is the string format of the byte sequence they produce. PHP produces a hex string, so you just need to convert from hex to Base64.

This could be an encoding issue. Make sure your PHP version gets the UTF-8 representation of the string, apply MD5, then convert to a base 64 string, and you should be fine.

This is an encoding issue I have had before between PHP and C#.

If PHP is manipulating ISO-8859-1 strings (which is probably your case), you can do:

md5(utf8_encode($stringToEncrypt))

The best way to test is to try a very simple string with az content, which should work fine regardless of any encoding issue. It that works and the whole thing doesn't, you have an encoding issue.

You could also do:

byte[] bs = System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(stringToEncrypt);

and

md5($stringToEncrypt)

will work just fine.

I see what is your problem:

String myString = Convert.ToBase64String(MD5.ComputeHash(bs)); 

will make a Base64 string out of a pure MD5 array hash.

PHP will first make an hex representation of the MD5 hash then base64-encode it.

You should get the hex result first as described here:

http://blog.stevex.net/c-code-snippet-creating-an-md5-hash-string/

and then base64 encode the string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM