网站中找回密码实现的一种方式,使用时间戳来验证过期

实现思路,先设置失效时间,将失效时间转为时间戳,使用DESEncrypt进行加密,将加密后的字符返回

验证的时候传入加密后的密文,先用DESEncrypt进行解密,解密后将时间戳转换为时间格式和当前时间比较,如果小于当前时间则表示已过期

 

新建DESEncrypt类

 public class DESEncrypt
    {
        /// <summary>
        /// DES 加密 注意:密钥必须为8位
        /// </summary>
        /// <param name="inputString">待加密字符串</param>
        /// <param name="encryptKey">密钥</param>
        /// <returns>加密后的字符串</returns>
        public static string Encrypt(string inputString, string encryptKey)
        {
            encryptKey = encryptKey.Length < 8 ? "xxxxxxxxx" : encryptKey;
            byte[] byKey = null;
            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            byKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.UTF8.GetBytes(inputString);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    return Convert.ToBase64String(ms.ToArray());
                }
            }
        }

        /// <summary>
        /// DES 解密 注意:密钥必须为8位
        /// </summary>
        /// <param name="inputString">待解密字符串</param>
        /// <param name="decryptKey">密钥</param>
        /// <returns>解密后的字符串</returns>
        public static string DesDecrypt(string inputString, string decryptKey)
        {
            decryptKey = decryptKey.Length < 8 ? "xxxxxxxxx" : decryptKey;
            byte[] byKey = null;
            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            byte[] inputByteArray = new Byte[inputString.Length];
            byKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 8));
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            inputByteArray = Convert.FromBase64String(inputString);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    return Encoding.UTF8.GetString(ms.ToArray());
                }
            }

        }
    }
View Code

EmailHelper类

 public class EmailHelper
    {
        private readonly static string SmtpServer = "smtp.qq.com";//smtp服务器
        private readonly static int SmtpServerPort = 25;
        private readonly static bool SmtpEnableSsl = false;
        private readonly static string SmtpUsername = "xxx@qq.com";//发件人邮箱地址
        private readonly static string SmtpDisplayName = "测试";//发件人昵称
        private readonly static string SmtpUserPassword = "abssdf";//授权码

        /// <summary>
        /// 发送邮件到指定收件人
        /// </summary>
        /// <param name="to">收件人地址</param>
        /// <param name="subject">主题</param>
        /// <param name="mailBody">正文内容(支持HTML)</param>
        /// <param name="copyTos">抄送地址列表</param>
        /// <returns>是否发送成功</returns>
        public static bool Send(string to, string subject, string mailBody, params string[] copyTos)
        {
            return Send(new[] { to }, subject, mailBody, copyTos, new string[] { }, MailPriority.Normal);

        }

        /// <summary>
        /// 发送邮件到指定收件人
        /// </summary>
        /// <remarks>
        ///  2013-11-18 18:55 Created By iceStone
        /// </remarks>
        /// <param name="tos">收件人地址列表</param>
        /// <param name="subject">主题</param>
        /// <param name="mailBody">正文内容(支持HTML)</param>
        /// <param name="ccs">抄送地址列表</param>
        /// <param name="bccs">密件抄送地址列表</param>
        /// <param name="priority">此邮件的优先级</param>
        /// <param name="attachments">附件列表</param>
        /// <returns>是否发送成功</returns>
        /// <exception cref="System.ArgumentNullException">attachments</exception>
        public static bool Send(string[] tos, string subject, string mailBody, string[] ccs, string[] bccs, MailPriority priority, params Attachment[] attachments)
        {
            if (attachments == null)
                throw new ArgumentNullException("attachments");
            if (tos.Length == 0)
                return false;
            //创建Email实体
            var message = new MailMessage();
            message.From = new MailAddress(SmtpUsername, SmtpDisplayName);
            message.Subject = subject;
            message.Body = mailBody;
            message.BodyEncoding = Encoding.UTF8;
            message.IsBodyHtml = true;
            message.Priority = priority;

            //插入附件
            foreach (var attachent in attachments)
            {
                message.Attachments.Add(attachent);
            }
            //插入收件人地址,抄送地址和密件抄送地址
            foreach (var to in tos.Where(t => !string.IsNullOrEmpty(t)))
            {
                message.To.Add(new MailAddress(to));
            }
            foreach (var cc in ccs.Where(c => !string.IsNullOrEmpty(c)))
            {
                message.CC.Add(new MailAddress(cc));
            }
            foreach (var bcc in bccs.Where(bc => !string.IsNullOrEmpty(bc)))
            {
                message.Bcc.Add(new MailAddress(bcc));
            }

            //创建Smtp客户端
            var client = new SmtpClient
            {
                Host = SmtpServer,
                Credentials = new NetworkCredential(SmtpUsername, SmtpUserPassword),
                DeliveryMethod = SmtpDeliveryMethod.Network,
                EnableSsl = SmtpEnableSsl,
                Port = SmtpServerPort
            };

            //发送邮件
            client.Send(message);

            return true;
        }

    }
View Code

HomeController页面

    public class HomeController : Controller
    {
        // GET: Home
        public string  Index()
        {
            //return "hello!";
            string timestamp = GetTimeStamp();
          string dncryptStr= Common.DESEncrypt.Encrypt(timestamp, "");
            string id = Guid.NewGuid().ToString();
            string emilaText= "您重置密码的连接为:http://localhost:13080/Home/RestPwd?id=" + id.ToString()+"&timeout="+dncryptStr;
           bool flag= Common.EmailHelper.Send("565770751@qq.com", "重置密码", emilaText);
            return flag ? "发送成功" : "发送失败";
        }
       

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="id"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public string RestPwd(string id, string timeout)
        {

            string timestamp =  Common.DESEncrypt.DesDecrypt(timeout,"");
            bool flag = Timespan(timestamp);
            return flag ? "未过期" : "已过期";
           
        }

       

        
       


       /// <summary>
       /// 将当前时间转换为时间戳
       /// </summary>
       /// <returns></returns>
        public  string GetTimeStamp()
        {
            //设置有效期为20分钟
            DateTime time = DateTime.Now.AddMinutes(20);
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
            long t = (time.Ticks - startTime.Ticks) / 10000;   //除10000调整为13位      
            return t.ToString();
        }
       
        /// <summary>
        /// 传入时间戳判断是否过期
        /// </summary>
        /// <param name="timeStamp">时间戳串</param>
        /// <returns></returns>
        private bool Timespan(string timeStamp)
        {
            DateTime nowTime=DateTime.Now;
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000");
            TimeSpan toNow = new TimeSpan(lTime);
            dtStart= dtStart.Add(toNow);
            return (dtStart-nowTime).Seconds > 0 ? true : false;
        }
    }

 

posted @ 2019-10-12 17:16  dongminglong  阅读(542)  评论(0编辑  收藏  举报