示例#1
1
 public TOBBaseObject(Account acc)
 {
     CryptoHelper cryptoHelper = new CryptoHelper();
     acc.DecryptedPassword = cryptoHelper.Decrypt(acc.Password);
     _acc = acc;
 }
 private static XmlConfigSource GetConfig(string cfgFileName)
 {
     XmlConfigSource source = null;
     if (configs.ContainsKey(cfgFileName))
     {
         return configs[cfgFileName];
     }
     string filename = cfgFileName;
     int num = filename.LastIndexOf('.');
     if (filename.EndsWith(".config") && File.Exists(filename.Insert(num + 1, "c")))
     {
         filename = filename.Insert(num + 1, "c");
         LoggingService.DebugFormatted("读取的是加密的配置文件:{0}", new object[] { filename });
         CryptoHelper helper = new CryptoHelper(CryptoTypes.encTypeDES);
         using (XmlTextReader reader = helper.GetDecryptXmlReader(filename))
         {
             XPathDocument document = new XPathDocument(reader);
             source = new XmlConfigSource(document);
             goto Label_00B8;
         }
     }
     if (!File.Exists(filename))
     {
         throw new ArgumentOutOfRangeException(cfgFileName + "不存在");
     }
     source = new XmlConfigSource(filename);
     Label_00B8:
     configs.Add(cfgFileName, source);
     return source;
 }
示例#3
0
        public ActionResult ChangePassword(DettaglioPasswordView dettaglioPassword, int id)
        {
            if (ModelState.IsValid)
            {
                Utente utente = ur.GetById(id);
                var chrypto = new CryptoHelper();

                if (utente.Password.Equals(chrypto.cryptPassword(dettaglioPassword.Password)))
                {
                    var newPassword = dettaglioPassword.newPassword;
                    var repeatNewPassword = dettaglioPassword.repeatNewPassword;
                    if (newPassword.Equals(repeatNewPassword))
                    {

                        utente.Password = chrypto.cryptPassword(newPassword);
                        ur.Save(utente);
                        MailHelper mh = new MailHelper();
                        //mh.SendChangedPasswordEmail(utente.Agenzia.Email);
                        return RedirectToAction("List");
                    }
                    else //questo non può mai succedere perchè c'è la validazione sul modello...
                        ModelState.AddModelError(String.Empty, "Le password inserite non corrispondono!");

                }
                else//questo non dovrebbe mai succedere perchè c'è la validazione Remote sul modello...
                    ModelState.AddModelError(String.Empty, "La password attuale non corrisponde con quella inserita!");
            }
            return View(dettaglioPassword);
        }
示例#4
0
 public override void Run()
 {
     using (OpenFileDialog dialog = new OpenFileDialog())
     {
         dialog.Filter = "cxml文件(*.cxml)|*.cxml|所有文件(*.*)|*.*";
         dialog.DefaultExt = "xml文件(*.xml)|*.xml";
         if (dialog.ShowDialog() == DialogResult.OK)
         {
             string str;
             using (StreamReader reader = new StreamReader(dialog.FileName))
             {
                 str = reader.ReadToEnd();
             }
             string str2 = new CryptoHelper(CryptoTypes.encTypeDES).Decrypt(str);
             using (SaveFileDialog dialog2 = new SaveFileDialog())
             {
                 if (dialog2.ShowDialog() == DialogResult.OK)
                 {
                     using (StreamWriter writer = new StreamWriter(dialog2.FileName))
                     {
                         writer.Write(str2);
                     }
                     MessageBox.Show("生成了解密文件:\n\r" + dialog2.FileName);
                 }
             }
         }
     }
 }
 static AutoUpdateHepler()
 {
     string str = FileUtility.ApplicationRootPath + @"\update";
     if (LoggingService.IsInfoEnabled)
     {
         LoggingService.Info("读取升级配置:" + str);
     }
     XmlConfigSource source = null;
     if (System.IO.File.Exists(str + ".cxml"))
     {
         XmlTextReader decryptXmlReader = new CryptoHelper(CryptoTypes.encTypeDES).GetDecryptXmlReader(str + ".cxml");
         IXPathNavigable document = new XPathDocument(decryptXmlReader);
         source = new XmlConfigSource(document);
         decryptXmlReader.Close();
     }
     else if (System.IO.File.Exists(str + ".xml"))
     {
         source = new XmlConfigSource(str + ".xml");
     }
     if (source != null)
     {
         softName = source.Configs["FtpSetting"].GetString("SoftName", string.Empty);
         version = source.Configs["FtpSetting"].GetString("Version", string.Empty);
         server = source.Configs["FtpSetting"].GetString("Server", string.Empty);
         user = source.Configs["FtpSetting"].GetString("User", string.Empty);
         password = source.Configs["FtpSetting"].GetString("Password", string.Empty);
         path = source.Configs["FtpSetting"].GetString("Path", string.Empty);
         liveup = source.Configs["FtpSetting"].GetString("LiveUp", string.Empty);
         autoupdate = source.Configs["FtpSetting"].GetString("autoupdate", string.Empty);
     }
 }
示例#6
0
 public override string GetMessage()
 {
     string msg= base.GetMessage();
     // 加密
     CryptoHelper helper = new CryptoHelper("ABCDEFGHIJKLMNOP");
     return helper.Encrypt(msg);
 }
示例#7
0
 /// <summary>
 /// Retrieve object containing information needed by client-side library
 /// </summary>
 public FrontEndData GetFrontEndData()
 {
     var crypto = new CryptoHelper();
     return new FrontEndData
     {
         Values = PossibleImageOptions.Select(option => option.Value).ToList(),
         ImageName = ValidImageOption.Key,
         ImageFieldName = crypto.GetRandomString(20),
         AudioFieldName = crypto.GetRandomString(20)
     };
 }
示例#8
0
        public JsonResult CheckPassword(String password, int userId)
        {
            bool valid = false;

            Utente utente = ur.GetById(userId);
            if (utente != null)
            {
                var chrypto = new CryptoHelper();
                if (utente.Password.Equals(chrypto.cryptPassword(password)))
                    valid = true;
            }

            return Json(valid, JsonRequestBehavior.AllowGet);
        }
示例#9
0
 public ActionResult AdminLogin(string password, string email)
 {
     CryptoHelper cryptoHelper = new CryptoHelper();
     var gr = new GestoreRepository();
     var admin = gr.GetByEmail(email);
     if (admin == null)
         return RedirectToAction("Index", "Homepage");
     var cryptedPassword = cryptoHelper.CryptPassword(password);
     if (cryptedPassword.Equals(admin.Password))
     {
         Session.LoginAsAdmin();
         return RedirectToAction("AdminDashBoard", "Dashboard");
     }
     return RedirectToAction("Index", "Homepage");
 }
示例#10
0
 public ActionResult Register(RegisterViewModel viewModel)
 {
     if (ModelState.IsValid)
     {
         CryptoHelper cryptoHelper = new CryptoHelper();
         var agency = viewModel.Agenzia;
         agency.Password = cryptoHelper.CryptPassword(agency.Password);
         var ar = new AgenziaRepository();
         ar.Save(agency);
         Session.Login(agency);
         if (agency.IsTourOperator)
             return RedirectToAction("TourOperatorDashboard", "Dashboard", new { id = agency.Id });
         return RedirectToAction("AgenziaDashboard", "Dashboard", new { id = agency.Id });
     }
     else return View(viewModel);
 }
示例#11
0
        static void Main(string[] args)
        {
            KeyHelper keyHelper = new KeyHelper();
            byte[] key = keyHelper.DeriveKey("testPW", "I+e2/x4P+32RsAp+iZhQaw==");

            CryptoHelper cryptoHelper = new CryptoHelper(key, Convert.FromBase64String("I+e2/x4P+32RsAp+iZhQaw=="));

            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes("test");
            var test = System.Convert.ToBase64String(plainTextBytes);

            string encryptedValue = cryptoHelper.EncryptValue(test);
            string decryptedValue = cryptoHelper.DecryptValue(encryptedValue);

            Console.WriteLine(encryptedValue);
            Console.WriteLine(decryptedValue);
            Console.ReadKey();
        }
示例#12
0
 public ActionResult Login(string password, string email)
 {
     CryptoHelper cryptoHelper = new CryptoHelper();
     var ar = new AgenziaRepository();
     var agency = ar.GetByEmail(email);
     if (agency == null)
         return View("Register");
     var cryptedPassword = cryptoHelper.CryptPassword(password);
     if (cryptedPassword.Equals(agency.Password))
     {
         Session.Login(agency);
         if (agency.IsTourOperator)
             return RedirectToAction("TourOperatorDashboard", "Dashboard", new { id = agency.Id });
         return RedirectToAction("AgenziaDashboard", "Dashboard", new { id = agency.Id });
     }
     var viewModel = new RegisterViewModel();
     return View("Register", viewModel);
 }
示例#13
0
        public static AuthenticationResult AuthenticateUtente(String name, String password)
        {
            AuthenticationResult result = null;

            AgenziaRepository ur = new AgenziaRepository();
            var registeredAgenzia = ur.GetByName(name);

            if (registeredAgenzia == null)
            {
                result = new AuthenticationResult { IsAuthenticated = false, AuthErrorMessage = "Username/Password errata!" };
            }
            else
            {
                CryptoHelper crypter = new CryptoHelper();
                if (crypter.CryptPassword(password).Equals(registeredAgenzia.Password))
                    result = new AuthenticationResult { IsAuthenticated = true, AuthenticatedAgenzia = registeredAgenzia };
                else
                    result = new AuthenticationResult { IsAuthenticated = false, AuthErrorMessage = "Username/Password errata!" };
            }
            return result;
        }
