.net签名加密实现的一种简单方法-创新互联

加密方法有很多,以下是其中一种简单的签名模式

创新互联公司-专业网站定制、快速模板网站建设、高性价比印台网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式印台网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖印台地区。费用合理售后完善,10年实体公司更值得信赖。

1、首先客户端通过webapi按照IP地址,时间戳,随机数生成签名,并传递序列号

private Result_Sign Valid()
        {
            string ServerIP = "192.168.1.6";// HttpContext.Request.ServerVariables.Get("Local_Addr").ToString(); //地址
            string timestamp = DateTimeToStamp(DateTime.Now); //时间戳

           string nonce = ST.WEB.App_Start.Common.CreateValidateCode(6);//随机数
            string SignStr = SignatureString(ServerIP, timestamp, nonce);//生成签名
            string appseq = ConfigurationManager.AppSettings["DPSeq"]; //产品序列号
            string Url = string.Format("http://www.abc.com:89/api/Valid?signature={0}×tamp={1}&nonce={2}&appseq={3}", SignStr, timestamp, nonce, appseq);//POST发送URL

            string resStr = ST.WEB.App_Start.Common.Get_Http(Url, 12000);
            Result_Sign resJson = new Result_Sign()
                {
                    code = "-1",
                    message = ""
                };
            if (resStr.Substring(0, 2) != "错误")
            {
                resJson = JsonConvert.DeserializeObject(resStr);
            }
            return resJson;
 }

// DateTime时间格式转换为Unix时间戳格式
 private string DateTimeToStamp(DateTime time)
 {
      System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
       return ((int)(time - startTime).TotalSeconds).ToString();
 }

//生成签名串

private string SignatureString(string appIP, string timestamp, string nonce)
 {
            string[] ArrTmp = { appIP, timestamp, nonce };

            Array.Sort(ArrTmp);
            string tmpStr = string.Join("", ArrTmp);

            tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
            return tmpStr.ToLower();
 }

//生成随机数

public static string CreateValidateCode(int length)
{
            int[] randMembers = new int[length];
            int[] validateNums = new int[length];
            string validateNumberStr = "";
            //生成起始序列值
            int seekSeek = unchecked((int)DateTime.Now.Ticks);
            Random seekRand = new Random(seekSeek);
            int beginSeek = (int)seekRand.Next(0, Int32.MaxValue - length * 10000);
            int[] seeks = new int[length];
            for (int i = 0; i < length; i++)
            {
                beginSeek += 10000;
                seeks[i] = beginSeek;
            }
            //生成随机数字
            for (int i = 0; i < length; i++)
            {
                Random rand = new Random(seeks[i]);
                int pownum = 1 * (int)Math.Pow(10, length);
                randMembers[i] = rand.Next(pownum, Int32.MaxValue);
            }
            //抽取随机数字
            for (int i = 0; i < length; i++)
            {
                string numStr = randMembers[i].ToString();
                int numLength = numStr.Length;
                Random rand = new Random();
                int numPosition = rand.Next(0, numLength - 1);
                validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1));
            }
            for (int i = 0; i < length; i++)
            {
                validateNumberStr += validateNums[i].ToString();
            }
            return validateNumberStr;
 }

       ///


        /// 获取远程服务器ATN结果
        ///

        /// 指定URL路径地址
        /// 超时时间设置
        /// 服务器ATN结果
        public static string Get_Http(string strUrl, int timeout)
        {
            string strResult;
            try
            {
                HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strUrl);
                myReq.Timeout = timeout;
                HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
                Stream myStream = HttpWResp.GetResponseStream();
                StreamReader sr = new StreamReader(myStream, Encoding.Default);
                StringBuilder strBuilder = new StringBuilder();
                while (-1 != sr.Peek())
                {
                    strBuilder.Append(sr.ReadLine());
                }
                strResult = strBuilder.ToString();
            }
            catch (Exception exp)
            {
                strResult = "错误:" + exp.Message;
            }
            return strResult;
        }
2、服务器端获取数据并验证返回结果

[HttpGet]
 public Result_Sign Sign(string signature, string timestamp, string nonce, string appseq)
 {
            Result_Sign sign = new Result_Sign()
            {
                  code="0",
                  message="fault"
            };
            if (Tool.ValidateSignature(signature, timestamp, nonce, appseq))
            {
                sign.code = "1";
                sign.message = "success";
            }
            return sign;

}

       ///


        /// 检查应用接入的数据完整性
        ///

        /// 加密签名内容
        /// 时间戳
        /// 随机字符串
        /// 序列号
        ///
        public static  bool ValidateSignature(string signature, string timestamp, string nonce, string appseq)
        {
            bool result = false;
            Register item = Cache.GetBySeq(appseq);//获取序列号相关信息
            if (item != null)
            {
                if (DateTime.Parse(item.ExpireDT) < DateTime.Now.Date) //是否过期
                {
                    return result;
                }
                #region 校验签名参数的来源是否正确
                string[] ArrTmp = { item.IP, timestamp, nonce };
                Array.Sort(ArrTmp);
                string tmpStr = string.Join("", ArrTmp);
                tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
                tmpStr = tmpStr.ToLower();
                if (tmpStr == signature && isNumberic(timestamp))
                { //验证成功
                    DateTime dtTime =  StampToDateTime(timestamp);
                    double minutes = DateTime.Now.Subtract(dtTime).TotalMinutes;
                    if (minutes < 5) //时间不能大于5分钟
                    {
                        result = true;
                    }
                }
                #endregion
            }
            return result;
}

///


 ///  时间戳转时间
 ///

///
///
 private static DateTime StampToDateTime(string timeStamp)
 {
            DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dateTimeStart.Add(toNow);
 }

///


/// 是否为数字
 ///

 ///
 ///
 protected static bool isNumberic(string message)
 {
            System.Text.RegularExpressions.Regex rex =
            new System.Text.RegularExpressions.Regex(@"^\d+$");

            if (rex.IsMatch(message))
            {

                return true;
            }
            else
                return false;
 }

public class Result_Sign
{
        public string code { set; get; }
        public string message { set; get; }

}

创新互联www.cdcxhl.cn,专业提供香港、美国云服务器,动态BGP最优骨干路由自动选择,持续稳定高效的网络助力业务部署。公司持有工信部办法的idc、isp许可证, 机房独有T级流量清洗系统配攻击溯源,准确进行流量调度,确保服务器高可用性。佳节活动现已开启,新人活动云服务器买多久送多久。


文章名称:.net签名加密实现的一种简单方法-创新互联
链接分享:http://bzwzjz.com/article/cocgjo.html

其他资讯

Copyright © 2007-2020 广东宝晨空调科技有限公司 All Rights Reserved 粤ICP备2022107769号
友情链接: 定制网站制作 成都网站设计 营销型网站建设 企业网站设计 成都模版网站建设 专业网站建设 企业网站设计 高端定制网站设计 响应式网站设计方案 成都网站设计 广安网站设计 成都网站设计 成都网站制作 成都网站建设 成都企业网站设计 品牌网站建设 高端网站设计 手机网站设计 成都网站制作 成都网站制作 高端网站设计 成都网站设计