paip.提升安全性-----时间判断

来源:互联网 发布:存储过程怎么执行sql 编辑:程序博客网 时间:2024/04/30 23:58

paip.提升安全性-----时间判断

常常有这样的情景,我们需要在编码中需要根据时间来执行某段代码,但是这段时间判断代码又不希望被别人看懂..特别是不能出现日期字串,以

防止别人猜明意思

伪码如下:
if( nowtime>"2013.1.1" )
{...........//some code
}


一个比较好的办法是使用magic number,并且不要使用相关的时间函数..如在C#,不要使用DATETIME类...
可以使用WIN32API来取时间,并且转换为LONG型数字来进行判断..

如:
  long t=      x.getl();     
     if (t > 63484678861000)
      {
       //todo
      }

 

这样就避免了代码段被人轻易读懂..这里的MAGIC NUMBER   63484678861000表示一个日期" 2013.1.1"..


getl函数主要如下,这里为了方便阅读,没有混淆加密。。如果在实际应用中,应该对此类方法进行混淆加密


------------------------- 相关代码--------------------------------------------

 

using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential)]     //这个如果不加,则返回值全部为0
public class MySystemTime
{
    public ushort wYear;      //必须设为ushort,如果为INT ,则数据错乱..WIN32API里是INTERGE
    public ushort wMonth;
    public ushort wDayOfWeek;
    public ushort wDay;
    public ushort wHour;
    public ushort wMinute;
    public ushort wSecond;
    public ushort wMilliseconds;
}
public class Win32API
{
   // [DllImport("User32.dll")]

        [DllImport("kernel32.dll")]
    public static extern void GetSystemTime(MySystemTime st);


        public static long getl()
        {
            //  是“协同世界时间”(即UTC,也叫做GMT)格式,需要+8个时区
            MySystemTime mt = new MySystemTime();
            Win32API.GetSystemTime(mt);

            int days = mt.wYear * 365 + mt.wMonth * 30 + mt.wDay;
            long millsecs = (long)days * 24 * 3600 * 1000 + (long)getHour(mt.wHour) * 3600 * 1000 + (long)mt.wMinute * 60 * 1000

+ mt.wSecond * 1000 + mt.wMilliseconds;
            //string s = mt.wYear + pad0left(mt.wMonth.ToString(), 2) + pad0left(mt.wDay.ToString(), 2);
            //s += getHour(mt.wHour) + pad0left(mt.wMinute.ToString(), 2) + pad0left(mt.wSecond.ToString(), 2);
            //s += pad0left(mt.wMilliseconds.ToString(), 3);
            return millsecs;
        }

        private static int getHour(ushort hour)
        {
            ushort t = (ushort)(hour +  ushort.Parse("8"));
            if (t == 24)
                t = 0;
            return t;
        }

        


        private static string pad0left(string ms, int len)
        {
            string strOrdid = ms;
            for (int i = 0; i < len - ms.Length; i++)
            {
                strOrdid = "0" + strOrdid;
            }
            return strOrdid;
        }

    public static long getMagicNum()
    {
                     int days = 2013 * 365 + 1 * 30 + 1;
            long millsecs = (long)days * 24 * 3600 * 1000 + (long)getHour(1) * 3600 * 1000 + (long)1 * 60 * 1000 +1 * 1000 + 0;
              return millsecs;
    }
}