示例#14
0
        public static AuthenticationResult AuthenticateUtente(String username, String passwordInChiaro)
        {
            AuthenticationResult result = null;

            UtenteRepository ur = new UtenteRepository();
            var registeredUtente = ur.GetByUsername(username);

            if (registeredUtente == null)
            {
                result = new AuthenticationResult { IsAuthenticated = false, AuthErrorMessage = "Username/Password errata!" };
            }
            else
            {
                CryptoHelper crypter = new CryptoHelper();
                if (crypter.cryptPassword(passwordInChiaro).Equals(registeredUtente.Password))
                    result = new AuthenticationResult { IsAuthenticated = true, AuthenticatedUtente = registeredUtente };
                else
                    result = new AuthenticationResult { IsAuthenticated = false, AuthErrorMessage = "Username/Password errata!"};

            }

            return result;
        }
        static ulong GetSteam3DepotManifest(uint depotId, uint appId, string branch)
        {
            if (Config.ManifestId != INVALID_MANIFEST_ID)
            {
                return(Config.ManifestId);
            }

            KeyValue depots     = GetSteam3AppSection(appId, EAppInfoSection.Depots);
            KeyValue depotChild = depots[depotId.ToString()];

            if (depotChild == KeyValue.Invalid)
            {
                return(INVALID_MANIFEST_ID);
            }

            if (depotChild["depotfromapp"] != KeyValue.Invalid)
            {
                uint otherAppId = (uint)depotChild["depotfromapp"].AsInteger();
                if (otherAppId == appId)
                {
                    // This shouldn't ever happen, but ya never know with Valve. Don't infinite loop.
                    Console.WriteLine("App {0}, Depot {1} has depotfromapp of {2}!",
                                      appId, depotId, otherAppId);
                    return(INVALID_MANIFEST_ID);
                }

                steam3.RequestAppInfo(otherAppId);

                if (AccountHasAccess(otherAppId))
                {
                    return(GetSteam3DepotManifest(depotId, otherAppId, branch));
                }
                else
                {
                    string contentName      = GetAppOrDepotName(INVALID_DEPOT_ID, otherAppId);
                    string contentDepotName = GetAppOrDepotName(depotId, appId);
                    Console.WriteLine("Dependent app {0} ({1}) for depot {2} ({3}) is not available from this account.", otherAppId, contentName, depotId, contentDepotName);
                }
            }

            var manifests           = depotChild["manifests"];
            var manifests_encrypted = depotChild["encryptedmanifests"];

            if (manifests.Children.Count == 0 && manifests_encrypted.Children.Count == 0)
            {
                return(INVALID_MANIFEST_ID);
            }

            var node = manifests[branch];

            if (branch != "Public" && node == KeyValue.Invalid)
            {
                var node_encrypted = manifests_encrypted[branch];
                if (node_encrypted != KeyValue.Invalid)
                {
                    string password = Config.BetaPassword;
                    if (password == null)
                    {
                        Console.Write("Please enter the password for branch {0}: ", branch);
                        Config.BetaPassword = password = Console.ReadLine();
                    }

                    byte[] input          = Util.DecodeHexString(node_encrypted["encrypted_gid"].Value);
                    byte[] manifest_bytes = CryptoHelper.VerifyAndDecryptPassword(input, password);

                    if (manifest_bytes == null)
                    {
                        Console.WriteLine("Password was invalid for branch {0}", branch);
                        return(INVALID_MANIFEST_ID);
                    }

                    return(BitConverter.ToUInt64(manifest_bytes, 0));
                }

                Console.WriteLine("Invalid branch {0} for appId {1}", branch, appId);
                return(INVALID_MANIFEST_ID);
            }

            if (node.Value == null)
            {
                return(INVALID_MANIFEST_ID);
            }

            return(UInt64.Parse(node.Value));
        }
示例#16
0
 public ActionResult Create(Utente utente)
 {
     if (ModelState.IsValid)
     {
         var cryptyo = new CryptoHelper();
         utente.Password = cryptyo.cryptPassword(utente.Password);
         ur.Save(utente);
         return RedirectToAction("List");
     }
     return View(utente);
 }
        /// <summary>
        /// TODO: Comment
        /// </summary>
        public void SaveDataExcecute()
        {
            //TODO: Save path in configuration
            string configurationPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                "SecureVault",
                "settings",
                "configuration.dat");

            ConfigurationHelper configHelper = new ConfigurationHelper(configurationPath);
            SecureStringHelper secureStringHelper = new SecureStringHelper();
            KeyHelper keyHelper = new KeyHelper();
            SaltGenerator saltGenerator = new SaltGenerator();

            //Generate random salt
            byte[] salt = saltGenerator.GenerateSalt();

            byte[] key = keyHelper.DeriveKey(secureStringHelper.SecureStringToString(this.Password), configHelper.GetSalt());

            CryptoHelper cryptoHelper = new CryptoHelper(key, salt);

            var plainTextBytes = Encoding.UTF8.GetBytes(secureStringHelper.SecureStringToString(this.SecureData));
            var plainPasswordBase64 = Convert.ToBase64String(plainTextBytes);

            string encryptedValue = cryptoHelper.EncryptValue(plainPasswordBase64);

            configHelper.AddData(this.Name, encryptedValue, Convert.ToBase64String(salt));

            //Close the NewData window
            Application.Current.Windows.OfType<Window>().SingleOrDefault(x => x.IsActive).Close();
        }
示例#18
0
        /// <summary>
        /// Use default chain id.
        /// </summary>
        /// <param name="keyPair"></param>
        public ContractTester(ECKeyPair keyPair)
        {
            Application =
                AbpApplicationFactory.Create <TContractTestAElfModule>(options =>
            {
                options.UseAutofac();
                options.Services.AddTransient(o =>
                {
                    var mockService = new Mock <IAccountService>();
                    mockService.Setup(a => a.SignAsync(It.IsAny <byte[]>())).Returns <byte[]>(data =>
                                                                                              Task.FromResult(CryptoHelper.SignWithPrivateKey(keyPair.PrivateKey, data)));

                    mockService.Setup(a => a.GetPublicKeyAsync()).ReturnsAsync(keyPair.PublicKey);

                    return(mockService.Object);
                });
            });

            Application.Initialize();

            KeyPair = keyPair;
        }
