Ejemplo 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");
 }
Ejemplo 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"); });
 }
Ejemplo n.º 3
0
        /// <summary>
        /// 消费通知接口
        /// </summary>
        /// <param name="noticeOrderConsumedRequest"></param>
        /// <returns></returns>
        public static bool Run(ConsumeNoticeRequest consumeNoticeRequest)
        {
            string requestBody = JsonSerializeHelper.ToJson(consumeNoticeRequest);

            requestBody = DesHelper.Encrypt(requestBody, TongChengConfig.UserKey);
            var         sign    = Helper.MakeSign("ConsumeNotice", requestBody);
            RequestData request = new RequestData
            {
                RequestHead = new RequestHead
                {
                    user_id   = TongChengConfig.UserId,
                    Method    = "ConsumeNotice",
                    Timestamp = Helper.GenerateTimeStamp(),
                    Version   = TongChengConfig.Version,
                    Sign      = sign
                },
                RequestBody = requestBody
            };
            string body = JsonSerializeHelper.ToJson(request);

            body = Helper.Base64Encode(body);
            var contnt = HttpService.Post(body, TongChengConfig.Website);

            if (!string.IsNullOrEmpty(contnt))
            {
                contnt = Helper.Base64Decode(contnt);
                var response = JsonSerializeHelper.ToObject <ResponseData>(contnt);
                if (response != null && response.responseHead.res_code == ResultCode.Success)
                {
                    return(true);
                }
            }
            return(false);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 跳转通过oauth获取ticket, 主要逻辑以及跳转在WeChatBaseController中完成
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="uri"></param>
        /// <returns></returns>
        public ActionResult GetTicketExt(int appId, string uri)
        {
            string UserId = ViewBag.WeChatUserID;

            if (string.IsNullOrEmpty(UserId))
            {
                return(Content("用户ID为空,请确定您已经关注企业号并且您的状态是在职!"));
            }

            log.Debug("API GetTicket Start  UserID:{0} Uri:{1} URL:{2}", UserId, uri, Request.Url);

            string enTicket = EncryptionHelper.ConvertBase64(DesHelper.Encrypt(UserId + "|" + DateTime.UtcNow.ToFileTime().ToString(), CommonService.GetSysConfig("EncryptKey", "")));

            string backUrl;//= EncryptionHelper.DecodeFrom64(uri) + enTicket;

            if (uri.IndexOf("_") >= 0)
            {
                var u  = uri.Split('_');
                var u1 = EncryptionHelper.DecodeFrom64(u[0]);

                backUrl = u1;
                // backUrl = (u1.IndexOf("?") >= 0 ? "&" : "?") + EncryptionHelper.DecodeFrom64(u[1]) + enTicket;
            }
            else
            {
                backUrl = EncryptionHelper.DecodeFrom64(uri);
            }

            string strRet = "";

            if (backUrl.IndexOf("ticket=") > 0)
            {
                strRet = backUrl + enTicket;
            }
            else
            {
                strRet = backUrl + (backUrl.IndexOf("?") >= 0 ? "&" : "?") + "ticket=" + enTicket;
            }

            var strToken = GetTokenExt();
            var userInfo = MailListApi.GetMember(strToken, UserId);

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

            strRet = strRet + "&extend1=";

            if (userInfo != null)
            {
                strRet = strRet + userInfo;
            }
            else
            {
                log.Error("用户不存在: userid:{0}", UserId);
            }

            log.Debug("API GetTicket End  backUrl:{0}", strRet);

            return(Redirect(strRet));
        }
Ejemplo n.º 5
0
        public void DesEncryptTest()
        {
            var key  = "12345678";
            var iv   = "12345678";
            var data = DesHelper.Encrypt("DES加密", key, iv);

            data.ShouldBe("lkXACZz387lOk9xiKpCOeg==");
        }
Ejemplo n.º 6
0
        public string Protect(TicketInfo ticket)
        {
            ticket.CheckNotNull(nameof(ticket));

            var json = JsonHelper.ToJson(ticket);

            return(DesHelper.Encrypt(json, _desKey) + DesHelper.Encrypt(_salt, _desKey));
        }
Ejemplo 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");
        }
Ejemplo 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);
        }
Ejemplo n.º 9
0
        private static void Save(List <UserInfo> list)
        {
            string listStr = JsonHelper.ToJson(list);
            string ret     = DesHelper.Encrypt(listStr, Ticket12306.Resx.Strings.DesKey, Ticket12306.Resx.Strings.DesIV);

            using (StreamWriter sr = new StreamWriter(userDataFile))
            {
                sr.Write(ret);
            }
        }
