Esempio n. 1
0
 public void EncryptAndDecryptTest()
 {
     DesHelper des = new DesHelper();
     Assert.Equal(des.Decrypt(des.Encrypt("admin")), "admin");
     des = new DesHelper(true);
     Assert.Equal(des.Decrypt(des.Encrypt("admin")), "admin");
 }
Esempio n. 2
0
 public void DesErrorTest()
 {
     Should.Throw <Exception>(() => { DesHelper.Encrypt("DES加密", "123", "12345678"); });
     Should.Throw <Exception>(() => { DesHelper.Encrypt("DES加密", "12345678", "123"); });
     Should.Throw <Exception>(() => { DesHelper.Decrypt("lkXACZz387lOk9xiKpCOeg==", "123", "12345678"); });
     Should.Throw <Exception>(() => { DesHelper.Decrypt("lkXACZz387lOk9xiKpCOeg==", "12345678", "123"); });
 }
Esempio n. 3
0
        /// <summary>
        /// 重写身份验证方法
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected override bool IsAuthorized(HttpActionContext httpContext)
        {
            try
            {
                string token = string.Empty;
                if (httpContext.Request.Headers.Contains(HttpHeaderNames.OSharpAuthenticationToken))
                {
                    token = httpContext.Request.Headers.GetValues(HttpHeaderNames.OSharpAuthenticationToken).FirstOrDefault();// 从客户端请求中获取 token
                }
                else
                {
                    HttpContextBase context = (HttpContextBase)httpContext.Request.Properties["MS_HttpContext"]; //获取传统context
                    HttpRequestBase request = context.Request;                                                   //定义传统request对象
                    token = request.Form[HttpHeaderNames.OSharpAuthenticationToken] ?? "";
                }

                var      strAuth = DesHelper.Decrypt(token, Constants.BodeAuthDesKey);
                Operator user    = strAuth.FromJsonString <Operator>() ?? new Operator();
                OSharpContext.Current.SetOperator(user);

                if (AllowAnonymous)
                {
                    return(true);
                }
                return(int.Parse(user.UserId) > 0 && user.ValidatePeriod > DateTime.Now);
            }
            catch
            {
                OSharpContext.Current.SetOperator(new Operator());
                return(AllowAnonymous);
            }
        }
        protected override bool IsAuthorized(HttpActionContext httpContext)
        {
            try
            {
                var    scope       = httpContext.Request.GetDependencyScope();
                var    userService = scope.GetService(typeof(IRepository <UserInfo, int>)) as IRepository <UserInfo, int>;
                string token       = httpContext.Request.Headers.GetValues(HttpHeaderNames.OSharpAuthenticationToken).FirstOrDefault();

                var      strAuth = DesHelper.Decrypt(token, OSharp.Core.Constants.BodeAuthDesKey);
                Operator user    = strAuth.FromJsonString <Operator>() ?? new Operator();

                int userId        = int.Parse(user.UserId);
                var onlineToken   = userService.GetByKey(userId).Token;
                var onlineStrAuth = DesHelper.Decrypt(onlineToken, OSharp.Core.Constants.BodeAuthDesKey);

                if (onlineToken != token)
                {
                    return(false);
                }
                return(true);
            }
            catch (Exception)
            {
                return(AllowAnonymous);
            }
        }
Esempio n. 5
0
        /// <summary>
        /// 重写身份验证方法
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected override bool IsAuthorized(HttpActionContext httpContext)
        {
            try
            {
                string token = httpContext.Request.Headers.GetValues(HttpHeaderNames.OSharpAuthenticationToken).FirstOrDefault();
                if (token.IsNullOrWhiteSpace())
                {
                    return(AllowAnonymous);
                }

                var      strAuth = DesHelper.Decrypt(token, Constants.BodeAuthDesKey);
                Operator user    = strAuth.FromJsonString <Operator>() ?? new Operator();
                OSharpContext.Current.SetOperator(user);

                if (AllowAnonymous)
                {
                    return(true);
                }
                return(int.Parse(user.UserId) > 0 && user.ValidatePeriod > DateTime.Now);
            }
            catch
            {
                return(AllowAnonymous);
            }
        }