示例#19
0
        public JsonResult Logined(FormCollection form)
        {
            Hashtable ht = new Hashtable();

            ht.Add("Msg", GeneralHandler.FBaseInfo);
            ht.Add("Url", GeneralHandler.SiteLoginUrl);
            ht.Add("IsCode", false);
            try
            {
                string txtUname = form["txtUname"] as string;
                string txtUpwd  = form["txtUpwd"] as string;
                txtUpwd = CryptoHelper.MD5(txtUpwd, true);
                string txtCheckCode = form["txtCheckCode"] as string;
                txtCheckCode = txtCheckCode.ToLower();
                string strCheckCode = Session["CheckCode"] as string;
                strCheckCode = strCheckCode.ToLower();
                if (txtCheckCode.Length != 4 || !ValidHelper.EngIsEngAndNum(txtCheckCode) || txtCheckCode != strCheckCode)
                {
                    ht["Msg"]    = "您输入的验证码不正确[4个字符]。";
                    ht["IsCode"] = true;
                }
                else if (txtUname.Length < 4 || txtUname.Length > 16 || !ValidHelper.EngIsRegisters(txtUname))
                {
                    ht["Msg"] = "您输入的用户名不正确[4-16个字符]。";
                }
                else if (ValidHelper.IsSqlFilter(txtUname))
                {
                    ht["Msg"] = "您输入的用户名不正确[4-16个字符]。IsSqlFilter";
                }
                else if (!DawnAuthUserBLL.ExistsOfName(txtUname))
                {
                    ht["Msg"] = "您输入的用户名不存在!";
                }
                else
                {
                    var userIList = DawnAuthUserBLL.ISelect(string.Format("[user_name]='{0}' and [user_pwd]='{1}'", txtUname, txtUpwd));
                    if (userIList.Count == 0)
                    {
                        ht["Msg"] = "您输入的用户名与密码不匹配!";
                    }
                    else if (userIList.Count > 1)
                    {
                        ht["Msg"] = "您的账号存在异常,请联系管理员!";
                    }
                    else
                    {
                        var userInfo = userIList.First();
                        if (userInfo.UserStatus == 0)
                        {
                            ht["Msg"] = "您的账号存已禁用,请联系管理员!";
                        }
                        else if (userInfo.UserGrade < 2)
                        {
                            ht["Msg"] = "对不起,您的管理级别不符合!";
                        }
                        else
                        {
                            userIList.Clear();
                            Session["LoginName"] = txtUname;
                            Session[txtUname]    = CryptoHelper.Encrypt(JsonConvert.SerializeObject(userInfo), GeneralHandler.TokenKey);
                            var userAuth = DawnAuthUserBLL.GetUserAuthority(userInfo.UserId);
                            Session["LoginAuthority"] = CryptoHelper.Encrypt(JsonConvert.SerializeObject(userAuth), GeneralHandler.TokenKey);
                            var userStat = DawnAuthUserBLL.GetUserStatus(userInfo.UserId);
                            Session["LoginStatus"] = CryptoHelper.Encrypt(JsonConvert.SerializeObject(userStat), GeneralHandler.TokenKey);
                            var userExtent = DawnAuthUserExtentBLL.ISelect(string.Format("user_id='{0}'", userInfo.UserId));
                            Session["LoginExtent"] = CryptoHelper.Encrypt(JsonConvert.SerializeObject(userExtent), GeneralHandler.TokenKey);
                            FormsAuthentication.SetAuthCookie(CryptoHelper.Encrypt(txtUname, GeneralHandler.TokenKey), false);

                            #region 登录日志

                            DawnAuthUserLoginMDL dataInfo = new DawnAuthUserLoginMDL();
                            dataInfo.UserId      = userInfo.UserId;
                            dataInfo.LogTime     = DateTime.Now;
                            dataInfo.LogIp       = RequestHelper.GetIPAddress();
                            dataInfo.LogMac      = "Unknown";
                            dataInfo.LogComputer = "Unknown";
                            dataInfo.LogAttach   = null;
                            dataInfo.LogCount    = 1;
                            DawnAuthUserLoginBLL.Insert(dataInfo);

                            #endregion

                            ht["Msg"] = GeneralHandler.StateSuccess;
                            ht["Url"] = GeneralHandler.SiteLoginedUrl;
                            //var hidReturnUrl = form["hidReturnUrl"] as string;
                            //ht["Url"] = string.IsNullOrEmpty(hidReturnUrl) ? GeneralHandler.SiteLoginedUrl : hidReturnUrl;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //ht["Msg"] = GeneralHandler.StateRefresh;
                ht["Msg"] = "对不起!无法与数据库建立连接!请联系管理员!";
                GeneralHandler.InsertByError(ex);
            }
            return(Json(ht));
        }
示例#20
0
        ////////////////////////////////////////////////////
        // STEAM WEB INTERFACE
        ////////////////////////////////////////////////////

        public override async void LoginWebInterface(ulong steamID)
        {
            if (!IsAuthenticated)
            {
                SteamUser.WebAPIUserNonceCallback callback;

                try
                {
                    callback = await _steamUser.RequestWebAPIUserNonce();
                }
                catch (Exception ex)
                {
                    _log.Error(ex, "Unable to request Web API Nonce. Titan won't be able to execute Web API actions.");
                    return;
                }

                if (string.IsNullOrWhiteSpace(callback?.Nonce))
                {
                    _log.Error("Received empty Web API Nonce. Titan won't be able to execute Web API actions.");
                    return;
                }

                var    sessionID  = Convert.ToBase64String(Encoding.UTF8.GetBytes(steamID.ToString()));
                var    sessionKey = CryptoHelper.GenerateRandomBlock(32);
                byte[] cryptedSessionKey;

                using (var rsa = new RSACrypto(KeyDictionary.GetPublicKey(_steamClient.Universe)))
                {
                    cryptedSessionKey = rsa.Encrypt(sessionKey);
                }

                var loginKey = new byte[callback.Nonce.Length];
                Array.Copy(Encoding.ASCII.GetBytes(callback.Nonce), loginKey, callback.Nonce.Length);

                // AES encrypt the login key with our session key
                var cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey);

                if (!Titan.Instance.WebHandle.AuthentificateUser(
                        steamID, cryptedLoginKey, cryptedSessionKey, out var result
                        ))
                {
                    _log.Error("Failed to authentificate with Web API Nonce. " +
                               "Titan won't be able to execute Web API actions.");
                    return;
                }

                var token       = result["token"].Value;
                var secureToken = result["tokensecure"].Value;

                if (string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(secureToken))
                {
                    _log.Error("Failed to authentificate with Web API Nonce. " +
                               "Titan won't be able to execute Web API actions.");
                    return;
                }

                Cookies.Add("sessionid", sessionID);
                Cookies.Add("steamLogin", token);
                Cookies.Add("steamLoginSecure", secureToken);

                if (!Titan.Instance.Options.Secure)
                {
                    _log.Debug("Authorized with Steam Web API. Session ID: {id}", sessionID);
                }

                _log.Information("Successfully authorized with Steam Web API.");

                IsAuthenticated = true;
            }
        }
示例#21
0
 public string ComputeHash(string dateTimeStr, string dateFormat, string secret)
 {
     return(CryptoHelper.HMACSHA256(dateTimeStr + dateFormat, secret));
 }
示例#22
0
        /// <summary>
        /// Language selection dropdown list for cryptocoin payment box
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="defaultLanguage"></param>
        /// <param name="anchor"></param>
        /// <returns></returns>
        public static MvcHtmlString LanguageBox(this HtmlHelper helper, string defaultLanguage = "en",
                                                string anchor = "gourlcryptolang", bool select_list = true)
        {
            defaultLanguage = defaultLanguage.ToLower();
            string id    = "gourlcryptolang";
            string lan   = CryptoHelper.cryptobox_sellanguage(defaultLanguage);
            var    query = HttpUtility.ParseQueryString(HttpContext.Current.Request.Url.Query);

            if (HttpContext.Current.Request.QueryString[id] != null &&
                HttpContext.Current.Request.QueryString[id] != "" &&
                localisation.ContainsKey(HttpContext.Current.Request.QueryString[id]))
            {
                query.Remove(id);
            }

            string     url = HttpContext.Current.Request.Url.AbsoluteUri.Split(new[] { '?' })[0];
            TagBuilder selectBuilder;

            if (select_list)
            {
                selectBuilder = new TagBuilder("select");
                selectBuilder.MergeAttribute("name", id);
                selectBuilder.MergeAttribute("id", id);

                selectBuilder.MergeAttribute("onchange", "window.open(\"" + url + "?" +
                                             query.ToString() +
                                             (query.Count > 0 ? "&" : "") + id +
                                             "=\"+this.options[this.selectedIndex].value+\"#" + anchor +
                                             "\",\"_self\")");
                foreach (string key in localisation.Keys)
                {
                    TagBuilder optionsBuilder = new TagBuilder("option");
                    if (key == lan)
                    {
                        optionsBuilder.MergeAttribute("selected", "selected");
                    }
                    optionsBuilder.MergeAttribute("value", key);
                    optionsBuilder.InnerHtml = localisation[key].Name;
                    selectBuilder.InnerHtml += optionsBuilder.ToString();
                }
            }
            else
            {
                selectBuilder = new TagBuilder("ul");
                selectBuilder.MergeAttribute("class", "dropdown-menu");
                foreach (string key in localisation.Keys)
                {
                    TagBuilder liBuilder = new TagBuilder("li");
                    if (key == lan)
                    {
                        liBuilder.MergeAttribute("class", "active");
                    }
                    TagBuilder aBuilder = new TagBuilder("a");
                    aBuilder.MergeAttribute("href", url + "?" +
                                            query.ToString() +
                                            (query.Count > 0 ? "&" : "") + id + "=" + key + "#" + anchor);
                    aBuilder.InnerHtml       = localisation[key].Name;
                    liBuilder.InnerHtml      = aBuilder.ToString();
                    selectBuilder.InnerHtml += liBuilder.ToString();
                }
            }

            return(MvcHtmlString.Create(selectBuilder.ToString()));
        }
        /// <summary>
        /// 获取指定用户在指定系统所有拥有的权限信息(专门用于第三方系统调用)
        /// </summary>
        /// <param name="sysId"></param>
        /// <param name="account"></param>
        /// <param name="sign"></param>
        /// <returns></returns>
        public string GetUserRightsJson(int sysId, string account, string sign)
        {
            try
            {
                //验证请求参数
                if (sysId <= 0 || string.IsNullOrEmpty(account) || string.IsNullOrEmpty(sign))
                {
                    return("{\"State\":1,\"Message\":\"请求参数无效。\"}");
                }

                //限定配置过的IP才能请求
                string clientIp = DACommonHelper.GetClientIP();
                //if (clientIp != "127.0.0.1"
                //    && !clientIp.StartsWith("10.")
                //    && !clientIp.StartsWith("192.168.")
                //    && !Regex.IsMatch(clientIp, @"^172\.(1([6-9]{1})|2([0-9]{1})|3([0-1]{1}))(\.[0-9]+){2}$")
                //    && !GetUserRightsJson_ClientIP.Contains(clientIp))
                //{
                //    return "{\"State\":2,\"Message\":\"当前请求IP无效。\"}";
                //}

                //指定的系统必须存在
                SystemInfo system = DABasicInfoHelper.GetSystem(sysId, CacheTimeOption.Short);
                if (system == null)
                {
                    return("{\"State\":101,\"Message\":\"当前系统不存在。\"}");
                }
                if (system.Status == StatusOptions.Invalid)
                {
                    return("{\"State\":102,\"Message\":\"当前系统已被禁用。\"}");
                }

                //请求有做MD5校验
                string md5 = CryptoHelper.MD5_Encrypt(string.Format("{0}{1}{2}", sysId, system.Md5Key, account));
                if (md5.ToLower() != sign.ToLower())
                {
                    return("{\"State\":3,\"Message\":\"无效的请求。\"}");
                }

                //验证用户有效性
                User user = DABasicInfoHelper.GetUser(account);
                if (user == null)
                {
                    return("{\"State\":103,\"Message\":\"用户不存在。\"}");
                }
                if (user.Status == StatusOptions.Invalid)
                {
                    return("{\"State\":104,\"Message\":\"用户已被禁用。\"}");
                }
                if (user.AccountType != UserTypeOptions.SuperAdmin &&
                    (DateTime.Now > user.EndTime || DateTime.Now < user.BeginTime))
                {
                    return("{\"State\":105,\"Message\":\"用户权限已过期。\"}");
                }
                List <UserSystem> userSystems = DARightsHelper.GetUserSystems(user.ID);
                UserSystem        userSystem  = userSystems.FirstOrDefault(a => a.SystemID == sysId);
                if (userSystem == null)
                {
                    return("{\"State\":106,\"Message\":\"用户没有当前系统的访问权限。\"}");
                }

                //提取用户权限
                List <Right>     allRights = DABasicInfoHelper.GetRights(sysId, -1, CacheTimeOption.Short);
                List <RightItem> myRights  = DARightsHelper.GetUserRights(sysId, user.ID, user.AccountType);
                var rights = from a in allRights
                             join b in myRights on a.ID equals b.RightID
                             where a.Status == StatusOptions.Valid
                             select a;
                if (rights.Count() == 0)
                {
                    return("{\"State\":107,\"Message\":\"用户没有当前系统的操作权限。\"}");
                }

                //生成正常返回JSON
                StringBuilder result = new StringBuilder("{\"State\":0,\"Message\":\"OK\",");
                result.AppendFormat("\"System\":{{\"ID\":{0},\"Name\":\"{1}\",\"Url\":\"{2}\"}},", system.ID, system.Name, system.Url);
                result.AppendFormat("\"User\":{{\"ID\":{0},\"Account\":\"{1}\",\"TrueName\":\"{2}\",\"UserType\":{3},\"Email\":\"{4}\",\"Department\":\"{5}\",\"LastLoginTime\":\"{6}\"}},"
                                    , user.ID, user.Account, user.TrueName, userSystem.Admin ? (int)user.AccountType : 0, user.Email, user.Department, userSystem.LastLoginTime.ToString("yyyy-MM-dd HH:mm:ss"));
                result.Append("\"Rights\":[");
                foreach (var right in rights)
                {
                    result.AppendFormat("{{\"ID\":{0},\"PID\":{1},\"Name\":\"{2}\",\"Level\":{3},\"Type\":{4},\"SortIndex\":{5},\"URL\":\"{6}\"}},"
                                        , right.ID, right.ParentID, right.Name, right.RightLevel, (int)right.RightType, right.SortIndex, right.PageUrl);
                }

                //更新最后一次访问时间
                DABasicInfoHelper.UpdateSystemLastLoginTime(sysId, user.ID);

                //记录日志
                DABasicInfoHelper.AddAdminLog(
                    new AdminLog
                {
                    Account     = user.Account,
                    TrueName    = user.TrueName,
                    AccountType = user.AccountType,
                    AddTime     = DateTime.Now,
                    IP          = clientIp,
                    PageUrl     = "GetUserRightsJson",
                    SystemID    = sysId,
                    Memo        = string.Format("{0}系统获取用户{1}权限", system.Name, user.Account)
                });

                return(result.ToString(0, result.Length - 1) + "]}");
            }
            catch (Exception ex)
            {
                LogHelper.WriteException("GetUserRightsJson异常", ex);
                return("{\"State\":4,\"Message\":\"系统异常。\"}");
            }
        }
        public static string GenerateDeviceIdFromGuid(Guid guid)
        {
            var hashedGuid = CryptoHelper.CalculateMd5(guid.ToString());

            return($"android-{hashedGuid.Substring(0, 16)}");
        }
示例#25
0
        public async Task <IActionResult> AddHospitalAsync([FromBody] AddHospitalRequestDto request)
        {
            HospitalBiz hospitalBiz = new HospitalBiz();

            if (await hospitalBiz.AnyAccountAsync(request.Account))
            {
                return(Failed(ErrorCode.UserData, "已经存在相同的账号!"));
            }

            var hospitalGuid = Guid.NewGuid().ToString("N");
            var textGuid     = Guid.NewGuid().ToString("N");

            request.Content = string.IsNullOrWhiteSpace(request.Content) ? "暂无详细" : request.Content;
            request.HosTag  = string.IsNullOrWhiteSpace(request.HosTag) ? "暂无标签" : request.HosTag;

            var richtextModel = new RichtextModel
            {
                Content         = request.Content,
                CreatedBy       = UserID,
                CreationDate    = DateTime.Now,
                Enable          = true,
                LastUpdatedBy   = UserID,
                LastUpdatedDate = DateTime.Now,
                OrgGuid         = string.Empty,
                OwnerGuid       = hospitalGuid,
                TextGuid        = textGuid,
            };
            var hospitalModel = new HospitalModel
            {
                HosAbstract    = request.HosAbstract,
                HosDetailGuid  = textGuid,
                HosLevel       = request.HosLevel,
                HosName        = request.HosName,
                HosTag         = request.HosTag,
                Location       = request.Location,
                LogoGuid       = request.LogoGuid,
                PlatformType   = PlatformType.CloudDoctor.ToString(),
                RegisteredDate = request.RegisteredDate,
                Visibility     = request.Visibility,
                HospitalGuid   = hospitalGuid,
                CreatedBy      = UserID,
                LastUpdatedBy  = UserID,
                Enable         = request.Enable,
                OrgGuid        = string.Empty,
                ContactNumber  = request.ContactNumber,
                Sort           = request.Sort,
                GuidanceUrl    = request.GuidanceUrl ?? string.Empty,
                ExternalLink   = request.ExternalLink ?? string.Empty,
                Password       = CryptoHelper.AddSalt(hospitalGuid, request.Password),
                Account        = request.Account,
                IsHospital     = request.IsHospital,
                Longitude      = request.Longitude,
                Latitude       = request.Latitude
            };
            var officeAll = await new OfficeBiz().GetAllAsync2();
            var offices   = officeAll.Select(a => (new
            {
                a.OfficeName,
                ParentName = officeAll.FirstOrDefault(b => b.OfficeGuid == a.ParentOfficeGuid)?.OfficeName,
                a.Sort,
                a.Enable,
                a.PictureGuid
            })).Distinct();
            var offices2 = new List <OfficeModel>();

            foreach (var item in offices)
            {
                GetOfficeModel(item.ParentName, item.OfficeName, item.Sort, item.Enable, item.PictureGuid, hospitalModel, offices2, offices);
            }
            var result = await hospitalBiz.AddAsync(hospitalModel, richtextModel, offices2);

            if (!result)
            {
                return(Failed(ErrorCode.UserData, "添加失败"));
            }
            return(Success());
        }
示例#26
0
        public async Task <IActionResult> UpdateHospitalAsync([FromBody] UpdateHospitalRequestDto request)
        {
            var hospitalBiz   = new HospitalBiz();
            var hospitalModel = await hospitalBiz.GetAsync(request.HospitalGuid);

            if (hospitalModel == null)
            {
                return(Failed(ErrorCode.DataBaseError, "数据错误"));
            }
            if (request.Account != hospitalModel.Account && await hospitalBiz.AnyAccountAsync(request.Account))
            {
                return(Failed(ErrorCode.UserData, "已经存在相同的账号!"));
            }
            var contentBiz = new RichtextBiz();

            request.Content = string.IsNullOrWhiteSpace(request.Content) ? "暂无详细" : request.Content;
            request.HosTag  = string.IsNullOrWhiteSpace(request.HosTag) ? "暂无标签" : request.HosTag;
            var richtextModel = await contentBiz.GetAsync(hospitalModel.HosDetailGuid);

            var richtextIsAdd = false;

            if (richtextModel != null)
            {
                richtextModel.Content         = request.Content;
                richtextModel.LastUpdatedBy   = UserID;
                richtextModel.LastUpdatedDate = DateTime.Now;
                richtextModel.OrgGuid         = string.Empty;
                richtextModel.OwnerGuid       = request.HospitalGuid;
            }
            else
            {
                var textGuid = Guid.NewGuid().ToString("N");
                richtextModel = new RichtextModel
                {
                    Content         = request.Content,
                    CreatedBy       = UserID,
                    CreationDate    = DateTime.Now,
                    Enable          = true,
                    LastUpdatedBy   = UserID,
                    LastUpdatedDate = DateTime.Now,
                    OrgGuid         = string.Empty,
                    OwnerGuid       = hospitalModel.HospitalGuid,
                    TextGuid        = textGuid,
                };
                hospitalModel.HosDetailGuid = textGuid;
                richtextIsAdd = true;
            }

            hospitalModel.HosAbstract     = request.HosAbstract;
            hospitalModel.HosLevel        = request.HosLevel;
            hospitalModel.HosName         = request.HosName;
            hospitalModel.HosTag          = request.HosTag;
            hospitalModel.Location        = request.Location;
            hospitalModel.LogoGuid        = request.LogoGuid;
            hospitalModel.RegisteredDate  = request.RegisteredDate;
            hospitalModel.Visibility      = request.Visibility;
            hospitalModel.LastUpdatedBy   = UserID;
            hospitalModel.LastUpdatedDate = DateTime.Now;
            hospitalModel.Enable          = request.Enable;
            hospitalModel.ContactNumber   = request.ContactNumber;
            hospitalModel.Sort            = request.Sort;
            hospitalModel.GuidanceUrl     = request.GuidanceUrl ?? string.Empty;
            hospitalModel.ExternalLink    = request.ExternalLink ?? string.Empty;
            hospitalModel.Account         = request.Account;
            hospitalModel.IsHospital      = request.IsHospital;
            hospitalModel.Longitude       = request.Longitude;
            hospitalModel.Latitude        = request.Latitude;
            if (null != request.Password)
            {
                hospitalModel.Password = CryptoHelper.AddSalt(hospitalModel.HospitalGuid, request.Password);
            }

            var response = await hospitalBiz.UpdateAsync(hospitalModel, richtextModel, richtextIsAdd);

            if (!response)
            {
                return(Failed(ErrorCode.DataBaseError, "修改失败"));
            }
            return(Success(response));
        }
示例#27
0
        //private static USER_LOGIN ObjInstance;
        ///// <summary>LOGIN单例模式</summary>
        //public static USER_LOGIN GetInstance()
        //{
        //    return ObjInstance ?? (ObjInstance = new USER_LOGIN());
        //}

        /// <summary>玩家登陆指令</summary>
        public ASObject CommandStart(TGGSession session, ASObject data)
        {
#if DEBUG
            XTrace.WriteLine("{0}:{1}", "LOGIN", "玩家登陆指令");
#endif
#if DEBUG
            XTrace.WriteLine("------------   登陆前  {0}     ------------", Variable.OnlinePlayer.Count);
#endif
            if (!data.ContainsKey("isAdult") || !data.ContainsKey("userName"))
            {
                return(null);
            }
            var isAdult = Convert.ToInt32(data.FirstOrDefault(q => q.Key == "isAdult").Value); //是否成年0:未成年 1:成年

            var name     = data.FirstOrDefault(q => q.Key == "userName").Value.ToString();
            var userName = string.Empty;
            if (CommonHelper.IsKey())
            {
                //var decrypt = CommonHelper.GetUserName(name);

                var gamekey   = CommonHelper.GetAppSettings("gamekey");//获取游戏加密
                var game_name = String.Empty;
                var cb        = false;
                try
                {
                    var str = CommonHelper.Decode(name);
                    game_name = CryptoHelper.Decrypt(str, gamekey);
                    cb        = true;
                }
                catch { XTrace.WriteLine("name:{0}", name); }

                if (!cb)
                {
                    return(CommonHelper.ErrorResult((int)ResultType.USER_SUBMIT_ERROR));
                }
                userName = game_name;
            }
            else
            {
                userName = name;
            }

            if (string.IsNullOrEmpty(userName))
            {
                return(CommonHelper.ErrorResult((int)ResultType.USER_SUBMIT_ERROR));
            }

            var user = tg_user.Find(string.Format("user_code='{0}'", userName));
            if (user == null)
            {
                return(new ASObject(BuildData((int)ResultType.NO_DATA, null, 0)));
            }
            if (user.state == (int)UserStateType.Block)
            {
                return(CommonHelper.ErrorResult((int)ResultType.BASE_PLAYER_BLOCK_ERROR));
            }
            if (user.state == (int)UserStateType.Frozen)
            {
                return(CommonHelper.ErrorResult((int)ResultType.BASE_PLAYER_FROZEN_ERROR));
            }
            var b = Variable.OnlinePlayer.ContainsKey(user.id);
#if DEBUG
            XTrace.WriteLine("OnlinePlayer:{0} {1}", user.id, b);
#endif
            if (b)
            {
                var user_id = Convert.ToInt64(user.id);
                var s       = Variable.OnlinePlayer[user_id] as TGGSession;
                if (s != null)
                {
                    s.Close();
                }
            }

            var player = Common.GetInstance().GetPlayer(user, isAdult);
            if (player == null)
            {
                return(null);
            }
            session.Player = player;
            session.Fight  = Common.GetInstance().GetFight(session.Player);

            Variable.OnlinePlayer.AddOrUpdate(user.id, session, (k, v) => session);
            tg_user_login_log.LoginLog(user.id, Common.GetInstance().GetRemoteIP(session));

            ReLoadTask(session);
            RemoveFightState(user.id);

            Int64 opentime = 0;
            if (CommonHelper.CheckOpenTime())
            {
                if (session.Player.UserExtend.fcm == (int)FCMType.Yes)
                {
                    var fcm = new Share.User().GetFCM(user.id);
                    if (fcm != null)
                    {
                        session.Player.onlinetime = fcm.login_time_longer_day * 60;
                        opentime = fcm.login_open_time;
                    }
                }
            }
            report_record_login.Login(player.User.id);
            report_day.OnOffLine();
            //new Share.ActivityOpenService().ActivityPush(session.Player.User.id);
            return(new ASObject(BuildData((int)ResultType.SUCCESS, session.Player, opentime)));
        }
示例#28
0
        public ContentResult Message(string signature, string timestamp, string nonce, string encrypt_type, string msg_signature)
        {
            //获取消息内容
            string msgContent = "";

            using (StreamReader sr = new StreamReader(Request.InputStream, Encoding.UTF8))
            {
                msgContent = sr.ReadToEnd();
            }


            if (String.IsNullOrEmpty(encrypt_type) || encrypt_type.Equals("raw"))
            {
                string mysig = CryptoHelper.SHA1(Token, timestamp, nonce);
                if (String.IsNullOrEmpty(signature) || !signature.Equals(mysig, StringComparison.OrdinalIgnoreCase))
                {
                    return(new ContentResult()
                    {
                        Content = ""
                    });
                }
            }
            else
            {
                //解密消息
                string        sMsg     = ""; //解析之后的明文
                int           ret_code = 0;
                WXBizMsgCrypt wxcpt    = new WXBizMsgCrypt(Token, EncryptKey, AppId);
                ret_code = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, msgContent, ref sMsg);
                if (ret_code != 0)
                {
                    return(new ContentResult()
                    {
                        Content = ""
                    });
                }

                msgContent = sMsg;
            }


            XmlDocument doc = new XmlDocument();

            doc.LoadXml(msgContent);


            if (doc.DocumentElement.SelectSingleNode("MsgType").InnerText == "text")       //根据回复关键字查询课程
            {
                #region Text

                string content = doc.DocumentElement.SelectSingleNode("Content").InnerText;
                var    user    = _db.Users.SingleOrDefault(u => u.Phone == content.Trim() && u.UserStatus == UserStatus.Ok);
                string msg     = "";
                if (user != null)
                {
                    msg = $@"<xml>
<ToUserName><![CDATA[{doc.DocumentElement.SelectSingleNode("FromUserName").InnerText}]]></ToUserName>
<FromUserName><![CDATA[{doc.DocumentElement.SelectSingleNode("ToUserName").InnerText}]]></FromUserName>
<CreateTime>{doc.DocumentElement.SelectSingleNode("CreateTime").InnerText}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[孩子姓名:{user.ChildName}
联系方式:{user.Phone}
剩余次数:{user.CanUseCount}
<a href='https://www.hdlebaobao.cn/Order/GetOrderListByUserPhone?phone={user.Phone}'>点击查看推拿记录</a>]]></Content>
</xml>";
                }
                else
                {
                    msg = $@"<xml>
<ToUserName><![CDATA[{doc.DocumentElement.SelectSingleNode("FromUserName").InnerText}]]></ToUserName>
<FromUserName><![CDATA[{doc.DocumentElement.SelectSingleNode("ToUserName").InnerText}]]></FromUserName>
<CreateTime>{doc.DocumentElement.SelectSingleNode("CreateTime").InnerText}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[查询有误,请重新输入]]></Content>
</xml>";
                }


                return(new ContentResult()
                {
                    Content = msg, ContentEncoding = Encoding.UTF8, ContentType = "text/xml"
                });

                #endregion
            }



            return(new ContentResult()
            {
                Content = "", ContentEncoding = Encoding.UTF8, ContentType = "text/xml"
            });
        }