Ejemplo n.º 10
0
        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));
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public TResult <EnterpriseUser> Login(EnterpriseUserLoginModel UserModel)
        {
            var result = new TResult <EnterpriseUser>();

            if (string.IsNullOrEmpty(UserModel.UserName) || string.IsNullOrEmpty(UserModel.PassWord))
            {
                return(result.FailureResult(null, "用户名和密码不能为空!"));
            }

            if (string.IsNullOrEmpty(UserModel.Code))
            {
                return(result.FailureResult(null, "请输入验证码!"));
            }
            var code = HttpContext.Current.Request.Cookies[SessionKey.ManagerUserLoginCode];

            if (code == null || (string.IsNullOrEmpty(code.Value)))
            {
                return(result.FailureResult(null, "验证码已过期,请重新输入验证码!"));
            }
            if (!String.Equals(code.Value, UserModel.Code.Trim(), StringComparison.CurrentCultureIgnoreCase))
            {
                return(result.FailureResult(null, "请输入正确的验证码!"));
            }
            var password = Md5HashHelper.HashPassword(UserModel.PassWord);
            //当前景区下未停用的售票员
            var model = Get(UserModel.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 userInfo = new EnterpriseUser
                {
                    UserId   = model.EnterpriseUserId,
                    UserName = model.UserName,
                    RealName = model.RealName,
                    ScenicId = model.ScenicId
                };
                //设置Session
                HttpContext.Current.Session[SessionKey.UserInfo] = userInfo;

                //设置登录信息cookie 1天有效
                HttpCookie hc = new HttpCookie(SessionKey.SaleUserLoginCookie);
                hc.Value = DesHelper.Encrypt(model.UserName + "|" + model.PassWord, SessionKey.ManagerUserLoginCookieKey);
                //设置cookie信息在第二天凌晨过期
                //(用户每天都需要输入密码登录一次,而且不会出现,在某一天中间某一刻时间,突然cookie过期)
                hc.Expires = DateTime.Now.AddDays(1);
                HttpContext.Current.Response.Cookies.Add(hc);

                return(result.SuccessResult(userInfo, "登录成功"));
            }
            return(result.FailureResult(null, "用户名或密码错误"));
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 获取当前登陆用户ID
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public string GetCurrentUserId(HttpRequest request)
        {
            var cookie = request.Cookies[AuthCookieConfig.AUTH_COOKIE_NAME];

            if (cookie == null)
            {
                throw new Exception("auth cookie is null");
            }
            //解密
            return(DesHelper.Encrypt(cookie.Value, AuthCookieConfig.AUTH_COOKIE_KEY));
        }
Ejemplo n.º 13
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);
        }
Ejemplo n.º 14
0
        public JsonResult Login(string username, string password, bool autoLogin = false)
        {
            if (string.IsNullOrEmpty(username))
            {
                return(Error("用户名不能为空。"));
            }

            if (string.IsNullOrEmpty(password))
            {
                return(Error("密码不能为空。"));
            }

            var user = _userService.GetByNameAsync(username.Trim());

            if (user == null)
            {
                return(Error("用户不存在。"));
            }

            if (Md5Helper.Encrypt(password) != user.Password.Trim())
            {
                return(Error("密码错误。"));
            }

            var loginUser = new LoginUser
            {
                UserId   = user.Id,
                UserName = user.UserName,
                NickName = user.NickName,
                Avatar   = user.Avatar,
            };

            CookieData.CurrentUser = loginUser;
            Session[WebAppSettings.SessionName] = loginUser;

            if (autoLogin)
            {
                string encryptStr = DesHelper.Encrypt(user.Id.ToString(), WebAppSettings.DesEncryptKey);
                CookieHelper.Set(WebAppSettings.CookieName, encryptStr, DateTime.Now.AddDays(3));
            }

            LogService.Write(new Instart.Models.Log
            {
                Title    = $"{user.UserName}登录系统",
                UserId   = user.Id,
                UserName = user.UserName,
                Type     = Instart.Models.Enums.EnumOperType.Other,
            });

            return(Success());
        }
Ejemplo n.º 15
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)));
        }
Ejemplo n.º 16
0
        /// <summary>
        /// 成功返回
        /// </summary>
        /// <param name="code"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static string SuccessResult <T>(T responseBody)
        {
            var body = JsonSerializeHelper.ToJson(responseBody);

            body = DesHelper.Encrypt(body, TongChengConfig.UserKey);
            var responseData = new ResponseData
            {
                responseHead = new ResponseHead
                {
                    res_code  = ResultCode.Success,
                    res_msg   = "成功",
                    timestamp = Helper.GenerateTimeStamp()
                },
                responseBody = body
            };
            var json = JsonSerializeHelper.ToJson(responseData);

            return(Helper.Base64Encode(json));
        }
