public async Task <ActionResult <int> > ChangePassword(int id, [FromBody] UserChangePasswordRequest request) { var user = await _context .Users .AsNoTracking() .FirstOrDefaultAsync(u => u.UserId == id); if (user != null) { var hash = await HashService.HashPassword(request.OldPassword, user.Salt); if (hash == user.Password) { var salt = SaltGenerator.MakeSalty(); var newHash = await HashService.HashPassword(request.Password, salt); var newUser = user with { Password = newHash, Salt = salt }; _context.Users.Update(newUser); await _context.SaveChangesAsync(); return(new OkResult()); } return(new ForbidResult()); } return(new BadRequestResult()); }
public static RefreshTokenModel GenerateToken(IConnectionMultiplexer connectionMultiplexer, string cacheKey, IEnumerable <Claim> claims, string key, string issuer = null, string audience = null, double?expires = null) { RSAParameters privateKeyParameters = DigitalSignatureManager.GetKey(key); RsaSecurityKey privateKey = new RsaSecurityKey(privateKeyParameters); SigningCredentials credentials = new SigningCredentials(privateKey, SecurityAlgorithms.RsaSha256); JwtSecurityToken securityToken = new JwtSecurityToken( issuer: issuer, audience: audience, claims: claims, expires: expires.HasValue ? (DateTime?)DateTime.UtcNow.AddMinutes(expires.Value) : null, signingCredentials: credentials); string token = new JwtSecurityTokenHandler().WriteToken(securityToken); string refreshToken = SaltGenerator.Generate(); IDatabase database = connectionMultiplexer.GetDatabase(0); database.StringSet(cacheKey, refreshToken); return(new RefreshTokenModel { Token = token, Expiration = securityToken.ValidTo, RefreshToken = refreshToken }); }
public async Task <ActionResult <Users> > CreateUsers([FromBody] Users model) { var fullname = model.Fullname; var role = model.Role; var salt = SaltGenerator.SaltMethod(); var passwordHash = _hashingService.ComputeSha256Hash(model.Passwordhash, salt); var email = model.Email; if (model != null) { var user = new Users() { Fullname = fullname, Role = role, Passwordsalt = salt, Passwordhash = passwordHash, Email = email }; _context.Users.Add(user); await _context.SaveChangesAsync(); user.Passwordhash = null; user.Passwordsalt = null; return(Ok(user)); } return(BadRequest("Something went wrong")); }
static HashComputer m_hashcomputer = new HashComputer(); //initialises new hash computer public static string GeneratePasswordHash(string password, out string salt) { salt = SaltGenerator.GetSaltString(); //retrieves and sets the salt from saltGenerator string saltedPassword = salt + password; //combines password and salt return(m_hashcomputer.GetPasswordHashAndSalt(saltedPassword)); // hashes salted password }
public override void APIPost(Users newUser, AppDbContext context) { ErrInfLogger.LockInstance.InfoLog("APIPost launched." + _logInfo); SqlParameter result = new SqlParameter("@result", System.Data.SqlDbType.Int) { Direction = System.Data.ParameterDirection.Output }; context.Database.ExecuteSqlCommand("SELECT @result = (NEXT VALUE FOR IntSeq)", result); //(int)result.Value ErrInfLogger.LockInstance.InfoLog(result.Value.ToString()); newUser.Id = (int)result.Value; newUser.PermissionId = 0; newUser.AuthToken = _jwt.ReturnJWT(System.DateTime.Now, 0, (int)result.Value); newUser.AuthTokenExpiration = System.DateTime.Now; newUser.Salt = SaltGenerator.GenerateSalt(); newUser.UserAccountStatus = "normal"; // encrypt password newUser.HashPassword = _krypton.EncryptStringAES(newUser.HashPassword, newUser.Salt); context.Users.Add(newUser); context.SaveChanges(); }
public string GeneratePasswordHash(string plainTextPassword, out string salt) { salt = SaltGenerator.GetSaltString(); string finalString = plainTextPassword + salt; return(m_hashComputer.GetCrypt(finalString)); }
public UserDto Register(string userName, string password, IList <string> rolesNames) { const int saltLength = 10; string salt = SaltGenerator.GetSalt(saltLength); string passwordHash = Encoding.ASCII.GetString(new SHA256Managed().ComputeHash(Encoding.ASCII.GetBytes(salt + password))); List <Role> roles = UnitOfWork.Roles.Find(r => rolesNames.Contains(r.Name)).ToList(); User user = UnitOfWork.Users.SingleOrDefaultDeleted(u => u.UserName == userName); if (user == null) { user = new User(userName, passwordHash, salt, roles); UnitOfWork.Users.Create(user); } else { user.Deleted = false; user.PasswordHash = passwordHash; user.Salt = salt; user.Roles.Clear(); user.Roles = roles; UnitOfWork.Users.Update(user); } UnitOfWork.Save(); return(user.ToDto()); }
public void Dispose() { _encryption = null; _decryption = null; _sha = null; _saltGenerator = null; }
private bool ResumeSession(Stream stream, byte[] additionalChallenge) { stream.Write((byte)16); byte[] aChallenge = SaltGenerator.Create(16); stream.Write(aChallenge); stream.Write((short)m_resumeTicket.Length); stream.Write(m_resumeTicket); stream.Flush(); if (stream.ReadBoolean()) { SetHashMethod((HashMethod)stream.ReadNextByte()); byte[] bChallenge = stream.ReadBytes(stream.ReadNextByte()); byte[] clientProof = m_hash.ComputeHash(aChallenge, bChallenge, m_sessionSecret, additionalChallenge); stream.Write(clientProof); stream.Flush(); if (stream.ReadBoolean()) { byte[] serverProof = m_hash.ComputeHash(bChallenge, aChallenge, m_sessionSecret, additionalChallenge); byte[] serverProofCheck = stream.ReadBytes(m_hash.GetDigestSize()); return(serverProof.SecureEquals(serverProofCheck)); } } m_sessionSecret = null; m_resumeTicket = null; return(Authenticate(stream, additionalChallenge)); }
// private readonly IUserService _service; //public UserService() //{ // // _service = service; //} //seeding or hardcoding the admin user. Works public static void Initialize(IServiceProvider serviceProvider) { using (var scope = serviceProvider.CreateScope()) { using (var context = scope.ServiceProvider.GetRequiredService <PayArenaMockContext>()) { if (!context.User.Any()) { string salt = SaltGenerator.SaltMethod(); HashingService hash = new HashingService(); context.User.Add(new User() { FirstName = "Uzoezi", LastName = "Ubiri", UserName = "******", Email = "*****@*****.**", Role = Role.Admin, Token = "Buzz", Salt = salt, Password = hash.ComputeSha256Hash("Admin", salt) }); context.SaveChanges(); } //add a user /* if (!context.User.Any()) * { * context.User.Add(new User() { FirstName = "Uzoezi", LastName = "Ubiri", UserName = "******", Password = "******", Role = Role.Admin }); * context.SaveChanges(); * }*/ } } }
/// <summary> /// Creates a user credential from the provided data. /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <param name="strength"></param> /// <param name="saltSize"></param> /// <param name="iterations"></param> /// <returns></returns> public SrpUserCredential(string username, string password, SrpStrength strength = SrpStrength.Bits1024, int saltSize = 32, int iterations = 4000) { username = username.Normalize(NormalizationForm.FormKC); password = password.Normalize(NormalizationForm.FormKC); UsernameBytes = Encoding.UTF8.GetBytes(username); var constants = SrpConstants.Lookup(strength); BigInteger N = constants.N; BigInteger g = constants.g; byte[] s = SaltGenerator.Create(saltSize); byte[] hashPassword = PBKDF2.ComputeSaltedPassword(HMACMethod.SHA512, Encoding.UTF8.GetBytes(password), s, iterations, 64); Sha512Digest hash = new Sha512Digest(); byte[] output = new byte[hash.GetDigestSize()]; hash.BlockUpdate(UsernameBytes, 0, UsernameBytes.Length); hash.Update((byte)':'); hash.BlockUpdate(hashPassword, 0, hashPassword.Length); hash.DoFinal(output, 0); hash.BlockUpdate(s, 0, s.Length); hash.BlockUpdate(output, 0, output.Length); hash.DoFinal(output, 0); BigInteger x = new BigInteger(1, output).Mod(N); BigInteger v = g.ModPow(x, N); UserName = username; Salt = s; Verification = v.ToByteArray(); Iterations = iterations; SrpStrength = strength; VerificationInteger = new BigInteger(1, Verification); }
public void CorrectLength() { var sg = new SaltGenerator(12); Assert.AreEqual(12, sg.Next().Length); Assert.AreEqual(12, sg.Next().Length); }
/// <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(); }
public CommandResult Register(UserRegisterCommand command) { bool exist = _repository.ExistName(command.Username); if (exist) { return(new CommandResult(false, "Este nome já está cadastrado! ")); } exist = _repository.ExistEmail(command.Email); if (exist) { return(new CommandResult(false, "Este email já está cadastrado! ")); } var user = new User(command.Username, command.Email, command.Password); if (user.Invalid) { return(new CommandResult(false, string.Join(". ", Notifications))); } // Add Hash and Salt var salt = SaltGenerator.Generate(); var hash = HashGenerator.Generate(user.Password, salt); user.AddHash(hash, Convert.ToBase64String(salt)); user.AddEmailToken(); _repository.Register(user); user.HidePassword(); return(new CommandResult(true, "Cadastro realizado! Valide seu e-mail. ", user)); }
public void SaltIsUnique() { var sg = new SaltGenerator(); var s1 = sg.Next(); var s2 = sg.Next(); Assert.AreNotEqual(s1, s2); }
public void EqualsSequence(string password) { var saltGenerator = new SaltGenerator(); byte[] key = saltGenerator.SaltPassword(password); bool result = saltGenerator.EqualsSequence(password, key); Assert.True(result); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Before public void initialize() public virtual void initialize() { runtimeService = engineRule.RuntimeService; identityService = engineRule.IdentityService; processEngineConfiguration = engineRule.ProcessEngineConfiguration; camundaDefaultEncryptor = processEngineConfiguration.PasswordEncryptor; camundaDefaultPasswordChecker = processEngineConfiguration.CustomPasswordChecker; camundaDefaultSaltGenerator = processEngineConfiguration.SaltGenerator; }
public RegisterResponse Register(RegisterRequest request) { var userExists = _context.Client.Any(c => c.Login.Equals(request.Login)); if (userExists) { throw new UserAlreadyExistsException("User already Exists!"); } var salt = SaltGenerator.CreateSalt(); var newClient = new Client() { FirstName = request.FirstName, LastName = request.LastName, Email = request.Email, Phone = request.Phone, Login = request.Login, Password = HashGenerator.CreateHashForPassword(request.Password, salt), Salt = salt, RefreshToken = RefreshTokenGenerator.CreateRefreshToken(), TokenExpirationDate = DateTime.Now.AddDays(7) }; var newClientClaims = new[] { new Claim(ClaimTypes.NameIdentifier, Convert.ToString(newClient.IdClient)), new Claim(ClaimTypes.Name, newClient.Login), new Claim(ClaimTypes.Role, "Client") }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SecretKey"])); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: "*****@*****.**", audience: "Clients", claims: newClientClaims, expires: DateTime.Now.AddMinutes(10), signingCredentials: credentials ); _context.Client.Add(newClient); _context.SaveChanges(); return(new RegisterResponse() { FirstName = newClient.FirstName, LastName = newClient.LastName, Email = newClient.Email, Phone = newClient.Phone, Login = newClient.Login, AccessToken = new JwtSecurityTokenHandler().WriteToken(token), RefreshToken = newClient.RefreshToken }); }
public RegisterUserResponse RegisterUser(RegisterUserRequest request) { var checkUser = _context.Client.Any(p => p.Login.Equals(request.Login) || p.Email.Equals(request.Email)); if (checkUser) { throw new UserExistsException(); } if (!MailValidator.IsValidMail(request.Email)) { throw new InvalidMail(); } var salt = SaltGenerator.GenerateSalt(); var hashedPass = HashPassword.HashPass(request.Password, salt); var client = new Client() { FirstName = request.FirstName, LastName = request.LastName, Email = request.Email, Phone = request.Phone, Login = request.Login, Password = hashedPass, Salt = salt }; var userclaim = new[] { new Claim(ClaimTypes.NameIdentifier, Convert.ToString(client.IdClient)), new Claim(ClaimTypes.Name, request.FirstName), new Claim(ClaimTypes.Role, "Client") }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SecretKey"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: "AdCompany", audience: "Clients", claims: userclaim, expires: DateTime.Now.AddMinutes(5), signingCredentials: creds ); client.RefreshToken = Guid.NewGuid().ToString(); client.ExpireDate = DateTime.Now.AddDays(1); _context.Client.Add(client); _context.SaveChanges(); return(new RegisterUserResponse() { AccessToken = new JwtSecurityTokenHandler().WriteToken(token), RefreshToken = client.RefreshToken }); }
public void EqualsSequenceBig() { var password = new string(';', 2048); var saltGenerator = new SaltGenerator(); byte[] key = saltGenerator.SaltPassword(password); bool result = saltGenerator.EqualsSequence(password, key); Assert.True(result); }
public void TestNormal(int count) { var ng = new SaltGenerator(); ng.SetSalt(0); var list = Enumerable.Range(1, count).AsParallel().Select(x => ng.NextSalt); var dupes = list.GroupBy(x => x).Where(g => g.Count() > 1).Select(x => x.Key); Assert.Equal(0, dupes.Count()); }
public void Test() { var gen = new SaltGenerator(); var first = gen.GetSaltBytes(); var second = gen.GetSaltBytes(); Assert.AreNotEqual(first, second); Assert.AreEqual("Salt generator", gen.ToString()); gen.SetSalt(long.MaxValue); Assert.AreEqual(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }, gen.GetSaltBytes()); }
public void Test() { var gen = new SaltGenerator(); var first = gen.GetSaltBytes(); var second = gen.GetSaltBytes(); Assert.AreNotEqual(first, second); Assert.AreEqual("Salt generator", gen.ToString()); gen.SetSalt(long.MaxValue); Assert.AreEqual(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }, gen.GetSaltBytes()); }
public User( string userName, string password, string eMail) { this.UserName = userName; this.Email = eMail; string salt = SaltGenerator.Generate(); this.Password = password.ComputeHashSHA256(salt); this.Salt = salt; }
public void Should_PassValidation_When_TwoGeneratedSaltsAreNotEqualGivenSameSaltSize() { // Arrange var saltGenerator = new SaltGenerator(); // Act var firstSalt = saltGenerator.GenerateSalt(128); var secondSalt = saltGenerator.GenerateSalt(128); // Assert firstSalt.Should().NotMatch(secondSalt); }
public ScriptCompiler(ICacheFile casheFile, EngineDescription buildInfo, OpcodeLookup opCodes, ScriptingContextCollection context, IProgress<int> progress, ScriptCompilerLogger logger, bool debug) { _buildInfo = buildInfo; _progress = progress; _cacheFile = casheFile; _scriptingContext = context; _opcodes = opCodes; _logger = logger; _debug = debug; _expectedTypes = new TypeStack(logger, _debug); ushort intialSalt = SaltGenerator.GetSalt("script node"); _currentIndex = new DatumIndex(intialSalt, 0); }
public User AdminLogin(LoginDto loginDto) { using (SqlConnection conn = new SqlConnection(this.DBString)) { using (SqlCommand cmd = new SqlCommand("spLogin", conn) { CommandType = CommandType.StoredProcedure }) { cmd.Parameters.AddWithValue("@email", loginDto.email); cmd.Parameters.AddWithValue("@user_role", 0); try { conn.Open(); SqlDataReader rdr = cmd.ExecuteReader(); if (rdr.HasRows) { User admin = new User(); while (rdr.Read()) { var epass = SaltGenerator.EncodePassword(loginDto.password, rdr["key_new"].ToString()); var dpass = SaltGenerator.Base64Decode(rdr["password"].ToString()); if (epass.Equals(dpass)) { admin.id = Convert.ToInt32(rdr["id"]); admin.fullName = rdr["full_name"].ToString(); admin.email = rdr["email"].ToString(); admin.password = rdr["password"].ToString(); admin.phoneNo = rdr["phone_no"].ToString(); admin.emailVerified = (bool)rdr["email_verified"]; admin.userRole = Convert.ToInt32(rdr["user_role"]); } return(admin); } return(null); } } catch { return(null); } finally { conn.Close(); } } } return(null); }
public string UserRegistration(UserRegistrationDto userRegistrationDto) { using (SqlConnection conn = new SqlConnection(this.DBString)) { var keyNew = SaltGenerator.GeneratePassword(10); userRegistrationDto.password = SaltGenerator.Base64Encode( SaltGenerator.EncodePassword(userRegistrationDto.password, keyNew)); using (SqlCommand cmd = new SqlCommand("spUserRegistration", conn) { CommandType = CommandType.StoredProcedure }) { cmd.Parameters.AddWithValue("@email", userRegistrationDto.email); cmd.Parameters.AddWithValue("@email_verified", true); cmd.Parameters.AddWithValue("@full_name", userRegistrationDto.fullName); cmd.Parameters.AddWithValue("@password", userRegistrationDto.password); cmd.Parameters.AddWithValue("@phone_no", userRegistrationDto.phoneNo); cmd.Parameters.AddWithValue("@registration_date", DateTime.Now); cmd.Parameters.AddWithValue("@user_role", userRegistrationDto.userRole); cmd.Parameters.AddWithValue("@key_new", keyNew); cmd.Parameters.Add("@id", SqlDbType.Int).Direction = ParameterDirection.Output; try { conn.Open(); cmd.ExecuteNonQuery(); string id = cmd.Parameters["@id"].Value.ToString(); if (id != "") { var GeneratedToken = this.GenerateJSONWebToken(Convert.ToInt32(id), "User"); MessagingService.Send("Verify Email", "Click on below given link to verify your email id " + "<br/> <a href='http://*****:*****@gmail.com"); return(id); } } catch { return(null); } finally { conn.Close(); } } } return(""); }
/// <summary> /// Calculates the salt value of an index and returns it. /// </summary> /// <param name="index">The index belonging to the salt value.</param> /// <returns>The salt value.</returns> private ushort IndexToSalt(ushort index) { // Initial value for the expression reflexive. ushort init = SaltGenerator.GetSalt("script node"); // This value is used to calculate the salt once it exceeds 0xFFFF. ushort restart = 0x7FFF; int salt = init + index; if (salt >= ushort.MaxValue) { salt = (salt % restart) + restart; } return((ushort)salt); }
/// <summary> /// TODO: Comment /// </summary> public void CreateConfigurationFile() { //Create Path Directory.CreateDirectory(Path.GetDirectoryName(this.configurationPath)); //Create basic configuration file XDocument doc = new XDocument(new XElement("configuration", new XElement("masterPassword"), new XElement("salt"), new XElement("encryptedData"))); SaltGenerator saltGenerator = new SaltGenerator(); //Save generated salt doc.Descendants("salt").First().Value = Convert.ToBase64String(saltGenerator.GenerateSalt()); //Save configuration file doc.Save(this.configurationPath); }
/// <summary> /// TODO: Comment /// </summary> public void CreateConfigurationFile() { //Create Path Directory.CreateDirectory(Path.GetDirectoryName(this.configurationPath)); //Create basic configuration file XDocument doc = new XDocument(new XElement("configuration", new XElement("masterPassword"), new XElement("salt"), new XElement("encryptedData"))); SaltGenerator saltGenerator = new SaltGenerator(); //Save generated salt doc.Descendants("salt").First().Value = Convert.ToBase64String(saltGenerator.GenerateSalt()); //Save configuration file doc.Save(this.configurationPath); }
public void TestOverflow(int count) { var overallDupes = 0; Parallel.ForEach(Enumerable.Range(0, count), i => { var ng = new SaltGenerator(); ng.SetSalt(long.MaxValue - 5); var list = Enumerable.Range(1, 20).AsParallel().Select(x => ng.NextSalt); var dupes = list.GroupBy(x => x).Where(g => g.Count() > 1).Select(x => x.Key); if (dupes.Count() > 0) { Interlocked.Increment(ref overallDupes); } }); Assert.Equal(0, overallDupes); }
/// <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(); }