示例#29
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(c => c.EnableEndpointRouting = false);
            services.AddControllers(config =>
            {
                config.Filters.Add(typeof(CustomExceptionFilter));
                //config.Filters.Add( new CustomAuthorizeFilter( new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build() ) );
            })
            .AddNewtonsoftJson(
                //options =>
                //    options.SerializerSettings.ContractResolver =
                //        new CamelCasePropertyNamesContractResolver()
                )
            .AddControllersAsServices()
            .AddFluentValidation(cfg =>
            {
                cfg.ValidatorFactoryType = typeof(AttributedValidatorFactory);
                cfg.ImplicitlyValidateChildProperties = true;
            });
            services.AddOptions();

            // https
            var useHttps = Configuration.GetValue <bool?>("UseHttps");

            if (useHttps.HasValue && useHttps.Value)
            {
                services.AddHttpsRedirection(options =>
                {
                    options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
                    options.HttpsPort          = 443;
                });
            }

            // ef pro
            // HibernatingRhinos.Profiler.Appender.EntityFramework.EntityFrameworkProfiler.Initialize();

            // log
            var seqServer   = Configuration.GetValue <string>("SeqServer");
            var levelSwitch = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Information);

            if (string.IsNullOrEmpty(seqServer))
            {
                Log.Logger = new LoggerConfiguration()
                             .MinimumLevel.ControlledBy(levelSwitch)
                             .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
                             .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
                             .Enrich.FromLogContext()
                             .WriteTo.RollingFile(pathFormat: Path.Combine(AppContext.BaseDirectory, "logs\\log-{Date}.log"))
                             //.WriteTo.Stackify( restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Debug )
                             .CreateLogger();
            }
            else
            {
                Log.Logger = new LoggerConfiguration()
                             .MinimumLevel.ControlledBy(levelSwitch)
                             .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
                             .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
                             .Enrich.FromLogContext()
                             .WriteTo.Seq(seqServer)
                             //.WriteTo.Stackify( restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information )
                             .CreateLogger();
            }
            services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));

            //automapper
            services.AddAutoMapper(typeof(Startup));
            MapperRegister.Register();

            //signalr
            services.AddSignalR(p =>
            {
                p.EnableDetailedErrors  = true;
                p.ClientTimeoutInterval = TimeSpan.FromSeconds(60);
                p.HandshakeTimeout      = TimeSpan.FromSeconds(30);
                p.KeepAliveInterval     = TimeSpan.FromSeconds(15);
            });

            // 跨域
            services.AddCors(o => o.AddPolicy("AllowAllPolicy", builder =>
            {
                builder
                .SetIsOriginAllowed(origin => true)
                .WithMethods("GET", "POST", "DELETE", "OPTIONS", "PUT")
                .AllowAnyHeader()
                .AllowCredentials();
            }));

            // token
            RsaSecurityKey signingKey = CryptoHelper.CreateRsaSecurityKey();

            services.AddAuthentication();
            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters {
                    ValidateAudience         = false,
                    ValidateIssuer           = true,
                    ValidIssuer              = Configuration.GetValue <string>("IdentityServer"),
                    ValidateIssuerSigningKey = false,
                    IssuerSigningKey         = signingKey,
                    ValidateLifetime         = false
                };

                // WebSocket的Token来自QueryString
                options.Events = new JwtBearerEvents {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];
                        if (string.IsNullOrEmpty(accessToken))
                        {
                            context.Request.Query.TryGetValue("token", out accessToken);
                        }

                        // If the request is for our hub...
                        var path = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/hubs/")))
                        {
                            // Read the token out of the query string
                            context.Token = accessToken;
                        }

                        return(Task.CompletedTask);
                    }
                };
            });

            //.AddIdentityServerAuthentication( options =>
            //{
            //    options.Authority = Configuration.GetValue<string>( "IdentityServer" );
            //    options.RequireHttpsMetadata = false;// 指定是否为HTTPS

            //    options.ApiName = "api";

            //    // WebSocket的Token来自QueryString
            //    options.Events = new JwtBearerEvents {
            //        OnMessageReceived = context =>
            //        {
            //            var accessToken = context.Request.Query[ "access_token" ];
            //            if( string.IsNullOrEmpty( accessToken ) ) {
            //                context.Request.Query.TryGetValue( "token", out accessToken );
            //            }

            //            // If the request is for our hub...
            //            var path = context.HttpContext.Request.Path;
            //            if( !string.IsNullOrEmpty( accessToken ) && ( path.StartsWithSegments( "/hubs/" ) ) ) {
            //                // Read the token out of the query string
            //                context.Token = accessToken;
            //            }
            //            return Task.CompletedTask;
            //        }
            //    };
            //} );

            // permission
            services.AddAuthorization(options =>
            {
                options.AddPolicy("Permission", policyBuilder =>
                {
                    policyBuilder.Requirements.Add(new PermissionRequirement());
                    policyBuilder.RequireAuthenticatedUser();
                });
            });
            services.AddSingleton <IAuthorizationHandler, PermissionAuthorizationPolicy>();

            // api doc
            services.AddSwaggerGen(c =>
            {
                // https://localhost:44312/swagger/v1/swagger.json
                c.SwaggerDoc("v1",
                             new Microsoft.OpenApi.Models.OpenApiInfo {
                    Title       = "烽客 API",
                    Version     = "v1",
                    Description = "烽客 API 文档",
                });

                c.EnableAnnotations();

                //c.CustomOperationIds( e => $"{e.ActionDescriptor.RouteValues[ "action" ]}");
                c.CustomOperationIds(apiDesc =>
                {
                    return(apiDesc.TryGetMethodInfo(out MethodInfo methodInfo) ? methodInfo.Name : null);
                });

                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                if (File.Exists(xmlPath))
                {
                    c.IncludeXmlComments(xmlPath);
                }
                var xmlPath2 = Path.Combine(AppContext.BaseDirectory, "Syinpo.Model.xml");
                if (File.Exists(xmlPath2))
                {
                    c.IncludeXmlComments(xmlPath2);
                }

                //
                c.DescribeAllEnumsAsStrings();

                //
                //c.AddFluentValidationRules();

                //http://wmpratt.com/part-ii-swagger-and-asp-net-web-api-enabling-oauth2/
                c.OperationFilter <AuthorizeCheckOperationFilter>();

                //c.AddSecurityDefinition( "oauth2", new OAuth2Scheme {
                //    Type = "oauth2",
                //    Flow = "implicit",
                //    AuthorizationUrl = $"{Configuration.GetValue<string>( "IdentityServer" )}/connect/authorize",
                //    TokenUrl = $"{Configuration.GetValue<string>( "IdentityServer" )}/connect/token",
                //    Scopes = new Dictionary<string, string>()
                //    {
                //        { "api", "Syinpo API" }
                //    }
                //} );
            });

            // 请求限制
            services.Configure <SysOptions>(Configuration.GetSection("Sys"));
            services.Configure <CacheOptions>(Configuration.GetSection("Cache"));
            services.AddMemoryCache();

            // cache
            var cacheOptions = Configuration.GetSection("Cache").Get <CacheOptions>();

            services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = cacheOptions.RedisConfiguration;
                options.InstanceName  = cacheOptions.RedisInstanceName;
            });
            services.AddDistributedMemoryCache();


            //hangfire
            services.Configure <HangfireOptions>(Configuration.GetSection("Hangfire"));
            var hangfireOptions = Configuration.GetSection("Hangfire").Get <HangfireOptions>();


            // task
            if (hangfireOptions.UseHangfire)
            {
                string taskConnectionString = Configuration.GetConnectionString("HangfireConnection");
                services.AddHangfire(x => x.UseSqlServerStorage(taskConnectionString));
                services.AddHangfireServer();
                JobStorage.Current = new SqlServerStorage(taskConnectionString);
                HangfireRegister.Register();
            }

            // IoC & DI
            services.AddAutofac();
            var iocProvider = IoCRegister.Register(services, Configuration);

            IoC.Init(iocProvider.Item1, iocProvider.Item2);

            // task
            if (hangfireOptions.UseHangfire)
            {
                GlobalConfiguration.Configuration.UseAutofacActivator(iocProvider.Item2, false);
            }

            return(iocProvider.Item1);
        }