Esempio n. 6
0
        public void DesDecrypt()
        {
            var key  = "12345678";
            var iv   = "12345678";
            var data = DesHelper.Decrypt("lkXACZz387lOk9xiKpCOeg==", key, iv);

            data.ShouldBe("DES加密");
        }
Esempio n. 7
0
        public void EncryptAndDecryptTest()
        {
            DesHelper des = new DesHelper();

            Assert.AreEqual(des.Decrypt(des.Encrypt("admin")), "admin");
            des = new DesHelper(true);
            Assert.AreEqual(des.Decrypt(des.Encrypt("admin")), "admin");
        }
Esempio n. 8
0
        public void TestDES()
        {
            string key          = "Fa410cOr=+)^*()d";
            string data         = "Copyright @ Kane Leung 2020. All rights reserved.";
            var    des          = new DesHelper();
            var    encryptValue = des.Encrypt(data, key);
            var    decryptValue = des.Decrypt(encryptValue, key);

            Assert.AreEqual(data, decryptValue);
        }
        public void TestEncryptAndDecrypt()
        {
            var key     = Encoding.ASCII.GetBytes("12345678");
            var content = Encoding.ASCII.GetBytes("12345678");

            var cipheredData    = DesHelper.Encrypt(content, key);
            var nonCipheredData = DesHelper.Decrypt(cipheredData, key);

            Assert.IsTrue(nonCipheredData.SequenceEqual(content));
        }
Esempio n. 10
0
        /// <summary>
        /// 对称加密测试
        /// </summary>
        public static void DesTest()
        {
            string key     = @"aksjwj2w";
            string iv      = @"jahajhgj";
            string data    = @"Hello 中国,这是一段很神奇的代码";
            string encData = DesHelper.Encrypt(data, key, iv);
            string decData = DesHelper.Decrypt(encData, key, iv);

            Console.WriteLine("原文:{0}", data);
            Console.WriteLine("密文:{0}", encData);
            Console.WriteLine("解密:{0}", decData);
        }
        public ActionResult GetNewByTicket(string ticket, string clientId)
        {
            if (!VerifyNewParam("ticket", clientId, _signCheckService))
            {
                return(ErrMsg());
            }

            var weChatConfig = GetWechatConfig();
            var t            = EncryptionHelper.DecodeFrom64(ticket);
            var key          = DesHelper.Decrypt(t, CommonService.GetSysConfig("EncryptKey", ""));

            var openid = key.Split('|')[0];

            var strToken = GetToken();
            var userInfo = MailListApi.GetMember(strToken, openid);

            // var userInfo = UserApi.Info(weChatConfig.WeixinAppId, weChatConfig.WeixinCorpSecret, openid);


            //var userView = GetUserInfo((AddressBookMemberView)new AddressBookMemberView().ConvertAPIModel(userInfo));


            if (userInfo != null)
            {
                var strJson = Newtonsoft.Json.JsonConvert.SerializeObject(new
                {
                    message = "",
                    success = true,
                    item    = new
                    {
                        userid = userInfo.userid,
                        name   = userInfo.name,
                        avatar = userInfo.avatar,
                        status = userInfo.status,
                        email  = userInfo.email
                    }
                });

                return(Content(strJson, "application/json"));
            }
            else
            {
                log.Error("用户不存在:ticket:{0} userid:{1}", ticket, openid);

                return(Json(new
                {
                    message = "用户不存在!",
                    success = false
                }, JsonRequestBehavior.AllowGet));
            }
        }
