Recently I am working on a PHP and. net project, receiving. I was surprised to find that the MD5 result was different from that of PHP. Why?
. Net endProgramIt is written in this way:
System. Text. asciiencoding encoding = new system. Text. asciiencoding ();
Byte [] bytessrc = encoding. getbytes ("xutf ");
System. Security. cryptography. MD5 MD5 = new system. Security. cryptography. md5cryptoserviceprovider ();
Byte [] result = md5.computehash (bytessrc );
String keymd5 = convert. tobase64string (result );
Input "xutf" and the result is "5j1nyfdlhm9dc/xofrwkyg = ".
The PHP program is written as follows:
$ Keymd5 = base64_encode (MD5 ("xutf "));
Enter "xutf" and the result is "ztyzzdrknja1mgniodrjzjvknznmnwnln2qxyzi0y2e = ".
In this case, the program cannot be written. Why are the results of the same operation different?
The MD5 function output result of PHP is converted to the MD5 result represented by 16 bits, while the md5.computehash method of. Net outputs the original MD5 result. (Note: the MD5 function of PhP5 string MD5 (string STR [, bool raw_output]) starts to support the output of the original results. The raw_output parameter only supports PhP5, but I am using PhP4)
If you want PHP results to be equivalent to. net results, you need to convert the results of the MD5 function from a hexadecimal string to a standard string.
Then the PHP program should be changed:
$ Md5hex = MD5 ("xutf ");
$ Len = strlen ($ md5hex)/2;
$ Md5raw = "";
For ($ I = 0; $ I <$ Len; $ I ++) {$ md5raw = $ md5raw. CHR (hexdec (substr ($ md5hex, $ I * 2, 2);} $ keymd5 = base64_encode ($ md5raw );
If you want to make the. net result equivalent to the PHP result, you need to convert the result output by the md5.computehash method to a hexadecimal string, then the. NET program should be changed:
System. Text. asciiencoding encoding = new system. Text. asciiencoding ();
Byte [] bytessrc = encoding. getbytes ("xutf ");
System. Security. cryptography. MD5 MD5 = new system. Security. cryptography. md5cryptoserviceprovider ();
Byte [] result = md5.computehash (bytessrc );
Stringbuilder sb = new stringbuilder ();
For (INT I = 0; I <result. length; I ++)
SB. appendformat ("{0: X2}", result [I]);
String S1 = sb. tostring ();
Byte [] bytesmd5 = encoding. getbytes (S1 );
String keymd5 = convert. tobase64string (bytesmd5 );
Self-http://www.tinydust.net/prog/diary/2006/11/phpnetmd5.html