示例#30
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="str"></param>
 /// <returns></returns>
 public static string ToHexMd5Hash(string str)
 {
     return(CryptoHelper.ToMd5Hash(str));
 }
示例#31
0
        /// <summary>
        /// Multiple crypto currency selection list. You can accept payments in multiple crypto currencies
        /// For example you can accept payments in bitcoin, litecoin, dogecoin and use the same price in USD
        /// </summary>
        /// <param name="coins"></param>
        /// <param name="defCoin"></param>
        /// <param name="defLang"></param>
        /// <param name="iconWidth"></param>
        /// <param name="style"></param>
        /// <param name="directory"></param>
        /// <param name="anchor"></param>
        /// <returns></returns>
        public static MvcHtmlString CurrencyBox(this HtmlHelper helper, string[] coins, string defCoin = "", string defLang = "en", int iconWidth = 50,
                                                object style = null, string directory = "images", string anchor = "gourlcryptocoins")
        {
            if (style == null || style.ToString().IsEmpty())
            {
                style = new { style = "width:350px; margin: 10px 0 10px 320px;" };
            }
            if (coins.Length == 0)
            {
                return(MvcHtmlString.Empty);
            }
            defCoin = defCoin.ToLower();
            defLang = defLang.ToLower();

            if (!CryptoboxCoins.Contains(defCoin))
            {
                return(MvcHtmlString.Create("Invalid your default value " + defCoin + " in CurrencyBox"));
            }
            if (!coins.Contains(defCoin))
            {
                coins = new[] { defCoin }
            }
            ;

            var query = HttpUtility.ParseQueryString(HttpContext.Current.Request.Url.Query);

            if (HttpContext.Current.Request.QueryString["gourlcryptocoin"] != null &&
                HttpContext.Current.Request.QueryString["gourlcryptocoin"] != "")
            {
                query.Remove("gourlcryptocoin");
            }

            string url = HttpContext.Current.Request.Url.AbsoluteUri.Split(new[] { '?' })[0] +
                         "?" + query.ToString() + (query.Count > 0 ? "&" : "") + "gourlcryptocoin=";

            string lan = CryptoHelper.cryptobox_sellanguage(defLang);
            string id  = "gourlcryptocoins";

            TagBuilder divBuilder = new TagBuilder("div");

            divBuilder.MergeAttribute("id", id);
            divBuilder.MergeAttribute("align", "center");
            divBuilder.MergeAttributes(new RouteValueDictionary(style));
            divBuilder.InnerHtml = "<div style='margin - bottom:15px'><b>" + localisation[lan].Payment + " -</b></div>";

            foreach (string coin1 in coins)
            {
                string coin = coin1.ToLower();
                if (!CryptoboxCoins.Contains(coin))
                {
                    return(MvcHtmlString.Create("Invalid your submitted value coin in CurrencyBox"));
                }
                TagBuilder aBuilder = new TagBuilder("a");
                aBuilder.MergeAttribute("href", url + coin + "#" + anchor);
                TagBuilder imgBuilder = new TagBuilder("img");
                imgBuilder.MergeAttribute("style", "box-shadow:none;margin:" + Math.Round((decimal)(iconWidth / 10)) + "px " + Math.Round((decimal)(iconWidth / 7)) + "px;border:0;");
                imgBuilder.MergeAttribute("width", iconWidth.ToString());
                imgBuilder.MergeAttribute("title", localisation[lan].PayIn.Replace("%coinName%", coin1));
                imgBuilder.MergeAttribute("alt", localisation[lan].PayIn.Replace("%coinName%", coin1));
                imgBuilder.MergeAttribute("src", "/" + directory + "//" + coin + (iconWidth > 70 ? "2" : "") + ".png");
                aBuilder.InnerHtml    = imgBuilder.ToString();
                divBuilder.InnerHtml += aBuilder.ToString();
            }

            return(MvcHtmlString.Create(divBuilder.ToString()));
        }
    }
