最近在对一个现有的系统进行c#改造,该系统以前是用php做的,后台的管理员登陆用的是md5加密算法。在php中,要对一个字符串进行md5加密非常简单,一行代码即可: md5 (something you want to encrypt.) 直接调用md5()方法,然后将要进行md5加密的字符串传
最近在对一个现有的系统进行c#改造,该系统以前是用php做的,后台的管理员登陆用的是md5加密算法。在php中,要对一个字符串进行md5加密非常简单,一行代码即可:
md5(something you want to encrypt.)
直接调用md5()方法,然后将要进行md5加密的字符串传进去,就可以得到返回的hash code。在c#中应该也会有对应的算法吧!对吗?我首先尝试了下面的代码,结果得到的hash code和php不一样。
public static string md5(string stringtohash){ return formsauthentication.hashpasswordforstoringinconfigfile(stringtohash, md5);}
所以,我们不得不借用c#的md5cryptoserviceprovider对象自己写代码进行转换。
1. 实例化md5cryptoserviceprovider对象
2. 将字符串转换成byte数组
3. 使用md5cryptoserviceprovider对象的computehash()方法将byte数组进行加密,返回转换后的byte数组
4. 在讲byte数组转换成字符串之前,还需要对其进行遍历并做如下转换:
mybyte.tostring(x2).tolower()
然后,你才能得到和php中一样的md5 hash code。为什么在.net中要这么麻烦,或许这也是为什么那么多的开发人员仍然热衷于php开发的理由之一,每一门编程语言都有它自身的魅力,也都有它存在的意义!
基于上面的讨论,完整的代码如下:
public static string md5forphp(string stringtohash){ var md5 = new system.security.cryptography.md5cryptoserviceprovider(); byte[] emailbytes = encoding.utf8.getbytes(stringtohash.tolower()); byte[] hashedemailbytes = md5.computehash(emailbytes); stringbuilder sb = new stringbuilder(); foreach (var b in hashedemailbytes) { sb.append(b.tostring(x2).tolower()); } return sb.tostring();}
或者,你也可以把上面的方法写成一个c#扩展方法,只需要修改方法签名即可。
public static string md5forphp(this string, string stringtohash){ // your code here.}
php程序和c#程序在许多方面都会涉及到格式之间的转换,如果运行php的服务器是unix类型的,则还会存在日期格式之间的转换。下面的两个方法展示了如何将unix时间转换成c# datetime以及如何将c# datetime转换成unix时间。
public static datetime unixtimestamptodatetime(long unixtimestamp){ // unix timestamp is seconds past epoch datetime dtdatetime = new datetime(1970, 1, 1, 0, 0, 0, 0, system.datetimekind.utc);
return dtdatetime.addseconds(unixtimestamp);}public static long datetimetounixtimestamp(datetime datetime){ timespan span = (datetime - new datetime(1970, 1, 1, 0, 0, 0, 0, datetimekind.utc)); return (long)span.totalseconds;}