Esempio n. 12
0
        /// <summary>
        /// 验证请求内容是否可以解密(des)
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string CheckRequestBodyForDecrypt(string requestBody)
        {
            var body = string.Empty;

            try
            {
                body = DesHelper.Decrypt(requestBody, TongChengConfig.UserKey);
            }
            catch
            {
                body = "";
            }
            return(body);
        }
Esempio n. 13
0
        public TicketInfo UnProtect(string token)
        {
            token.CheckNotNullOrEmpty(nameof(token));

            var salt = DesHelper.Encrypt(_salt, _desKey);

            if (!token.EndsWith(salt))
            {
                return(null);
            }

            var json = token.Substring(0, token.Length - salt.Length);

            return(JsonHelper.FromJson <TicketInfo>(DesHelper.Decrypt(json, _desKey)));
        }
Esempio n. 14
0
        public void DecryptTest()
        {
            string key = "12345678";
            string actual = "TMR29YtnGPI=";
            DesHelper des = new DesHelper(Encoding.UTF8.GetBytes(key));
            Assert.Equal(des.Decrypt(actual), "admin");
            Assert.Equal(DesHelper.Decrypt(actual, key), "admin");


            key = "!@#$%^&*QWERTYUI12345678";
            actual = "Qp4r67VJ8Z0=";
            des = new DesHelper(Encoding.UTF8.GetBytes(key));
            Assert.Equal(des.Decrypt(actual), "admin");
            Assert.Equal(DesHelper.Decrypt(actual, key), "admin");
        }
Esempio n. 15
0
        public void DecryptTest()
        {
            string    key    = "12345678";
            string    actual = "TMR29YtnGPI=";
            DesHelper des    = new DesHelper(Encoding.UTF8.GetBytes(key));

            Assert.AreEqual(des.Decrypt(actual), "admin");
            Assert.AreEqual(DesHelper.Decrypt(actual, key), "admin");


            key    = "!@#$%^&*QWERTYUI12345678";
            actual = "Qp4r67VJ8Z0=";
            des    = new DesHelper(Encoding.UTF8.GetBytes(key));
            Assert.AreEqual(des.Decrypt(actual), "admin");
            Assert.AreEqual(DesHelper.Decrypt(actual, key), "admin");
        }
Esempio n. 16
0
        public static List <UserInfo> GetUsers()
        {
            List <UserInfo> list     = new List <UserInfo>();
            string          userData = string.Empty;

            using (StreamReader sr = new StreamReader(userDataFile))
            {
                userData = sr.ReadToEnd();
            }
            //解密
            if (userData != "")
            {
                userData = DesHelper.Decrypt(userData, Ticket12306.Resx.Strings.DesKey, Ticket12306.Resx.Strings.DesIV);
                list     = JsonHelper.FromJson <List <UserInfo> >(userData);
            }
            return(list);
        }