示例#32
0
        public void SynchronizationConfirmedBlockSerializerTest()
        {
            ulong syncBlockHeight = 1;
            uint  nonce           = 4;

            byte[] powHash     = BinaryBuilder.GetPowHash(1234);
            ushort version     = 1;
            ulong  blockHeight = 9;

            byte[] prevHash = BinaryBuilder.GetDefaultHash(1234);

            ushort round        = 1;
            byte   signersCount = 10;

            byte[] body = new byte[11 + Globals.NODE_PUBLIC_KEY_SIZE * signersCount + Globals.SIGNATURE_SIZE * signersCount];

            byte[][] expectedSignerPKs        = new byte[signersCount][];
            byte[][] expectedSignerSignatures = new byte[signersCount][];

            DateTime expectedDateTime = DateTime.Now;


            for (int i = 0; i < signersCount; i++)
            {
                byte[] privateSignerKey = CryptoHelper.GetRandomSeed();

                Ed25519.KeyPairFromSeed(out byte[] publicSignerKey, out byte[] expandedSignerKey, privateSignerKey);

                expectedSignerPKs[i] = publicSignerKey;

                byte[] roundBytes      = BitConverter.GetBytes(round);
                byte[] signerSignature = Ed25519.Sign(roundBytes, expandedSignerKey);

                expectedSignerSignatures[i] = signerSignature;
            }

            using (MemoryStream ms = new MemoryStream(body))
            {
                using (BinaryWriter bw = new BinaryWriter(ms))
                {
                    bw.Write(expectedDateTime.ToBinary());
                    bw.Write(round);
                    bw.Write(signersCount);

                    for (int i = 0; i < signersCount; i++)
                    {
                        bw.Write(expectedSignerPKs[i]);
                        bw.Write(expectedSignerSignatures[i]);
                    }
                }
            }

            byte[] expectedPacket = BinaryBuilder.GetSignedPacket(
                PacketType.Synchronization,
                syncBlockHeight,
                nonce, powHash, version,
                BlockTypes.Synchronization_ConfirmedBlock, blockHeight, prevHash, body, _privateKey, out byte[] expectedSignature);

            SynchronizationConfirmedBlock block = new SynchronizationConfirmedBlock()
            {
                SyncBlockHeight = syncBlockHeight,
                BlockHeight     = blockHeight,
                Nonce           = nonce,
                PowHash         = powHash,
                HashPrev        = prevHash,
                ReportedTime    = expectedDateTime,
                Round           = round,
                PublicKeys      = new byte[signersCount][],
                Signatures      = new byte[signersCount][]
            };

            for (int i = 0; i < signersCount; i++)
            {
                block.PublicKeys[i] = expectedSignerPKs[i];
                block.Signatures[i] = expectedSignerSignatures[i];
            }

            SynchronizationConfirmedBlockSerializer serializer = new SynchronizationConfirmedBlockSerializer(_cryptoService, _identityKeyProvidersRegistry, _hashCalculationRepository);

            serializer.Initialize(block);

            byte[] actualPacket = serializer.GetBytes();

            Assert.Equal(expectedPacket, actualPacket);
        }