Ejemplo n.º 17
0
        /// <summary>
        /// 跳转通过oauth获取ticket, 主要逻辑以及跳转在WeChatBaseController中完成
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="uri"></param>
        /// <returns></returns>
        public ActionResult GetTicket(int appId, string uri)
        {
            string UserId = ViewBag.WeChatUserID;

            if (string.IsNullOrEmpty(UserId))
            {
                return(Content("用户ID为空,请确定您已经关注企业号并且您的状态是在职!"));
            }

            log.Debug("API GetTicket Start  UserID:{0} Uri:{1} URL:{2}", UserId, uri, Request.Url);

            string enTicket = EncryptionHelper.ConvertBase64(DesHelper.Encrypt(UserId + "|" + DateTime.UtcNow.ToFileTime().ToString(), CommonService.GetSysConfig("EncryptKey", "")));

            string backUrl; //= EncryptionHelper.DecodeFrom64(uri) + enTicket;

            if (uri.IndexOf("_") >= 0)
            {
                var u  = uri.Split('_');
                var u1 = EncryptionHelper.DecodeFrom64(u[0]);

                backUrl = u1;
                // backUrl = (u1.IndexOf("?") >= 0 ? "&" : "?") + EncryptionHelper.DecodeFrom64(u[1]) + enTicket;
            }
            else
            {
                backUrl = EncryptionHelper.DecodeFrom64(uri);
            }

            string strRet = "";

            if (backUrl.IndexOf("ticket=") > 0)
            {
                strRet = backUrl + Server.UrlEncode(enTicket);
            }
            else
            {
                strRet = backUrl + (backUrl.IndexOf("?") >= 0 ? "&" : "?") + "ticket=" + Server.UrlEncode(enTicket);
            }

            log.Debug("API GetTicket End  backUrl:{0}", strRet);

            return(Redirect(strRet));
        }
