public async Task <CommandResult> Handle(AuthenticateUserCommand request, CancellationToken cancellationToken) { var stopwatch = new Stopwatch(); stopwatch.Start(); var user = await _entitiesRepository.GetFirstOrDefaultAsync <User>(u => u.Username == request.Username.ToLower()); if (user != null) { if (!user.IsDisabled) { if (SecurityUtility.IsMatchingHash(request.Password, user.HashedPassword, user.Salt)) { return(new CommandResult() { ObjectRefId = user.Username, ElapsedMs = stopwatch.ElapsedMilliseconds, Type = CommandResultTypes.None }); } } } return(new CommandResult() { ElapsedMs = stopwatch.ElapsedMilliseconds, ObjectRefId = null, Type = CommandResultTypes.None }); }
protected override bool CheckSignature() { List <string> list = new List <string>(); list.Add(PublicToken); list.Add(Timestamp); list.Add(Nonce); //排序 list.Sort(); //拼串 string input = string.Empty; foreach (var item in list) { input += item; } //加密 string new_signature = SecurityUtility.SHA1Encrypt(input); log.Info("new_signature : " + new_signature); //验证 if (new_signature == Signature) { return(true); } else { return(false); } }
public ConfirmationResponse Execute(ChangePasswordRequest request) { request.ThrowExceptionIfInvalid(); if (request.ForUserId != Identity.FromString(request.UserId)) { throw new UseCaseException("Can't change data of another user."); } var entity = _personRepository.Read(request.ForUserId); var person = _personRepository.FindByEmailAndPasswordHash(entity.Email, SecurityUtility.HashPassword(request.OldPassword)); if (person == null) { request.Errors.Add("", "Old password is invalid."); throw new InvalidRequestException { Errors = request.Errors }; } person.PasswordHash = SecurityUtility.HashPassword(request.NewPassword); _personRepository.ChangePassword(person); return(new ConfirmationResponse("Password changed successfully.") { Id = person.Id, }); }
public ActionResult Edit(NewsModel news) { try { int userId = -1; if (Session["UserId"] != null) { userId = int.Parse(Session["UserID"].ToString()); } BLLNews bll = new BLLNews(); NewsInfo newsObjest = new NewsInfo() { NewId = news.NewId, Title = news.Title, Content = SecurityUtility.RemoveIllegalCharacters(news.Message), CreateDate = DateTime.Now, IsDelete = false, IsTop = false, IsPublic = true, ViewTimes = 0, UserId = userId, ImageUrl = "" }; //编辑信息 之后提交更新 bll.Update(newsObjest); return(RedirectToAction("Index", "News")); } catch (Exception) { return(View()); } }
public override bool ChangePassword(string username, string oldPassword, string newPassword) { oldPassword = oldPassword.Trim(); if (!SecurityUtility.IsPasswordValid(newPassword)) { return(false); } var user = SecurityUtility.GetUserByUsername(username); if (user == null) { return(false); } var feedbackMessage = new System.Text.StringBuilder(); if (user.Password != oldPassword && user.Password != Cryptography.EncryptPassword(oldPassword, user.Salt)) { return(false); } user.Password = Cryptography.EncryptPassword(newPassword, user.Salt); IRepositoryProvider _repositoryProvider = new RepositoryProvider(new RepositoryFactories()); var unitofWork = new UnitOfWork(new MisukaDBContext(), _repositoryProvider); unitofWork.Repository <Domain.Entity.User>().Update(user); var ret = unitofWork.SaveChanges(); return(ret > 0); }
private bool IsValid(string license) { try { if (string.IsNullOrEmpty(license)) { throw new ArgumentNullException(); } var request = new ValidateRequest { License = license, FingerPrint = SecurityUtility.GetMd5Hash(AppConfigUtility.FingerPrint) }; var response = WebServiceUtility.Post(AppConfigUtility.ValidateLicenseUrl, request.ToJSON()); if (!response.Success) { throw new LicenseNotValidException(response.Message); } return(true); } catch (LicenseNotValidException) { throw; } catch (Exception ex) { LogUtility.Log(LogUtility.LogType.SystemError, MethodBase.GetCurrentMethod().Name, ex.Message); return(false); } }
/// <summary> /// 检查签名 /// </summary> /// <param name="request"></param> /// <returns></returns> private bool CheckSignature() { string signature = Request.QueryString[SIGNATURE]; string timestamp = Request.QueryString[TIMESTAMP]; string nonce = Request.QueryString[NONCE]; List <string> list = new List <string>(); list.Add(TOKEN); list.Add(timestamp); list.Add(nonce); //排序 list.Sort(); //拼串 string input = string.Empty; foreach (var item in list) { input += item; } //加密 string new_signature = SecurityUtility.SHA1Encrypt(input); //验证 if (new_signature == signature) { return(true); } else { return(false); } }
public async void CreateStepWithSecret() { Mock <IEntitiesRepository> entitiesRepository = new Mock <IEntitiesRepository>(); entitiesRepository.Setup(sr => sr.GetFirstOrDefaultAsync <StepTemplate>(It.IsAny <Expression <Func <StepTemplate, bool> > >())).Returns(Task.FromResult(SecretSampleData.StepTemplate)); var stepTemplate = await entitiesRepository.Object.GetFirstOrDefaultAsync <StepTemplate>(st => st.ReferenceId == SecretSampleData.StepTemplate.ReferenceId); var newStep = stepTemplate.GenerateStep(stepTemplate.ReferenceId, "", "", "", new Dictionary <string, object>() { { "secret", "This is a test" } }, null, null, ClusterStateService.GetEncryptionKey()); _node.Setup(n => n.Handle(It.IsAny <AddShardWriteOperation>())).Returns(Task.FromResult(new AddShardWriteOperationResponse() { IsSuccessful = true })); var handler = new CreateStepCommandHandler(entitiesRepository.Object, clusterMoq.Object, _node.Object); var step = await handler.Handle(new CreateStepCommand() { StepTemplateId = stepTemplate.ReferenceId, Inputs = new Dictionary <string, object>() { { "secret", "This is a test" } } }, new System.Threading.CancellationToken()); //Test encryption of step worked Assert.NotEqual("This is a test", (string)step.Result.Inputs["secret"]); //Test decryption of step Assert.Equal("This is a test", SecurityUtility.SymmetricallyDecrypt((string)step.Result.Inputs["secret"], ClusterStateService.GetEncryptionKey())); }
public override bool ValidateUser(string username, string password) { password = password.Trim(); var user = SecurityUtility.GetUserByUsername(username); if (user != null) { //// if (!user.Active || user.AccountLocked) //if (user.Locked) // return false; if (SecurityUtility.IsPasswordEqual(password, user.Password, user.Salt)) { //Stored valid logged user to session new UserSession(user); user.LastLoginTime = DateTime.Now; user.FailedLoginTimes = 0; SecurityUtility.UpdateUserInformation(user); return(true); } user.LastLoginTime = DateTime.Now; user.FailedLoginTimes++; SecurityUtility.UpdateUserInformation(user); } return(false); }
internal virtual void SaveAuthenticatedIdentity() { if (SessionData == null) { return; } Principal = CreatePrincipal(); if (Context != null) { Context.User = Principal; } if (SessionData.Saved) { return; } SessionData.Saved = true; if (Context != null) { AuthenticationCookieManager.Save(SessionData.Username, Context); } SessionData.RoleIds = SecurityUtility.GetRoleIds(SessionData.UserId); SessionData.IsAdministrator = SessionData.RoleIds != null && SessionData.RoleIds.Contains(SystemConfiguration.Instance.SecuritySettings.AdministratorRole); SessionObjectStorageStrategy.Save(SessionData); }
public async Task <IActionResult> Login(LoginViewModel vm) { if (!ModelState.IsValid) { return(View(vm)); } var repository = _repositoryProvider.Person; var person = repository.FindByEmailAndPasswordHash(vm.Email, SecurityUtility.HashPassword(vm.Password)); if (person != null) { var claims = new List <Claim> { new Claim(ClaimTypes.Name, person.DisplayName), new Claim(ClaimTypes.NameIdentifier, person.Id.ToPresentationIdentity()) }; var userIdentity = new ClaimsIdentity(claims, "SecureLogin"); var userPrincipal = new ClaimsPrincipal(userIdentity); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddMinutes(20), IsPersistent = false, AllowRefresh = false }); return(RedirectToAction(nameof(Index))); } MessageHandler(MessageType.Error, "Username or password is invalid."); return(View()); }
/// <summary> /// Saves keys /// </summary> private void OnSaveCommand() { // check app sid length if (this.AppSidText.Length != 36) { DialogManager.ShowErrorDialog("Incorrect APP SID length! APP SID should be 36 symbols length."); return; } // check app key length if (this.AppKeyText.Length != 32) { DialogManager.ShowErrorDialog("Incorrect APP KEY length! APP KEY should be 32 symbols length."); return; } // update keys to provide new values CoreApi.UpdateKeys(this.AppKeyText, this.AppSidText); // encrypt keys and save in settings byte[] encryptedAppKey = SecurityUtility.Encrypt(Encoding.UTF8.GetBytes(this.AppKeyText)); byte[] encryptedAppSid = SecurityUtility.Encrypt(Encoding.UTF8.GetBytes(this.AppSidText)); UserSettingsUtility.SaveCredentials(encryptedAppKey, encryptedAppSid); this.view.Close(); }
public async Task <FunctionSecrets> GetFunctionSecretsAsync(string functionName) { FunctionSecrets secrets; string secretFilePath = GetFunctionSecretsFilePath(functionName); if (FileSystemHelpers.FileExists(secretFilePath)) { // load the secrets file string secretsJson = await FileSystemHelpers.ReadAllTextFromFileAsync(secretFilePath); secrets = JsonConvert.DeserializeObject <FunctionSecrets>(secretsJson); } else { // initialize with new secrets and save it secrets = new FunctionSecrets { Key = SecurityUtility.GenerateSecretString() }; FileSystemHelpers.EnsureDirectory(Path.GetDirectoryName(secretFilePath)); await FileSystemHelpers.WriteAllTextToFileAsync(secretFilePath, JsonConvert.SerializeObject(secrets, Formatting.Indented)); } secrets.TriggerUrl = String.Format(@"https://{0}/api/{1}?code={2}", System.Environment.GetEnvironmentVariable("WEBSITE_HOSTNAME") ?? "localhost", functionName, secrets.Key); return(secrets); }
protected string Security(SecurityMode securityMode, string source) { switch (_securityComponentMode) { case SecurityComponentMode.Base64: _securityUtility = new Base64Helper(); break; case SecurityComponentMode.DES: _securityUtility = new DESHelper(); break; case SecurityComponentMode.MD5: _securityUtility = new MD5Helper(); break; case SecurityComponentMode.RSACryption: _securityUtility = new RSACryptionHelper(_privateKey, _publicKey); break; case SecurityComponentMode.TripleDES: _securityUtility = new TripleDESHelper(); break; default: break; } return(_securityUtility.SecurityUtilityInvoke(securityMode).Invoke(source)); }
public void Register(RegisterCommand command) { ISecurityUtility securityUtility = new SecurityUtility(); ThrowError.Against <ArgumentException>(string.IsNullOrEmpty(command.UserName), String.Format(ErrorMessage.IsRequired, "Tên đăng nhập")); ThrowError.Against <ArgumentException>(string.IsNullOrEmpty(command.Password), String.Format(ErrorMessage.IsRequired, "Mật khẩu")); var user = securityUtility.GetUserByUsername(command.UserName); ThrowError.Against <ArgumentException>(user != null, String.Format(ErrorMessage.Exists, "Tên đăng nhập")); ThrowError.Against <ArgumentException>(_personService.Query(t => t.Email == command.Email).Select().Any(), String.Format(ErrorMessage.Exists, "Email")); // ThrowError.Against<ArgumentException>(!securityUtility.IsPasswordValid(command.Password), String.Format(ErrorMessage.IsPassword)); var person = new Person() { Email = command.Email, FullName = command.FullName, PersonId = Guid.NewGuid() }; user = new User() { Type = command.Type, UserName = command.UserName, CreationDate = DateTime.Now, Locked = false, PersonId = person.PersonId, Password = Cryptography.EncryptPassword(command.Password, "") }; _unitOfWork.Repository <Domain.Entity.User>().Insert(user); _personService.Insert(person); _unitOfWork.SaveChanges(); }
public async Task <CommandResult> Handle(CreateUserCommand request, CancellationToken cancellationToken) { var stopwatch = new Stopwatch(); stopwatch.Start(); var salt = SecurityUtility.GenerateSalt(128); Guid id = Guid.NewGuid(); var createdUser = await _entitiesRepository.Insert(new Domain.Entities.Users.User( request.Username.ToLower(), SecurityUtility.OneWayHash(request.Password, salt), request.Username.ToLower(), salt, request.CreatedBy, DateTime.UtcNow, id )); return(new CommandResult() { ElapsedMs = stopwatch.ElapsedMilliseconds, ObjectRefId = id.ToString(), Type = CommandResultTypes.Create }); }
// Retrieves the user record private DataSet Retrieve(string sUserName, string sPassword) { DataSet dsUser = new DataSet(); DataTable dtUser = new DataTable(); DataRow drUser; string sPasswordSalt; // Since the Northwind database does not have a user table, just generate the dataset // Add the columns to the table dtUser.Columns.Add(FN_USER_NAME); dtUser.Columns.Add(FN_PASSWORD_ENCODED); dtUser.Columns.Add(FN_PASSWORD_SALT); dtUser.Columns.Add(FN_STATUS); // Add the data to the row drUser = dtUser.NewRow(); drUser[FN_USER_NAME] = "DeborahK"; sPasswordSalt = SecurityUtility.ComputeSalt(); drUser[FN_PASSWORD_ENCODED] = SecurityUtility.ComputeHash(sPasswordSalt + sPassword); drUser[FN_PASSWORD_SALT] = sPasswordSalt; drUser[FN_STATUS] = STATUS_ACTIVE; //Add the row to the table dtUser.Rows.Add(drUser); // Add the table to the dataset dsUser.Tables.Add(dtUser); // Set the table name dsUser.Tables[0].TableName = TN_USER; return(dsUser); }
public void UtilityTest() { var admin = SecurityUtility.EncryptAndEncode("admin"); Assert.True(SecurityUtility.DecodeAndDecrypt(admin) == "admin"); Assert.True(SecurityUtility.DecodeAndDecrypt("4eIVszyvsMJErvFLw/kxJg==") == "admin"); }
/// <summary> /// Initializes the change groups dialog with current user group settings /// </summary> private void InitializeChangeGroupsDialog() { AvailableGroups.Items.Clear(); SelectedGroups.Items.Clear(); IList <Group> managableGroups = SecurityUtility.GetManagableGroups(); IList <string> subscriptionGroups = new List <string>(); foreach (Group group in managableGroups) { if (group.SubscriptionPlans != null && group.SubscriptionPlans.Count > 0) { if (_User.IsInGroup(group.Id)) { subscriptionGroups.Add(group.Name); PHSubscriptionGroups.Controls.Add(new LiteralControl(string.Format("<option disabled='disabled'>{0}</option>", group.Name))); } } else { ListItem newItem = new ListItem(group.Name, group.Id.ToString()); bool groupSelected = _User.IsInGroup(group.Id); if (groupSelected) { SelectedGroups.Items.Add(newItem); } else { AvailableGroups.Items.Add(newItem); } } } phMyGroupsWarning.Visible = (_UserId == AbleContext.Current.UserId); SubscriptionGroupLI.Visible = subscriptionGroups.Count > 0; }
private static RemoteMethodInfo GetRemoteMethod(MethodInfo method) { string serviceKey = SecurityUtility.HashObject(method.DeclaringType); RemoteMethodAttribute rmAttribute = method.GetCustomAttributes(typeof(RemoteMethodAttribute), true)[0] as RemoteMethodAttribute; return(new RemoteMethodInfo(SecurityUtility.HashObject(method), serviceKey, method.Name, rmAttribute.Description, rmAttribute.Offline, method, String.Empty)); }
protected void Page_Init(object sender, System.EventArgs e) { // locate group to delete _GroupId = AlwaysConvert.ToInt(Request.QueryString["GroupId"]); Group group = GroupDataSource.Load(_GroupId); if (group == null) { Response.Redirect("Default.aspx"); } // groups managed by the application cannot be deleted if (group.IsReadOnly) { Response.Redirect("Default.aspx"); } // ensure user has permission to edit this group IList <Group> managableGroups = SecurityUtility.GetManagableGroups(); if (managableGroups.IndexOf(group) < 0) { Response.Redirect("Default.aspx"); } Caption.Text = string.Format(Caption.Text, group.Name); InstructionText.Text = string.Format(InstructionText.Text, group.Name); BindGroups(group); }
/// <summary> /// Encodes the invoke. /// </summary> /// <param name="method">The method.</param> /// <param name="parameter">The parameter.</param> /// <param name="encryptKey">The encrypt key.</param> /// <param name="package">The package.</param> public static void EncodeInvoke(MethodInfo method, object parameters, string encryptKey, ref NetworkInvokePackage package) { package.Context[METHOD] = serializer.Serialize <MethodInfo>(method); package.Context[METHOD_NAME] = serializer.Serialize <string>(method.Name); package.Context[METHOD_ISGENERIC] = method.IsGenericMethod; package.Context[METHOD_PARAMETERS] = SecurityUtility.DESEncrypt(serializer.Serialize <object>(parameters), encryptKey); package.Context[METHOD_INVOKEINFO] = SecurityUtility.DESEncrypt(serializer.Serialize <MethodInvokeInfo>(new MethodInvokeInfo(method)), encryptKey); }
private void AuthorizeClientWithBotId(HttpClient client) { _nonce++; var nonceKey = SecurityUtility.RsaEncryptWithPrivate("" + _nonce, keyPair.PrivateKey); client.DefaultRequestHeaders.Add("BotKey", _botId); client.DefaultRequestHeaders.Add("Nonce", nonceKey); }
private static void SaveStringValue(string key, string finalValue) { string encrypedKey = Use_Encrypt ? SecurityUtility.GetInstance().EncryptString(key) : key; string encryptedValue = Use_Encrypt ? CombineEncryptKeyAndValue(key, finalValue) : finalValue; PlayerPrefs.SetString(encrypedKey, encryptedValue); PlayerPrefs.Save(); }
public static CollectionOfConnectStrings EncrpytConnectionString(string key, CollectionOfConnectStrings connectStrings) { connectStrings.ReadOnlyConnectionString = SecurityUtility.EncryptString(key, connectStrings.ReadOnlyConnectionString); return(connectStrings); }
public BotClient(BotClientOptions options) { _url = options.Url; _nonce = 0; keyPair = SecurityUtility.GenerateRSAKeyPair(2048); var result = RegisterBot(options.Name, keyPair.PublicKey).GetAwaiter().GetResult(); _botId = result.IdKey; }
public BotClient(string botName, string url) { _url = url; _nonce = 0; keyPair = SecurityUtility.GenerateRSAKeyPair(2048); var result = RegisterBot(botName, keyPair.PublicKey).GetAwaiter().GetResult(); _botId = result.IdKey; }
public static SecurityUtility GetInstance() { if (instance == null) { instance = new SecurityUtility(); instance.offset = Random.Range(0, 100000); } return(instance); }
public Step GenerateStep(string stepTemplateId, string createdBy, string name = "", string description = "", Dictionary <string, object> inputs = null, List <string> stepTestTemplateIds = null, Guid?workflowId = null, string encryptionKey = "", Guid?executionTemplateId = null, Guid?executionScheduleId = null) { var verifiedInputs = new Dictionary <string, object>(); if (inputs != null) { if (inputs.Count() > InputDefinitions.Count() && !AllowDynamicInputs) { throw new InvalidStepInputException("Too many step inputs for step template " + Id + " were given, expected " + InputDefinitions.Count() + " got " + inputs.Count()); } if (InputDefinitions.Count() > inputs.Count()) { string missingInputs = ""; foreach (var id in InputDefinitions) { if (!inputs.Select(i => i.Key).Contains(id.Key)) { inputs.Add(id.Key, null); //missingInputs += id.Key + " "; } } //throw new InvalidStepInputException("Missing step inputs for step template " + Id + ", expected " + InputDefinitions.Count() + " got " + inputs.Count() + " missing "); } foreach (var input in inputs) { var foundTemplate = InputDefinitions.Where(tp => tp.Key == input.Key).FirstOrDefault(); if (!IsStepInputValid(input)) { throw new InvalidStepInputException("Step input " + input.Key + " is not found in the template definition."); } if ((AllowDynamicInputs && !InputDefinitions.ContainsKey(input.Key)) || InputDefinitions.ContainsKey(input.Key)) { if (InputDefinitions.ContainsKey(input.Key) && InputDefinitions[input.Key].Type == InputDataTypes.Secret && !InputDataUtility.IsInputReference(input, out _, out _)) { verifiedInputs.Add(input.Key.ToLower(), SecurityUtility.SymmetricallyEncrypt((string)input.Value, encryptionKey)); } else { verifiedInputs.Add(input.Key.ToLower(), input.Value); } } } } else if (inputs == null && InputDefinitions.Count() > 0) { throw new InvalidStepInputException("No inputs were specified however step template " + Id + " has " + InputDefinitions.Count() + " inputs."); } var newStep = new Step(Guid.NewGuid(), name, description, stepTemplateId, createdBy, verifiedInputs, encryptionKey, workflowId, executionTemplateId, executionScheduleId); return(newStep); }
public UploadFileResult UploadFile(string fileID, string fileName, byte[] data, bool isFirstChunk, bool isLastChunk, Dictionary <string, string> customParams) { UploadFileResult result = new UploadFileResult(); string extension = Path.GetExtension(fileName); string tempFileName = ""; string tempFilePath = ""; string tempUpFilePath = TempPathForUploadedFiles; if (!Directory.Exists(tempUpFilePath)) { Directory.CreateDirectory(tempUpFilePath); } if (isFirstChunk) { // 第一个文件块 ServiceLog.Log("大文件上传", "UploadFileService", fileName, "开始上传啦"); tempFileName = GetNewFileName(tempUpFilePath, extension) + "_temp"; tempFilePath = Path.Combine(tempUpFilePath, tempFileName); } else { // 非第一个文件块 tempFileName = fileID; tempFilePath = Path.Combine(tempUpFilePath, tempFileName); } // 临时文件名作为文件唯一标识 result.FileID = tempFileName; // 生成 SHA1 散列值 result.SHA1 = SecurityUtility.SHA1(data); // 写入数据 using (FileStream fs = File.Open(tempFilePath, FileMode.Append)) { fs.Write(data, 0, data.Length); fs.Flush(); fs.Close(); } if (isLastChunk) { // 保存上传文件 result.FileID = DealUploadedFile(fileName, tempFilePath, customParams); // 删除临时文件 if (File.Exists(tempFilePath)) { File.Delete(tempFilePath); } } return(result); }