示例#33
0
        /// <summary>
        /// Encodes the Id and Partition Key into a format suitable for a <see cref="CosmosEntity"/>
        /// </summary>
        /// <param name="channelId">A Channel Id that identifies the Bot channel, i.e. "msteams", "slack".</param>
        /// <param name="userId">The User Id provided by the Bot Channel</param>
        /// <returns>An Id, PK tuple.</returns>
        internal static (string id, string pk) EncodeIds(ConversationInfo info, string userId)
        {
            // ringo:{channel_id}:{channel_team_id.ToLower()}:user:user_id.ToLower()}
            string id = $"{RingoBotHelper.RingoBotName}:{info.ChannelId}:{info.ChannelTeamId}:user:{CryptoHelper.Base62Encode(userId)}"
                        .ToLower();

            return(id, id);
        }
 static byte[] getDefaulPassword()
 {
     return(CryptoHelper.Sha256(defaultKey));
 }
示例#35
0
 public static string GetWeopenToken(this IAccessControl ac)
 {
     return($"{ac.User.HashId}-{CryptoHelper.ComputeMD5("WEOPEN", ac.User.HashId)}");
 }
示例#36
0
        private ContractTester(IAbpApplicationWithInternalServiceProvider application, ECKeyPair keyPair)
        {
            application.Services.AddTransient(o =>
            {
                var mockService = new Mock <IAccountService>();
                mockService.Setup(a => a.SignAsync(It.IsAny <byte[]>())).Returns <byte[]>(data =>
                                                                                          Task.FromResult(CryptoHelper.SignWithPrivateKey(keyPair.PrivateKey, data)));

                mockService.Setup(a => a.GetPublicKeyAsync()).ReturnsAsync(keyPair.PublicKey);

                return(mockService.Object);
            });

            Application = application;

            KeyPair = keyPair;
        }
示例#37
0
 public ActionResult ResetPassword(string email)
 {
     var ar = new AgenziaRepository();
     var agency = ar.GetByEmail(email);
     if (agency != null)
     {
         CryptoHelper cryptoHelper = new CryptoHelper();
         var random = new Random();
         var password = random.Next().ToString();
         agency.Password = cryptoHelper.CryptPassword(password);
         ar.Save(agency);
         var mailerHelper = new MailerHelper();
         var text = string.Format("Gentile {0} la tua nuova password di Parti Comodo è: {1}", agency.Nome, password);
         mailerHelper.SendMail(email, text);
     }
     var viewModel = new RegisterViewModel();
     return View("Register", viewModel);
 }
示例#38
0
        public ContractTester(int chainId, ECKeyPair keyPair)
        {
            var sampleKeyPairs = SampleECKeyPairs.KeyPairs.Take(3).ToList();

            InitialMinerList.AddRange(sampleKeyPairs);
            KeyPair = keyPair ?? InitialMinerList[1];

            Application =
                AbpApplicationFactory.Create <TContractTestAElfModule>(options =>
            {
                options.UseAutofac();
                if (chainId != 0)
                {
                    options.Services.Configure <ChainOptions>(o => { o.ChainId = chainId; });
                }

                options.Services.Configure <ConsensusOptions>(o =>
                {
                    var miners = new List <string>();

                    foreach (var minerKeyPair in InitialMinerList)
                    {
                        miners.Add(minerKeyPair.PublicKey.ToHex());
                    }

                    o.InitialMinerList = miners;
                    o.MiningInterval   = 4000;
                    o.StartTimestamp   = new Timestamp {
                        Seconds = 0
                    };
                });

                if (keyPair != null)
                {
                    options.Services.AddTransient(o =>
                    {
                        var mockService = new Mock <IAccountService>();
                        mockService.Setup(a => a.SignAsync(It.IsAny <byte[]>())).Returns <byte[]>(data =>
                                                                                                  Task.FromResult(CryptoHelper.SignWithPrivateKey(KeyPair.PrivateKey, data)));

                        mockService.Setup(a => a.GetPublicKeyAsync()).ReturnsAsync(KeyPair.PublicKey);

                        return(mockService.Object);
                    });
                }
            });

            Application.Initialize();
        }
示例#39
0
        private static ImmutableDictionary<string, string> GetRandomImageOptions(int numberOfOptions)
        {
            var randomOptions = ImmutableDictionary.CreateBuilder<string, string>();
            var availableOptions = Assets.Images.ToList();

            var crypto = new CryptoHelper();
            for (var i = 0; i < numberOfOptions; i++)
            {
                var randomItem = availableOptions[crypto.GetRandomIndex(availableOptions.Count)];
                randomOptions.Add(randomItem.Key, crypto.GetRandomString(20));

                availableOptions.Remove(randomItem); // We don't want duplicate entries
            }

            return randomOptions.ToImmutable();
        }
 private static XmlTextReader GetXmlTextReader(string path, string AssemblyName)
 {
     XmlTextReader reader = null;
     string str = Path.Combine(path, AssemblyName + ".cfg.cxml");
     if (File.Exists(str))
     {
         CryptoHelper helper = new CryptoHelper(CryptoTypes.encTypeDES);
         return helper.GetDecryptXmlReader(str);
     }
     str = Path.Combine(path, AssemblyName + ".cfg.xml");
     if (File.Exists(str))
     {
         reader = new XmlTextReader(str);
     }
     return reader;
 }
示例#41
0
 public static CryptoHelper getInstance()
 {
     if (CryptoHelper.instance == null)
     {
         CryptoHelper.instance = new CryptoHelper();
     }
     return CryptoHelper.instance;
 }
示例#42
0
 public static string Decrypt(string encryptedText, string key)
 {
     CryptoHelper helper = new CryptoHelper(key);
     return helper.Decrypt(encryptedText);
 }
示例#43
0
 public static String HashPassword(String password, String salt)
 {
     return(CryptoHelper.GenerateBase64Hash(CryptoHelper.GenerateBase64Hash(password) + salt + Security.PASSWORDSALT));
 }
示例#44
0
        public void RandomByteArrayGenerate_Test()
        {
            var byteArray1 = CryptoHelper.RandomFill(30);

            byteArray1.Length.ShouldBe(30);
        }
示例#45
0
        public override AsymmetricSignatureFormatter GetSignatureFormatter(string algorithm)
        {
            // One can sign only if the private key is present.
            if (PrivateKey == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.MissingPrivateKey));
            }

            if (string.IsNullOrEmpty(algorithm))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(algorithm, SR.Format(SR.EmptyOrNullArgumentString, nameof(algorithm)));
            }

            // We support:
            //     XmlDsigDSAUrl = "http://www.w3.org/2000/09/xmldsig#dsa-sha1";
            //     XmlDsigRSASHA1Url = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
            //     RsaSha256Signature = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
            AsymmetricAlgorithm privateKey = PrivateKey;

            object algorithmObject = CryptoHelper.GetAlgorithmFromConfig(algorithm);

            if (algorithmObject != null)
            {
                SignatureDescription description = algorithmObject as SignatureDescription;
                if (description != null)
                {
                    return(description.CreateFormatter(privateKey));
                }

                try
                {
                    AsymmetricSignatureFormatter asymmetricSignatureFormatter = algorithmObject as AsymmetricSignatureFormatter;
                    if (asymmetricSignatureFormatter != null)
                    {
                        asymmetricSignatureFormatter.SetKey(privateKey);
                        return(asymmetricSignatureFormatter);
                    }
                }
                catch (InvalidCastException e)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.AlgorithmAndPrivateKeyMisMatch, e));
                }

                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.Format(SR.UnsupportedAlgorithmForCryptoOperation,
                                                                                                               algorithm, nameof(GetSignatureFormatter))));
            }

            switch (algorithm)
            {
            case SignedXml.XmlDsigDSAUrl:

                // Ensure that we have a DSA algorithm object.
                DSA dsa = (PrivateKey as DSA);
                if (dsa == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.PrivateKeyNotDSA));
                }
#pragma warning disable CA5351 // Do Not Use Broken Cryptographic Algorithms
                return(new DSASignatureFormatter(dsa));

#pragma warning restore CA5351 // Do Not Use Broken Cryptographic Algorithms

            case SignedXml.XmlDsigRSASHA1Url:
                // Ensure that we have an RSA algorithm object.
                RSA rsa = (PrivateKey as RSA);
                if (rsa == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.PrivateKeyNotRSA));
                }

                return(new RSAPKCS1SignatureFormatter(rsa));

            case SecurityAlgorithms.RsaSha256Signature:
                // Ensure that we have an RSA algorithm object.
                RSA rsaSha256 = (privateKey as RSA);
                if (rsaSha256 == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.PrivateKeyNotRSA));
                }

                return(new RSAPKCS1SignatureFormatter(rsaSha256));

            default:
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnsupportedCryptoAlgorithm, algorithm)));
            }
        }
        /// <summary>
        /// TODO: Comment
        /// </summary>
        public void ShowPasswordExcecute(int? selectedID)
        {
            //TODO: Save path in configuration
            string configurationPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                "SecureVault",
                "settings",
                "configuration.dat");

            ConfigurationHelper configHelper = new ConfigurationHelper(configurationPath);
            KeyHelper keyHelper = new KeyHelper();
            SecureStringHelper secureStringHelper = new SecureStringHelper();

            byte[] key = keyHelper.DeriveKey(secureStringHelper.SecureStringToString(this.Password), configHelper.GetSalt());

            CryptoHelper cryptoHelper = new CryptoHelper(key, Convert.FromBase64String(this.SavedData[selectedID.Value].Salt));

            string decryptedValue = cryptoHelper.DecryptValue(this.SavedData[selectedID.Value].EncryptedValue);

            this.DecryptedPassword = decryptedValue;
        }
