public async Task <string> OpenDocument(string filepath) { using var stream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.None); var hash = await HashingUtility.ComputeHashFromStreamAsync(stream); using var reader = FileReader.OpenStream(stream, Encoding.Default); var text = await reader.ReadToEndAsync(); var info = new DocumentInfo() { Id = Guid.NewGuid().ToString(), Encoding = reader.CurrentEncoding, Document = new TextDocument(text), Hash = hash, Filepath = filepath }; lock (documentCollectionLock) { this.openedDocuments.Add(info); } this.DocumentOpened?.Invoke(this, info.Id); return(info.Id); }
public IActionResult Add(Member model) { // validate some data.. if (model.password == null || model.password == "") { return(Content("Error : password can't be empty!")); } MySql.Data.MySqlClient.MySqlConnection conn; string myConnectionString = "server=127.0.0.1;uid=root;pwd=defaultdefault;database=Test"; try { conn = new MySql.Data.MySqlClient.MySqlConnection(); conn.ConnectionString = myConnectionString; conn.Open(); } catch (MySql.Data.MySqlClient.MySqlException ex) { return(View(ex.Message)); } string hashedPassword = HashingUtility.GetHashString(model.password); string insrt = "INSERT INTO Members ( firstName, lastName, emailAddress, password ) " + "VALUES ( '" + model.firstName + "', '" + model.lastName + "', '" + model.emailAddress + "', '" + hashedPassword + "');"; MySqlCommand cmd = new MySqlCommand(insrt, conn); cmd.ExecuteNonQuery(); return(Content("user was added")); }
public async Task <OperationResponse <bool> > changePassword(ChangePasswordModel changePasswordModel) { OperationResponse <bool> response = new OperationResponse <bool>(); try { var user = await _dbContext.DeliveryClient.Where(c => c.DelClientId == changePasswordModel.userID && c.Password == HashingUtility.hashPassword(changePasswordModel.oldPassword)).FirstOrDefaultAsync(); if (user != null) { user.Password = HashingUtility.hashPassword(changePasswordModel.newPassword); } var rowsAffectred = _dbContext.SaveChanges(); if (rowsAffectred > 0) { response.Data = true; } else { response.HasErrors = true; response.Message = "Error in Creating User"; } } catch (Exception ex) { var msg = ex.Message; response.HasErrors = true; response.Message = msg; } return(response); }
/// <summary> /// Generates a new password for the user in case he forgets the password /// </summary> /// <param name="logOnName">Log on name</param> /// <param name="securityQuestion">Security question</param> /// <param name="answer">Answer to security question</param> /// <returns>New password generated for the user</returns> /// <remarks>In case user forgets his password the security API gives him a new system generated password. /// Set user's logon name, security question and answer properties to correct /// values (those matching ones entered at the time of user registration) and then call this method. /// It returns a system generated strong password of minimum length as specified by the password policy /// </remarks> /// <exception cref="System.ArgumentException">Thrown when this method is called without first setting the /// logon name, security question or answer of the ZentityUser object.</exception> /// <example> /// <code> /// try /// { /// //In case user forgets his password the security API gives him a new system generated password. /// //User needs to provide security question and answer which he had entered at the time of registration. /// /// //Create an instance of ZentityUser and set logon name, security question and answer. /// ZentityUser user = new ZentityUser { LogOnName = "john" }; /// user.SetSecurityQuestion("What is a bit?"); /// user.SetAnswer("0 or 1"); /// //Call ForgotPassword method. It returns a new strong password which is of minimum length specified in password policy. /// string newSystemGeneratedPassword = user.ForgotPassword(); /// if (!string.IsNullOrEmpty(newSystemGeneratedPassword)) /// { /// Console.WriteLine("Your new password is {0}", newSystemGeneratedPassword); /// } /// else /// { /// Console.WriteLine("Errors in generating new password. Please verify that logon name, security question and answer are correct."); /// } /// } /// catch (AuthenticationException ex) /// { /// // AuthenticationException may be thrown in case of database errors /// Console.WriteLine(ex.Message); /// // In case of database errors the AuthenticationException object will wrap the sql exception. /// if (ex.InnerException != null) /// { /// Console.WriteLine(ex.InnerException.Message); /// } /// } /// /// </code> /// </example> public static string ForgotPassword(string logOnName, string securityQuestion, string answer) { string newPassword = PasswordManager.ForgotPassword( logOnName, securityQuestion, HashingUtility.GenerateHash(answer.ToUpper(CultureInfo.CurrentCulture))); return newPassword; }
public void TestCreate() { var tokenResult = HashingUtility.Create(this.publicKey, this.privateKey); Assert.NotNull(tokenResult.token); Assert.NotNull(tokenResult.timestamp); Assert.NotNull(tokenResult.nonce); }
public void TestCreate_WithNonce() { var tokenResult = HashingUtility.Create(this.publicKey, this.privateKey, nonce: "test"); Assert.NotNull(tokenResult.token); Assert.NotNull(tokenResult.timestamp); Assert.Equal("test", tokenResult.nonce); }
/// <summary> /// Initializes a new instance of the ZentityAuthenticatedToken class. /// </summary> /// <param name="identityName">User name</param> internal ZentityAuthenticatedToken(string identityName) { #region Input validation if (string.IsNullOrEmpty(identityName)) { throw new ArgumentNullException("identityName"); } #endregion this.identity = identityName; this.hashedIdentity = HashingUtility.GenerateHash(this.identity); }
public IActionResult SignIn(SignIn model) { //establish/test sql connection MySql.Data.MySqlClient.MySqlConnection conn; string myConnectionString = "server=127.0.0.1;uid=root;pwd=defaultdefault;database=Test"; try { conn = new MySql.Data.MySqlClient.MySqlConnection(); conn.ConnectionString = myConnectionString; conn.Open(); } catch (MySql.Data.MySqlClient.MySqlException ex) { return(View(ex.Message)); } //create sql query for password firstname lastname from members where email = input string sqlQuery = "select firstname, lastname, password from Members where emailAddress='" + model.email + "';"; MySqlCommand query = new MySqlCommand(sqlQuery, conn); string firstName; string lastName; //reader to parse sql reply //if correct, show welcome msg //if incorrect show error msg using (var reader = query.ExecuteReader()) { if (reader.Read()) { firstName = reader["firstname"].ToString(); lastName = reader["lastname"].ToString(); string password = reader["password"].ToString(); string hashedPassword = HashingUtility.GetHashString(model.password); if (password != hashedPassword) { return(Content("'" + model.password + "'")); } } else { return(Content(model.email)); } } return(Content("Welcome " + firstName + " " + lastName + "! You are now logged in.")); }
/// <summary> /// Validates whether the token is valid, that is it is not tampered with, and it is not expired. /// </summary> /// <returns>True if token is valid</returns> /// <example>Please refer to the ZentityAuthenticatedToken class help page for a code sample.</example> public override bool Validate() { string hashOfCurrentIdentity = HashingUtility.GenerateHash(this.identity); if (string.Compare(hashOfCurrentIdentity, this.hashedIdentity, StringComparison.Ordinal) == 0) { if (this.ValidUpTo != null) { if (this.ValidUpTo >= DateTime.Now) { return(true); } return(false); } return(true); } return(false); }
public async Task <bool> IsOutOfSyncWithFileAsync() { if (this.Filepath == null || this.Hash == null) { return(false); } var fileInfo = new FileInfo(this.Filepath); if (!fileInfo.Exists) { return(false); } using (var reader = this.Document.CreateReader()) { var currentHash = await HashingUtility.ComputeHashFromReaderAsync(reader, this.Encoding); return(!this.Hash.SequenceEqual(currentHash)); } }
public async Task <OperationResponse <DeliveryClient> > createAccount(DeliveryClient registerModel) { OperationResponse <DeliveryClient> response = new OperationResponse <DeliveryClient>(); try { if (_dbContext.DeliveryClient.Where(c => c.Email == registerModel.Email).Any()) { throw new Exception("user email exists before"); } if (_dbContext.DeliveryClient.Where(c => c.Phone1 == registerModel.Phone1).Any()) { throw new Exception("phone number exists before"); } registerModel.Password = HashingUtility.hashPassword(registerModel.Password); _dbContext.DeliveryClient.Add(registerModel); var rowsAffectred = _dbContext.SaveChanges(); if (rowsAffectred > 0) { response.Data = registerModel; } else { response.HasErrors = true; response.Message = "Error in Creating User"; } } catch (Exception ex) { var msg = ex.Message; response.HasErrors = true; response.Message = msg; } if (response.Data != null) { response.Data.Password = ""; } return(response); }
public async Task <AuthUser> Authenticate(AuthCredentials credentials) { var user = await _userCollection.Find <UserDTO>(user => user.Email == credentials.Email).FirstOrDefaultAsync(); if (user == null) { return(null); } if (!user.Password.Code.Equals(HashingUtility.GetHash(credentials.Password, user.Password.Salt))) { return(null); } // authentication successful so generate jwt token var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(Configuration["Jwt:Key"]); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim("userId", user.Id.ToString()), new Claim(ClaimTypes.Email, user.Email) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); return(new AuthUser() { User = GetQueryUser(user), Token = tokenHandler.WriteToken(token) }); }
public static string GenerateHashCode(object obj) { return(HashingUtility.GetSHA1Hash(obj)); }
public Password(string password) { Salt = Guid.NewGuid().ToString(); Code = HashingUtility.GetHash(password, Salt); }
public async Task <OperationResponse <DeliveryClient> > Login(LoginModel loginModel) { OperationResponse <DeliveryClient> or = new OperationResponse <DeliveryClient>(); try { var user = await _dbContext.DeliveryClient.Where(c => c.Phone1 == loginModel.PhoneNumber && c.Password == HashingUtility.hashPassword(loginModel.password)).FirstOrDefaultAsync(); if (user != null) { if (loginModel.GcmToken != null) { user.GcmToken = loginModel.GcmToken; _dbContext.SaveChanges(); } user.Password = null; or.Data = user; } else { throw new Exception("Incorrect phone number or password"); } } catch (Exception ex) { or.Message = ex.Message; or.HasErrors = true; } return(or); }
public void TestHash() { var hash = HashingUtility.Hash(this.publicKey, this.privateKey); Assert.NotNull(hash); }
public void TestGenerateKey() { var key = HashingUtility.GenerateKey(size: 64); Assert.NotNull(key); }