爱东东

VS.NET,IT,个人,个人网站 爱东东 http://www.idongdong.net

 

php和.net中的Md5函数如何兼容

最近在做一个php和.net共同组成的项目,接收.net部分传送过来的一个经md5过的数据,我惊奇的发现,居然和php进行md5的结果不同,这是为啥呢?

.net端程序是这么写的:

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);
输入的"xutf",得出的结果是"5j1NYFDLhM9dc/XOfRwkyg=="。

php端程序是这么写的:

$keymd5=base64_encode(md5("xutf"));
同样输入"xutf",得出来的结果却是"ZTYzZDRkNjA1MGNiODRjZjVkNzNmNWNlN2QxYzI0Y2E="。

这样下去,程序没法写了,同样的操作为什么结果不同呢?

原来php的md5函数输出的结果是转换成16位表示的md5结果,而.net的md5.ComputeHash方法输出的结果是原始的md5结果。(注:php5的md5函数string md5 ( string str [, bool raw_output] )开始支持输出原始结果,参数raw_output只支持php5,但是我在使用php4)

如果想让php的结果等同于.net的结果,那么需要对md5函数的结果进行16进制字符串到标准字符串的转换。
那么php程序应改为:

$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);

如果想让.net的结果等同于php的结果,那么需要把md5.ComputeHash方法输出的结果转换成16进制字符串,那么.net程序应该改为:

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

转自 http://www.tinydust.net/prog/diary/2006/11/phpnetmd5.html

posted on 2007-07-26 21:55  爱东东  阅读(1605)  评论(0编辑  收藏  举报

导航