示例#47
0
 public override bool IsSymmetricAlgorithm(string algorithm)
 {
     return(CryptoHelper.IsSymmetricAlgorithm(algorithm));
 }
示例#48
0
            public static string Encrypt(string clearText, string key)
            {
                CryptoHelper helper = new CryptoHelper(key);

                return(helper.Encrypt(clearText));
            }
示例#49
0
 public UserController(IUserService service, CryptoHelper cryptoHelper, IUmsFacade umsFacade)
 {
     _service      = service;
     _cryptoHelper = cryptoHelper;
     _umsFacade    = umsFacade;
 }
示例#50
0
            public static string Decrypt(string encryptedText, string key)
            {
                CryptoHelper helper = new CryptoHelper(key);

                return(helper.Decrypt(encryptedText));
            }
    /// <summary>
    /// Creates the response for a implicit flow request
    /// </summary>
    /// <param name="request"></param>
    /// <param name="authorizationCode"></param>
    /// <returns></returns>
    protected virtual async Task <AuthorizeResponse> CreateImplicitFlowResponseAsync(ValidatedAuthorizeRequest request, string authorizationCode = null)
    {
        Logger.LogDebug("Creating Implicit Flow response.");

        string accessTokenValue    = null;
        int    accessTokenLifetime = 0;

        var responseTypes = request.ResponseType.FromSpaceSeparatedString();

        if (responseTypes.Contains(OidcConstants.ResponseTypes.Token))
        {
            var tokenRequest = new TokenCreationRequest
            {
                Subject = request.Subject,
                // implicit responses do not allow resource indicator, so no resource indicator filtering needed here
                ValidatedResources = request.ValidatedResources,

                ValidatedRequest = request
            };

            var accessToken = await TokenService.CreateAccessTokenAsync(tokenRequest);

            accessTokenLifetime = accessToken.Lifetime;

            accessTokenValue = await TokenService.CreateSecurityTokenAsync(accessToken);
        }

        string jwt = null;

        if (responseTypes.Contains(OidcConstants.ResponseTypes.IdToken))
        {
            string stateHash = null;

            if (Options.EmitStateHash && request.State.IsPresent())
            {
                var credential = await KeyMaterialService.GetSigningCredentialsAsync(request.Client.AllowedIdentityTokenSigningAlgorithms);

                if (credential == null)
                {
                    throw new InvalidOperationException("No signing credential is configured.");
                }

                var algorithm = credential.Algorithm;
                stateHash = CryptoHelper.CreateHashClaimValue(request.State, algorithm);
            }

            var tokenRequest = new TokenCreationRequest
            {
                ValidatedRequest   = request,
                Subject            = request.Subject,
                ValidatedResources = request.ValidatedResources,
                Nonce = request.Raw.Get(OidcConstants.AuthorizeRequest.Nonce),
                IncludeAllIdentityClaims = !request.AccessTokenRequested,
                AccessTokenToHash        = accessTokenValue,
                AuthorizationCodeToHash  = authorizationCode,
                StateHash = stateHash
            };

            var idToken = await TokenService.CreateIdentityTokenAsync(tokenRequest);

            jwt = await TokenService.CreateSecurityTokenAsync(idToken);
        }

        var response = new AuthorizeResponse
        {
            Request             = request,
            AccessToken         = accessTokenValue,
            AccessTokenLifetime = accessTokenLifetime,
            IdentityToken       = jwt,
            SessionState        = request.GenerateSessionStateValue()
        };

        return(response);
    }
 public TestEncyptionController()
 {
     var salt = "testSaltString";
     cryptoHelper= new CryptoHelper(salt);
 }
示例#53
0
        public override AsymmetricSignatureDeformatter GetSignatureDeformatter(string algorithm)
        {
            // We support one of the two algoritms, but not both.
            //     XmlDsigDSAUrl = "http://www.w3.org/2000/09/xmldsig#dsa-sha1";
            //     XmlDsigRSASHA1Url = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";

            if (string.IsNullOrEmpty(algorithm))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(algorithm, SR.Format(SR.EmptyOrNullArgumentString, nameof(algorithm)));
            }

            object algorithmObject = CryptoHelper.GetAlgorithmFromConfig(algorithm);

            if (algorithmObject != null)
            {
                SignatureDescription description = algorithmObject as SignatureDescription;
                if (description != null)
                {
                    return(description.CreateDeformatter(PublicKey));
                }

                try
                {
                    AsymmetricSignatureDeformatter asymmetricSignatureDeformatter = algorithmObject as AsymmetricSignatureDeformatter;
                    if (asymmetricSignatureDeformatter != null)
                    {
                        asymmetricSignatureDeformatter.SetKey(PublicKey);
                        return(asymmetricSignatureDeformatter);
                    }
                }
                catch (InvalidCastException e)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.AlgorithmAndPublicKeyMisMatch, e));
                }

                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.Format(SR.UnsupportedAlgorithmForCryptoOperation,
                                                                                                               algorithm, nameof(GetSignatureDeformatter))));
            }

            switch (algorithm)
            {
            case SignedXml.XmlDsigDSAUrl:

                // Ensure that we have a DSA algorithm object.
                DSA dsa = (PublicKey as DSA);
                if (dsa == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.PublicKeyNotDSA));
                }

                return(new DSASignatureDeformatter(dsa));

            case SignedXml.XmlDsigRSASHA1Url:
            case SecurityAlgorithms.RsaSha256Signature:
                // Ensure that we have an RSA algorithm object.
                RSA rsa = (PublicKey as RSA);
                if (rsa == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.PublicKeyNotRSA));
                }

                return(new RSAPKCS1SignatureDeformatter(rsa));

            default:
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnsupportedCryptoAlgorithm, algorithm)));
            }
        }
示例#54
0
 public static string Encrypt(string clearText, string key)
 {
     CryptoHelper helper = new CryptoHelper(key);
     return helper.Encrypt(clearText);
 }
示例#55
0
        /// <summary>
        /// Handles the Click event of the SendPasswordBtn control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void SendPasswordBtn_Click( object sender, EventArgs e )
        {
            if ( email.Text == string.Empty ) {
                Message.Text = "Please enter you email address";
                Message.TextKey = "SIGNIN_ENTER_EMAIL_ADDR";
                return;
            }
            // generate random password
            string randomPassword = RandomPassword.Generate( 8, 10 );

            CryptoHelper crypthelp = new CryptoHelper();
            UsersDB usersDB = new UsersDB();

            //Obtain single row of User information
            AppleseedUser user = usersDB.GetSingleUser( email.Text, this.PortalSettings.PortalAlias );

            if ( user != null ) {

                string Pswrd;
                string AppName = this.PortalSettings.PortalName;
                bool encrypted = Config.EncryptPassword;
                string Name = user.Email;
                if ( encrypted ) {
                    Pswrd = randomPassword;
                    crypthelp.ResetPassword( Name, randomPassword );
                }
                else {
                    Pswrd = user.GetPassword();
                }
                crypthelp.ResetPassword( Name, randomPassword );
                string LoginUrl = Path.ApplicationFullPath + "DesktopModules/Admin/Logon.aspx?Usr="******"&Pwd=" +
                                  Pswrd + "&Alias=" + this.PortalSettings.PortalAlias;
                MailMessage mail = new MailMessage();

                // [email protected]
                // Date 19 March 2003
                // We have to use a correct sender address,
                // because most SMTP servers reject it otherwise
                //jes1111 - mail.From = ConfigurationSettings.AppSettings["EmailFrom"].ToString();
                mail.From = Config.EmailFrom;
                mail.To = email.Text;
                mail.Subject = AppName + " - " + General.GetString( "SIGNIN_SEND_PWD", "Send me password", this );

                StringBuilder sb = new StringBuilder();

                sb.Append( Name );
                sb.Append( "," );
                sb.Append( "\r\n\r\n" );
                sb.Append( General.GetString( "SIGNIN_PWD_REQUESTED", "This is the password you requested", this ) );
                sb.Append( " " );
                sb.Append( Pswrd );
                sb.Append( "\r\n\r\n" );
                sb.Append( General.GetString( "SIGNIN_THANK_YOU", "Thanks for your visit.", this ) );
                sb.Append( " " );
                sb.Append( AppName );
                sb.Append( "\r\n\r\n" );
                sb.Append( General.GetString( "SIGNIN_YOU_CAN_LOGIN_FROM", "You can login from", this ) );
                sb.Append( ":" );
                sb.Append( "\r\n" );
                sb.Append( Path.ApplicationFullPath );
                sb.Append( "\r\n\r\n" );
                sb.Append( General.GetString( "SIGNIN_USE_DIRECT_URL", "Or using direct url", this ) );
                sb.Append( "\r\n" );
                sb.Append( LoginUrl );
                sb.Append( "\r\n\r\n" );
                sb.Append(
                    General.GetString( "SIGNIN_URL_WARNING",
                                      "NOTE: The address above may not show up on your screen as one line. This would prevent you from using the link to access the web page. If this happens, just use the 'cut' and 'paste' options to join the pieces of the URL.",
                                      this ) );

                mail.Body = sb.ToString();
                mail.BodyFormat = MailFormat.Text;

                SmtpMail.SmtpServer = Config.SmtpServer;
                SmtpMail.Send( mail );

                Message.Text =
                    General.GetString( "SIGNIN_PWD_WAS_SENT", "Your password was sent to the addess you provided",
                                      this );
                Message.TextKey = "SIGNIN_PWD_WAS_SENT";
            }
            else {
                Message.Text =
                    General.GetString( "SIGNIN_PWD_MISSING_IN_DB",
                                      "The email you specified does not exists on our database", this );
                Message.TextKey = "SIGNIN_PWD_MISSING_IN_DB";
            }
        }