Ejemplo n.º 18
0
        public void EncryptTest()
        {
            string key = "12345678";
            string actual = "TMR29YtnGPI=";
            DesHelper des = new DesHelper(Encoding.UTF8.GetBytes(key));
            Assert.Equal(des.Encrypt("admin"), actual);
            Assert.Equal(DesHelper.Encrypt("admin", key), actual);

            //弱密钥
            key = "123456781234567812345678";
            des = new DesHelper(Encoding.UTF8.GetBytes(key));
            Assert.Throws<CryptographicException>(() => des.Encrypt("admin"));

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

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

            //弱密钥
            key = "123456781234567812345678";
            des = new DesHelper(Encoding.UTF8.GetBytes(key));
            ExceptionAssert.IsException <CryptographicException>(() => des.Encrypt("admin"));

            key    = "!@#$%^&*QWERTYUI12345678";
            actual = "Qp4r67VJ8Z0=";
            des    = new DesHelper(Encoding.UTF8.GetBytes(key));
            Assert.AreEqual(des.Encrypt("admin"), actual);
            Assert.AreEqual(DesHelper.Encrypt("admin", key), actual);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// 重置用户Token有效期
        /// </summary>
        /// <param name="user">用户</param>
        /// <param name="loginDevice">登录设备</param>
        /// <param name="clientVersion">客户端版本</param>
        /// <returns></returns>
        public async Task <OperationResult> ResetToken(UserInfo user, LoginDevice loginDevice, string clientVersion)
        {
            Operator oper = new Operator()
            {
                UserId         = user.Id.ToString(),
                UserName       = user.SysUser.UserName,
                LoginDevice    = loginDevice,
                PhoneNo        = user.SysUser.PhoneNumber,
                ClientVersion  = clientVersion,
                ValidatePeriod = DateTime.Now.AddDays(30),//默认30天有效期
                UserDatas      = new Dictionary <string, object>()
            };
            string strAuth = oper.ToJsonString();

            user.Token = DesHelper.Encrypt(strAuth, OSharp.Core.Constants.BodeAuthDesKey);

            await UserInfoRepo.UpdateAsync(user);

            return(new OperationResult(OperationResultType.Success, "重置成功", user.Token));
        }
Ejemplo n.º 21
0
        /// <summary>
        /// 重置用户Token有效期
        /// </summary>
        /// <param name="user">用户</param>
        /// <param name="loginDevice">登录设备</param>
        /// <param name="clientVersion">客户端版本</param>
        /// <returns></returns>
        public async Task <OperationResult> ResetToken(UserInfo user, LoginDevice loginDevice, string clientVersion)
        {
            Operator oper = new Operator()
            {
                UserId         = user.Id.ToString(),
                UserName       = user.SysUser.UserName,
                LoginDevice    = loginDevice,
                PhoneNo        = user.SysUser.PhoneNumber,
                ClientVersion  = clientVersion,
                ValidatePeriod = DateTime.Now.AddDays(30)//默认30天有效期
            };
            string authDesKey = "bodeauth";
            string strAuth    = oper.ToJsonString();

            user.Token = DesHelper.Encrypt(strAuth, authDesKey);

            await UserInfoRepo.UpdateAsync(user);

            return(new OperationResult(OperationResultType.Success, "重置成功"));
        }
Ejemplo n.º 22
0
        /// <summary>
        /// 跳转通过oauth获取ticket, 主要逻辑以及跳转在WeChatBaseController中完成
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="uri"></param>
        /// <returns></returns>
        public ActionResult GetTicket(int appId, string uri)
        {
            string UserId = ViewBag.WeChatUserID;



            string enTicket = EncryptionHelper.ConvertBase64(DesHelper.Encrypt(UserId + "|" + DateTime.UtcNow.ToFileTime().ToString(), CommonService.GetSysConfig("EncryptKey", "901212345678901234567890")));

            string backUrl = "";

            if (uri.IndexOf("_") >= 0)
            {
                var u  = uri.Split('_');
                var u1 = EncryptionHelper.DecodeFrom64(u[0]);

                backUrl = u1;
                // backUrl = (u1.IndexOf("?") >= 0 ? "&" : "?") + EncryptionHelper.DecodeFrom64(u[1]) + enTicket;
            }
            else
            {
                backUrl = EncryptionHelper.DecodeFrom64(uri);
            }

            string strRet = "";

            if (backUrl.IndexOf("ticket=") > 0)
            {
                strRet = backUrl + Server.UrlEncode(enTicket);
            }
            else
            {
                strRet = backUrl + (backUrl.IndexOf("?") >= 0 ? "&" : "?") + "ticket=" + Server.UrlEncode(enTicket);
            }

            return(Redirect(strRet));
        }
Ejemplo n.º 23
0
        /// <summary>
        /// 重写Controler中的Json方法
        /// </summary>
        /// <param name="context"></param>
        public override void ExecuteResult(System.Web.Mvc.ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            var requestData = (context.Controller as NetSSLController).RequestData;

            if (JsonRequestBehavior == Mvc.JsonRequestBehavior.DenyGet &&
                String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException("指定的操作不允许Get的Ajax请求方式访问");
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!string.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                if (requestData.Contains("secret") && requestData.Contains("encryption"))
                {
                    var       decrypt = Utils.GetDecrypt(requestData);
                    RsaHelper rsa     = new RsaHelper(null, Utils.RsaPubKey(decrypt.isdefault));

                    string secret     = string.Empty;
                    string encryption = string.Empty;
                    if (decrypt.sectype == SecType.Des.GetHashCode())
                    {
                        var desKv = Utils.DesKV();

                        secret     = rsa.Encrypt(desKv);
                        encryption = DesHelper.Encrypt(JsonHelper.Serialize(Data), desKv);
                    }
                    else
                    {
                        var       aesKv = Utils.AesKV();
                        AESHelper aes   = new AESHelper($"{aesKv}{aesKv}", aesKv);

                        secret     = rsa.Encrypt(aesKv);
                        encryption = aes.Encrypt(JsonHelper.Serialize(Data));
                    }

                    try
                    {
                        response.Write(JsonHelper.Serialize(new Decrypt
                        {
                            secret     = secret,
                            encryption = encryption,
                            isdefault  = decrypt.isdefault,
                            sectype    = decrypt.sectype
                        }));
                    }
                    catch (Exception ex)
                    {
                        response.Write(JsonHelper.Serialize(JResult.Error($"加密失败,异常:{ex.Message}")));
                    }
                }
                else
                {
                    response.Write(JsonHelper.Serialize(Data));
                }
            }
        }
Ejemplo n.º 24
0
 public static string ToDES(this string value)
 {
     return(DesHelper.Encrypt(value, null));
 }
Ejemplo n.º 25
0
        public ActionResult DesTest()
        {
            var str = DesHelper.Encrypt("http://user.cczcrv.com/", "12345678");

            return(Content(str));
        }