Esempio n. 17
0
        /// <summary>
        /// 根据ticket获得员工信息
        /// </summary>
        /// <param name="ticket"></param>
        /// <returns></returns>
        public ActionResult GetByTicket(string ticket)
        {
            if (!VerifyParam("ticket"))
            {
                return(ErrMsg());
            }

            var weChatConfig = GetWechatConfig();
            var t            = EncryptionHelper.DecodeFrom64(ticket);
            var key          = DesHelper.Decrypt(t, CommonService.GetSysConfig("EncryptKey", ""));

            var openid = key.Split('|')[0];

            var userInfo = UserApi.Info(weChatConfig.WeixinAppId, weChatConfig.WeixinCorpSecret, openid);

            if (userInfo.errcode == Weixin.ReturnCode.请求成功)
            {
                var UserView = _BaseService.GetList <WechatMPUserView>(0, a => a.OpenId == userInfo.openid, null).FirstOrDefault();
                if (UserView == null)
                {
                    return(ErrMsg("simuid 没有找到!"));
                }

                return(Json(new
                {
                    message = "",
                    nickname = userInfo.nickname,
                    realName = "",
                    simuid = UserView.Id,
                    avatar = userInfo.headimgurl,
                    success = true,
                    hrcode = ""
                }, JsonRequestBehavior.AllowGet));
            }
            else
            {
                return(Json(new
                {
                    message = userInfo.errmsg,
                    success = false
                }, JsonRequestBehavior.AllowGet));
            }
        }
        public EnterpriseUser LoginForSession()
        {
            var userInfo = HttpContext.Current.Session[SessionKey.UserInfo];

            if (userInfo != null)
            {
                return((EnterpriseUser)userInfo);
            }
            HttpCookie cookie = HttpContext.Current.Request.Cookies[SessionKey.SaleUserLoginCookie];

            if (cookie != null && !string.IsNullOrEmpty(cookie.Value))
            {
                string   des    = DesHelper.Decrypt(cookie.Value, SessionKey.ManagerUserLoginCookieKey);
                string[] tmpArr = des.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                if (tmpArr.Length == 2)
                {
                    string userName = tmpArr[0];
                    string passWord = tmpArr[1];
                    //当前景区下未停用的售票员
                    var model = Get(userName, passWord);
                    if (model != null)
                    {
                        //var tbl_Scenic = Repository.First<Tbl_Scenic>(a => a.ScenicId == model.ScenicId);
                        //UserInfoDTO dto = new UserInfoDTO(model, (int)SystemType.Sale, tbl_Scenic.ScenicName);
                        //model.LastLoginTime = DateTime.Now;
                        //Repository.Update(model);
                        var dto = new EnterpriseUser
                        {
                            UserId   = model.EnterpriseUserId,
                            UserName = model.UserName,
                            RealName = model.RealName,
                            ScenicId = model.ScenicId
                        };
                        //设置Session
                        HttpContext.Current.Session[SessionKey.UserInfo] = dto;
                        return(dto);
                    }
                }
            }
            return(null);
        }
Esempio n. 19
0
        protected override bool Authorize(string authenticationToken)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(authenticationToken))
                {
                    var      strAuth = DesHelper.Decrypt(authenticationToken, AuthDesKey);
                    Operator user    = strAuth.FromJsonString <Operator>() ?? new Operator();

                    if (!user.UserName.IsNullOrWhiteSpace() && _onlineUserStore.IsOnline(user.UserName))
                    {
                        OSharpContext.Current.SetOperator(user);
                        _onlineUserStore.ResetLastOperationTime(user.UserName);
                        return(true);
                    }
                }
                return(false);
            }
            catch
            {
                return(false);
            }
        }
Esempio n. 20
0
        /// <summary>
        /// 根据ticket获得员工信息
        /// </summary>
        /// <param name="ticket"></param>
        /// <returns></returns>
        public ActionResult GetByTicket(string ticket)
        {
            if (!VerifyParam("ticket"))
            {
                return(ErrMsg());
            }

            var weChatConfig = GetWechatConfig();
            var t            = EncryptionHelper.DecodeFrom64(ticket);
            var key          = DesHelper.Decrypt(t, CommonService.GetSysConfig("EncryptKey", ""));

            var openid = key.Split('|')[0];

            var userInfo = ((IAddressBookService)_BaseService).GetMemberByUserId(openid);

            // var userInfo = UserApi.Info(weChatConfig.WeixinAppId, weChatConfig.WeixinCorpSecret, openid);


            var userView = GetUserInfo((AddressBookMemberView) new AddressBookMemberView().ConvertAPIModel(userInfo));


            if (userInfo != null)
            {
                var strJson = Newtonsoft.Json.JsonConvert.SerializeObject(new
                {
                    message = "",
                    success = true,
                    item    = userView
                });

                return(Content(strJson, "application/json"));

                //return Json(new
                //{
                //    message = "",

                //    success = true,
                //    item= userView
                //    //item = new
                //    //{
                //    //    id = userInfo.Id,
                //    //    teamId = userInfo.AccountManageId,
                //    //    userId = userInfo.UserId,
                //    //    name = userInfo.UserName,
                //    //    position = userInfo.Position,
                //    //    mobile = userInfo.Mobile,
                //    //    gender = userInfo.Gender,
                //    //    avatar = userInfo.Avatar,
                //    //    extend1 = "",
                //    //    // telephone = userInfo.te,
                //    //    email = userInfo.Email,
                //    //    wxid = userInfo.WeiXinId,
                //    //    hrcode = userInfo.EmployeeNo,
                //    //    status = userInfo.Status,
                //    //    createTime = userInfo.CreateTime
                //    //},

                //}, JsonRequestBehavior.AllowGet);
            }
            else
            {
                log.Error("用户不存在:ticket:{0} userid:{1}", ticket, openid);

                return(Json(new
                {
                    message = "用户不存在!",
                    success = false
                }, JsonRequestBehavior.AllowGet));
            }
        }
