public void ComputeHashOfCurrentDirectory() { // Given HashProvider hp = new HashProvider(); DirectoryInfo currentDir = new DirectoryInfo(new TestConfiguration().GetRootPath()); if (!currentDir.EnumerateFiles("*", SearchOption.AllDirectories).Any()) { File.Create(Path.Combine(currentDir.FullName, string.Format("{0}.test", Guid.NewGuid().ToString("B")))).Dispose(); } // When byte[] hash1 = hp.ComputeHash(currentDir); byte[] hash2 = hp.ComputeHash(currentDir); File.Create(Path.Combine(currentDir.FullName, string.Format("{0}.test", Guid.NewGuid().ToString("B")))).Dispose(); byte[] hashChanged = hp.ComputeHash(currentDir); // Then Assert.That(hash1, Is.Not.Null); Assert.That(hash2, Is.Not.Null); Assert.That(hashChanged, Is.Not.Null); CollectionAssert.AllItemsAreNotNull(hash1); CollectionAssert.AllItemsAreNotNull(hash2); CollectionAssert.AllItemsAreNotNull(hashChanged); Assert.That(hash1.SequenceEqual(hash2), Is.True); Assert.That(hash2.SequenceEqual(hashChanged), Is.False); }
public void Given_String_Compute_Hash_Calculates_Correct_MD5_Hash() { var dotNetGroupValue = "DotNetGroup"; var dotNetGroupHash = "4779ccd6ffccfac7cf91cfe585d02db0"; var hashProvider = new HashProvider(new MD5CryptoServiceProvider()); var hash = hashProvider.ComputeHash(dotNetGroupValue); Assert.That(hash, Is.EqualTo(dotNetGroupHash)); }
public void HashProvider_ComputeHash_ReturnsExpectedByte() { HashProvider hashProvider = new HashProvider(); byte[] dataBytes = Encoding.UTF8.GetBytes(data); byte[] actualHash = hashProvider.ComputeHash(dataBytes); string actualHashString = BitConverter.ToString(actualHash).Replace("-", string.Empty); Assert.AreEqual(dataExpectedHash, actualHashString); }
public void ShouldBeAbleToHashString() { //Arrange var target = new HashProvider(); var theString = "test"; //Act var result = target.ComputeHash(theString); //Assert Assert.Equal("7iaw3Ur350mqGo7jwQrpkj9hiYB3Lkc/iBml1JQODbJ6wYX4oOHV+E+IvIh/1nsUNzLDBMxfqa2Ob1f1ACio/w==", result); }
public void ComputeHashOnEmptyDirectory() { // Given HashProvider hp = new HashProvider(); DirectoryInfo emptyDir = new DirectoryInfo(Path.Combine(new TestConfiguration().GetRootPath(), Guid.NewGuid().ToString("B"))); emptyDir.Create(); // When byte[] hash = hp.ComputeHash(emptyDir); // Then Assert.That(hash, Is.Not.Null); Assert.That(hash.All(b => b == 0)); emptyDir.Delete(); }
private static void AddInitialUserAccounts(AppDBContext context, SecurityOptions securityOptions) { if (context.Users.Any() == false) { var password = "******"; string hashedPassword = HashProvider.ComputeHash(password, HashProvider.HashAlgorithmList.SHA256, securityOptions.PasswordSalt); var users = new User[] { new User { DisplayName = "Dezi Van Vuuren", FirstName = "Dezi", Surname = "Van Vuuren", EmailAddress = "*****@*****.**", Password = hashedPassword, UserID = Guid.NewGuid(), CreatedDateTime = DateTime.UtcNow, CreatedUserID = Guid.Empty, EditDateTime = DateTime.UtcNow, EditUserID = Guid.Empty, } }; foreach (User s in users) { context.Users.Add(s); var adminRole = context.UserRoles.Where(x => x.EventCode == PublicEnums.UserRoleList.ROLE_ADMINISTRATOR).First(); LinkUserRole roleLink = new LinkUserRole() { LinkUserRoleID = Guid.NewGuid(), UserID = s.UserID, UserRoleID = adminRole.UserRoleID }; context.LinkUserRole.Add(roleLink); } context.SaveChanges(); } }
internal async Task <bool> ChangePassword() { UserHelperFunctions userHelper = new UserHelperFunctions() { _context = _context, _securityOptions = _securityOptions, _user = _user }; userHelper.Populate(); bool returnValue = false; if (Guid.TryParse(T, out Guid tResult)) { var userToken = _context.UserTemporaryToken.Where(x => x.UserTemporaryTokenID == tResult).FirstOrDefault(); if (userToken != null) { var user = _context.Users.Where(x => x.UserID == userToken.UserID).FirstOrDefault(); if (user != null) { var hashedPassword = HashProvider.ComputeHash(Password, HashProvider.HashAlgorithmList.SHA256, _securityOptions.PasswordSalt); user.Password = hashedPassword; user.IsSuspended = false; user.LoginTries = 0; user.EditUserID = user.UserID; user.EditDateTime = DateTime.UtcNow; user.EditUserID = userHelper.loggedInUserID; _context.Update(user); await _context.SaveChangesAsync(); returnValue = true; } } } return(returnValue); }
/// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { while (true) { // Request a plain text value from the user. string enterValuePrompt = "Enter a value to hash (press Ctrl+C to exit)"; Console.WriteLine(enterValuePrompt); Console.WriteLine("".PadLeft(enterValuePrompt.Length, '=')); Console.WriteLine(); string plainValue = Console.ReadLine(); // If the value entered is null (Ctrl+C), // break from the loop to close the program. if (plainValue == null) { break; } // Display a title above the hashed value output. string hashedValueTitle = "Hashed Value"; Console.WriteLine(); Console.WriteLine(hashedValueTitle); Console.WriteLine("".PadLeft(hashedValueTitle.Length, '=')); Console.WriteLine(); // Compute the hashed value. IHashProvider hashProvider = new HashProvider(); string hashedValue = hashProvider.ComputeHash(plainValue); // Display the hashed value. Console.WriteLine(hashedValue); Console.WriteLine(); } }
private string GetHexHashSignature(string payload) { byte[] hash = HashProvider.ComputeHash(Encoding.UTF8.GetBytes(payload)); return(BitConverter.ToString(hash).Replace("-", "").ToLower()); }
public void Given_Null_Value_Compute_Hash_Throws() { var hashProvider = new HashProvider(); Assert.Throws <ArgumentNullException>(() => hashProvider.ComputeHash(null)); }
public IEnumerable <IDelta> GetDeltas(Stream inputStream) { if (inputStream == null) { throw new ArgumentNullException("inputStream"); } if (_initialized == false) { throw new InvalidOperationException("Initialize must be called"); } ChecksumProvider.Reset(); var slidingBuffer = new SlidingStreamBuffer(inputStream, _blockSize); slidingBuffer.Warmup(); bool startingNewBlock = true; long offset = 0; var deltas = new List <IDelta>(); var currentByteDelta = new ByteDelta(); #if DEBUG Statistics.Matching = 0; Statistics.PossibleMatches = 0; Statistics.NonMatching = 0; #endif int currentBlockSize; while ((currentBlockSize = (int)slidingBuffer.GetNumBytesAvailable()) > 0) { // Deal with signed integer limits if (IsSignedIntLength(offset - currentByteDelta.Offset)) { currentByteDelta.Length = (int)(offset - currentByteDelta.Offset); deltas.Add(currentByteDelta); startingNewBlock = true; } if (startingNewBlock) { currentByteDelta = new ByteDelta { Offset = offset }; ChecksumProvider.ProcessBlock(slidingBuffer.GetBuffer(), 0, currentBlockSize); } else if (currentBlockSize < _blockSize) { ChecksumProvider.TrimFront(); // remaining bytes < block_size, so read nothing new - just trim } else { ChecksumProvider.RollByte(slidingBuffer[(int)(currentBlockSize - 1)]); } // at this point, sigGen needs the last byte of the current block uint currentBlockChecksum = ChecksumProvider.Value; ushort currentBlockChecksumHash = RollingChecksum.HashChecksum(currentBlockChecksum); if (_remoteBlocksIndexTable.ContainsKey(currentBlockChecksumHash)) { List <HashBlock> possibleRemoteBlockMatches = _remoteBlocksIndexTable[currentBlockChecksumHash]; if (possibleRemoteBlockMatches.Any(entry => entry.Checksum == currentBlockChecksum)) { #if DEBUG ++Statistics.PossibleMatches; #endif byte[] currentBlockHash = HashProvider.ComputeHash(slidingBuffer.GetBuffer(), 0, (int)currentBlockSize); HashBlock matchingTargetBlock; if ((matchingTargetBlock = possibleRemoteBlockMatches.FirstOrDefault( entry => entry.Hash.SequenceEqual(currentBlockHash))) != null) { #if DEBUG Statistics.Matching += 1; #endif if ((currentByteDelta.Length = (int)(offset - currentByteDelta.Offset)) > 0) { deltas.Add(currentByteDelta); } deltas.Add(new CopyDelta { Offset = matchingTargetBlock.Offset, Length = matchingTargetBlock.Length }); slidingBuffer.MoveForward((int)currentBlockSize); offset += currentBlockSize; startingNewBlock = true; continue; } } } #if DEBUG ++Statistics.NonMatching; #endif slidingBuffer.MoveForward(1); ++offset; startingNewBlock = false; } Statistics.FileLength = offset; if (!startingNewBlock && (currentByteDelta.Length = (int)(offset - currentByteDelta.Offset)) > 0) { deltas.Add(currentByteDelta); } #if DEBUG Statistics.FileLength = offset; #endif return(deltas); }
public async Task <Guid> Save() { UserHelperFunctions userHelper = new UserHelperFunctions() { _context = _context, _emailService = _emailService, _securityOptions = _securityOptions, _user = _user }; userHelper.Populate(); bool isNew = false; bool isWasRemoved = false; string tempPassword = ""; PublicEnums.EmailTemplateList emailTemplate = PublicEnums.EmailTemplateList.NTF_REGISTRATION_WELCOME_CUSTOM; //Save user details var user = _context.Users.FirstOrDefault(x => x.UserID == UserID); if (user == null) { //Check user not deleted before user = _context.Users.FirstOrDefault(x => ((x.EmailAddress == EmailAddress && x.EmailAddress != null)) && x.IsRemoved == true); if (user == null) { //Perform dup-check user = _context.Users.FirstOrDefault(x => ((x.EmailAddress == EmailAddress && x.EmailAddress != null)) && x.IsRemoved == false); if (user == null) { user = new User(); isNew = true; user.UserID = Guid.NewGuid(); user.IsSuspended = false; user.LoginTries = 0; user.CreatedUserID = userHelper.loggedInUserID; user.CreatedDateTime = DateTime.UtcNow; user.IsRemoved = false; tempPassword = HelperFunctions.GeneratePassword(8); if (!string.IsNullOrEmpty(_tmpPassword)) { tempPassword = _tmpPassword; } user.Password = HashProvider.ComputeHash(tempPassword, HashProvider.HashAlgorithmList.SHA256, _securityOptions.PasswordSalt); _tmpPassword = tempPassword; } else { errorMessage = "The user email address already exists. Find the existing user first and edit their details"; return(Guid.Empty); } } else { tempPassword = HelperFunctions.GeneratePassword(8); if (!string.IsNullOrEmpty(_tmpPassword)) { tempPassword = _tmpPassword; } user.Password = HashProvider.ComputeHash(tempPassword, HashProvider.HashAlgorithmList.SHA256, _securityOptions.PasswordSalt); _tmpPassword = tempPassword; user.IsRemoved = false; isWasRemoved = true; } } user.DisplayName = DisplayName; user.EmailAddress = EmailAddress; user.IsSuspended = IsSuspended; user.LoginTries = (IsSuspended == false) ? 0 : user.LoginTries; user.EditUserID = userHelper.loggedInUserID; user.EditDateTime = DateTime.UtcNow; user.FirstName = FirstName; user.Surname = Surname; user.Timezone = SelectedTimezone; if (isNew) { _context.Add(user); } else { _context.Update(user); } if (isNew || isWasRemoved) { #region Send new user registration email if (!string.IsNullOrEmpty(EmailAddress)) { emailTemplate = PublicEnums.EmailTemplateList.NTF_REGISTRATION_WELCOME_CUSTOM; var variables = new Dictionary <string, PropertyMetaData> { { "HostUrl", new PropertyMetaData { Type = typeof(string), Value = _securityOptions.WebsiteHostUrl } }, { "DisplayName", new PropertyMetaData { Type = typeof(string), Value = DisplayName } }, { "Password", new PropertyMetaData { Type = typeof(string), Value = tempPassword } }, { "Username", new PropertyMetaData { Type = typeof(string), Value = EmailAddress } } }; await _emailService.SendEmailAsync(new List <string>() { EmailAddress }, "Welcome", emailTemplate, variables, _user); } #endregion } await ClearUserRoles(user.UserID); await AddSelectedUserRoles(user.UserID); await _context.SaveChangesAsync(); UserID = user.UserID; return(UserID); }
internal async Task <bool> Register() { bool isNew = false; if (string.IsNullOrEmpty(FirstName)) { _errorMessage = "Please enter a Name"; return(false); } else if (string.IsNullOrEmpty(Surname)) { _errorMessage = "Please enter a Surname"; return(false); } else if (string.IsNullOrEmpty(EmailAddress)) { _errorMessage = "Please enter a Email"; return(false); } else if (string.IsNullOrEmpty(Password)) { _errorMessage = "Please enter a Password"; return(false); } else if (Password != ConfirmPassword) { _errorMessage = "The password and Confirm Password must match"; return(false); } var user = _context.Users.FirstOrDefault(x => ((x.EmailAddress == EmailAddress && x.EmailAddress != null))); if (user == null) { user = new User(); isNew = true; user.UserID = Guid.NewGuid(); user.IsSuspended = false; user.LoginTries = 0; user.CreatedUserID = user.UserID; user.CreatedDateTime = DateTime.UtcNow; user.IsRemoved = false; user.Password = HashProvider.ComputeHash(Password, HashProvider.HashAlgorithmList.SHA256, _securityOptions.PasswordSalt); } else { _errorMessage = "The user email address already exists. Find the existing user first and edit their details"; return(false); } user.DisplayName = DisplayName; user.EmailAddress = EmailAddress; user.IsSuspended = false; user.LoginTries = 0; user.EditUserID = user.UserID; user.EditDateTime = DateTime.UtcNow; user.FirstName = FirstName; user.Surname = Surname; user.Timezone = _context.SystemConfiguration.First(x => x.EventCode == PublicEnums.SystemConfigurationList.KEY_DEFAULT_TIME_ZONE.ToString()).ConfigValue; if (isNew) { _context.Add(user); //Add default student user role LinkUserRole link = new LinkUserRole(); link.LinkUserRoleID = Guid.NewGuid(); link.UserID = user.UserID; link.UserRoleID = _context.UserRoles.First(x => x.EventCode == PublicEnums.UserRoleList.ROLE_USER).UserRoleID; link.CreatedUserID = user.UserID; link.EditUserID = user.UserID; _context.Add(link); } else { _context.Update(user); } await _context.SaveChangesAsync(); return(true); }