Esempio n. 21
0
        public static string Run(string body, double total_fee, string authCode, string outTradeNo)
        {
            // 1固定参数
            PayData postmap = new PayData();    // 请求参数的map

            postmap.Put("rancode", Helper.GenerateRandom(5));
            postmap.Put("reqtime", DateTime.Now.ToString("yyyyMMddHHmmss"));
            postmap.Put("snNo", PayConfig.SnNo);
            //postmap.Put("merchantNo", PayConfig.MerchantNo);

            postmap.Put("terminalType", "OTHER");
            postmap.Put("outTradeNo ", outTradeNo);//外部接入系统订单号
            postmap.Put("amount ", total_fee);
            postmap.Put("authCode ", authCode);
            postmap.Put("casherNo ", "T001");//收银员编号
            postmap.Put("description", "OTHER");
            postmap.Put("orderTime", DateTime.Now.ToString("yyyyMMddHHmmss"));
            postmap.Put("systemCode", PayConfig.SystemCode);
            postmap.Put("version", PayConfig.Version);



            byte[] byteArray = System.Text.Encoding.Default.GetBytes(PayConfig.Key);


            byte[] bcdbyte = str2Bcd("B95EB858BAA4170731EDBB0D7661B39A34");
            byte[] keybyte = str2Bcd("1111222233334444");
            byte   ssss    = 0;

            byte[] ggg     = new byte[] { ssss };
            byte   borByte = 0;

            for (int i = 0; i < bcdbyte.Length - 1; i++)
            {
                if (i == 0)
                {
                    borByte = bcdbyte[i];
                }
                borByte ^= bcdbyte[i + 1];
            }
            byte[]        bor = new byte[] { borByte };
            StringBuilder sb  = new StringBuilder(bor.Length);
            String        sTemp;

            for (int i = 0; i < bor.Length; i++)
            {
                sTemp = String.Format("{0:X}", 0xFF & bor[i]);
                //sTemp = Integer.toHexString(0xFF & bor[i]);
                if (sTemp.Count() < 2)
                {
                    sb.Append(0);
                }
                sb.Append(sTemp.ToUpper());
            }
            var str = sb.ToString();

            var key = DesHelper.Decrypt(PayConfig.Key, str);



            // 2签名
            string sign = Helper.MakeSign(postmap.ToUrl(), key);

            postmap.Put("sign", sign);

            // 3请求、响应
            string rspStr = HttpService.Post(postmap.ToJson(), PayConfig.WebSite + "/merchantpay/trade/microorder?" + postmap.ToUrl());



            var response = JsonSerializeHelper.ToObject <ActivationResponse>(rspStr);

            if (response.ReturnCode == ResultCode.Success)
            {
                var data = JsonSerializeHelper.ToObject <ActivationDataResponse>(response.Data);
                //var key = DesHelper.Decrypt(data.Key, PayConfig.DefaultKey);
            }
            return(rspStr);
        }
        private string GetOpenId(ActionExecutingContext filterContext)
        {
            //var objLoginInfo = Session["UserInfo"] as WechatUser;

            //LogManager.GetLogger(this.GetType()).Debug("objLoginInfo : " + (objLoginInfo == null?"NULL":objLoginInfo.wechatUserID));
            ////判断用户是否为空
            //if (objLoginInfo == null)
            {
                //LogManager.GetLogger(this.GetType()).Debug("objLoginInfo is null");
                if (HttpContext.Request.IsAuthenticated)
                {
                    LogManager.GetLogger(this.GetType()).Debug("HttpContext.Request.IsAuthenticated");
                    if (Request.UserAgent.IndexOf("MicroMessenger") >= 0)
                    {
                        LogManager.GetLogger(this.GetType()).Debug("WeChat Browser");
                        var windowsIdentity = User.Identity;
                        if (windowsIdentity != null)
                        {
                            return(windowsIdentity.Name);
                        }
                        else
                        {
                            return(string.Empty);
                        }
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(Request["Ticket"]))
                    {
                        var ticket = Request["Ticket"];
                        Session["Ticket"] = ticket;



                        string enTicket = EncryptionHelper.DecodeFrom64(ticket);
                        enTicket = DesHelper.Decrypt(enTicket, WebConfigurationManager.AppSettings["EncryptKey"]);

                        var openid = enTicket.Split('|')[0];

                        //登录
                        ClaimsIdentity claimsIdentity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
                        claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, openid, "http://www.w3.org/2001/XMLSchema#string"));
                        claimsIdentity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, openid, "http://www.w3.org/2001/XMLSchema#string"));
                        claimsIdentity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"));

                        HttpContext.GetOwinContext().Authentication.SignIn(new AuthenticationProperties()
                        {
                            IsPersistent = false
                        }, claimsIdentity);

                        //
                    }
                    else if (Session["Ticket"] == null)
                    {
                        var strUrl = WebConfigurationManager.AppSettings["OAuthUrl"];

                        filterContext.Result = new RedirectResult(strUrl + Server.UrlEncode(EncryptionHelper.ConvertBase64(Request.Url.ToString())));
                    }



                    //    LogManager.GetLogger(this.GetType()).Debug("SessionId:" + Session.SessionID);
                    //    Session["ReturnUrlMP"] = Request.Url.ToString();

                    //    string strRet = WebConfigurationManager.AppSettings["UserBackUrlMP"];
                    //    // string AppId = Request["AppId"];


                    //    string strwechatid = Request["wechatid"];

                    //    string strBackUrl = string.Format("{0}?wechatid={1}", strRet, strwechatid);

                    //    LogManager.GetLogger(this.GetType()).Debug("UrlStart:" + strBackUrl);

                    //   // var weChatConfig = WeChatCommonService.GetWeChatConfigByID(int.Parse(strwechatid));


                    //    LogManager.GetLogger(this.GetType()).Debug("UrlStart");
                    //    string strUrl = OAuthApi.GetAuthorizeUrl("wx2a3f5167603c5caf", strBackUrl, "About", Innocellence.Weixin.MP.OAuthScope.snsapi_base);
                    //    LogManager.GetLogger(this.GetType()).Debug(strUrl);

                    //    if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                    //    {
                    //        AjaxResult<int> result = new AjaxResult<int>();
                    //        result.Message = new JsonMessage((int)HttpStatusCode.Unauthorized, strUrl);
                    //        filterContext.Result = Json(result, JsonRequestBehavior.AllowGet);

                    //    }
                    //    else
                    //    {
                    //        LogManager.GetLogger(this.GetType()).Debug("filterContext.Result = new RedirectResult(strUrl)");
                    //        filterContext.Result = new RedirectResult(strUrl);
                    //    }
                    //    return string.Empty;
                }
            }
            return(string.Empty);
        }
Esempio n. 23
0
 public static string DecryptDES(this string value)
 {
     return(DesHelper.Decrypt(value, null));
 }