/// <summary> /// Loads the private key into memory (as a BIO object) and attempts to create a private key using the RSA algorithm and /// the supplied privateKeyPassword. /// </summary> /// <param name="pathToPrivateKeyFile">The path to the private key file.</param> /// <param name="privateKeyPassword">The password for the private key. Pass null if no password.</param> /// <returns>A new instance of CryptoKey from the RSA private key.</returns> public static CryptoKey LoadRsaPrivateKeyFromFile(string pathToPrivateKeyFile, PasswordHandler privateKeyPassword) { using (var privateKeyBio = FileHelpers.Load(pathToPrivateKeyFile)) { using (var rsa = RSA.FromPrivateKey(privateKeyBio, privateKeyPassword, null)) { return new CryptoKey(rsa); } } }
public void TestEncryption() { // ARRANGE // Create a new mainform which also creates a new UserPreferences object, where encryption settings are stored. FormMain mainForm = new FormMain(); PasswordHandler pwh = new PasswordHandler("password", mainForm); FileInformation fi = new FileInformation(); AESencrypter aesEnc = new AESencrypter(fi.GenerateFileInfoHeader(), fi.FileContents, mainForm); // ACT byte[] encryptedFile = aesEnc.EncryptBytes(); // ASSERT Assert.AreNotEqual(fi.FileContents, encryptedFile); }
public void SendMail() { #region RabbitMq var envelope = new MailLetter(); var rbImpl = new RabbitMqImpl(); var connection = RabbitMqService.RabbitMqConnection; var channel = RabbitMqService.RabbitMqModel; RabbitMqService.SetupInitialTopicQueue(channel); channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); envelope = JsonConvert.DeserializeObject <MailLetter>(message); channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false); #region email var clientDetails = new SmtpClient { Port = 587, Host = "smtp.gmail.com", EnableSsl = true, Credentials = new NetworkCredential(envelope.Mime.From, PasswordHandler.GetPassword()) }; var from = new MailAddress(envelope.Mime.From, envelope.Envelope); var to = new MailAddress(envelope.Mime.To, envelope.Recipient); MailMessage mailMessage = new MailMessage(from, to) { Subject = envelope.Mime.Subject, Body = envelope.Mime.TextVersion }; if (envelope.Mime.Attachments.Base64String.Length > 0) { var attachement = new Attachment(new MemoryStream(envelope.Mime.Attachments.Base64String), "Receipt.pdf", MediaTypeNames.Application.Pdf); mailMessage.Attachments.Add(attachement); } try{ clientDetails.Send(mailMessage); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Exception caught while sending email: {0}", ex.ToString()); } #endregion }; channel.BasicConsume(RabbitMqService.SerialisationQueueName, autoAck: false, consumer: consumer); #endregion }
//Insert new player object to the database, if the username was valid after trying to sign up. public async void RegisterNewPlayer(string playerName, string pw) { try { player.Name = playerName; player.Password = PasswordHandler.Encrypt(pw, player.Name); await playerCollection.InsertOneAsync(player); hsCollection = player.ScoreCollection; } catch (Exception e) { Debug.LogWarning(e); } }
public IActionResult Login(User user) { QueryHandler.connect(_configuration); if ((PasswordHandler.verifyPassword(user.Name, user.Password))) { HttpContext.Session.SetString("sessionUser", user.Name); //Authenticate(user.Name); return(RedirectToAction("Editor")); } else { return(RedirectToAction("Index")); } }
public static void OnFirstInit(IGenericRepository <User> userGR, IGenericRepository <Role> roleGR) { userGR.Create(new User { Id = "admin", Name = "Admin", Surname = "Admin", Lastname = "Admin", Email = "*****@*****.**", Login = "******", PhotoId = "default-user-photo", PasswordHash = PasswordHandler.CreatePasswordHash("admin"), RoleId = roleGR.GetAll(x => x.Name == "Admin").FirstOrDefault().Id }); }
public async Task <LoggedDto> EndRegister(EndRegisterDto entity, string uuid) { var token = ValidateRegistrationToken(entity.RegistrationToken); if (await _userService.IsIssetAsync(token.Id)) { throw new ClientException("r-token-already-used"); } else if (_userService.IsIssetByLogin(entity.Login)) { throw new ClientException("r-login-alrd-reg"); } else if (_userService.IsIssetByEmail(token.Claims.First(x => x.Type == "email").Value)) { throw new ClientException("r-email-alrd-reg"); } var user = new User { Id = token.Id, Login = entity.Login, Email = token.Claims.First(x => x.Type == "email").Value, Name = entity.Name, Surname = entity.Surname, Lastname = entity.Lastname, PhotoId = "default-user-photo", Birthday = entity.Birthday.Value, RoleId = int.Parse(token.Claims.First(x => x.Type == "role").Value), PasswordHash = PasswordHandler.CreatePasswordHash(entity.Password) }; var noPermissions = new List <Permission>(); if (token.Claims.First(x => x.Type == "noPermissions").Value.Length > 0) { foreach (var item in token.Claims.First(x => x.Type == "noPermissions").Value.Split(' ')) { noPermissions.Add(new Permission { Id = int.Parse(item) }); } } var usr = await _userService.AddAsync(user, noPermissions); usr.Role = await _roleService.GetAsync(usr.RoleId); return(await _loginService.Login(usr, uuid)); }
private void Login(object obj) { Employee employee = service.FindByUsername(CurrentEmployee.Username); string hashedPassword = PasswordHandler.Md5Encrypt(CurrentEmployee.Password, employee.Salt); if (hashedPassword == employee.Password) { LoggedUser.Employee_id = employee.Employee_id; LoggedUser.Name = employee.Name; LoggedUser.Salt = employee.Salt; LoggedUser.Status = employee.Status; LoggedUser.SurName = employee.SurName; new NavService().NavigateTo("Main"); } }
public bool CheckCredentials(CredentialsDTO credentials) { User user = _unitOfWork.UsersRepository.Get(new UserFilter() { Email = credentials.Login }); if (PasswordHandler.Verify(credentials.Password, user.HashPassword)) { return(true); } else { return(false); } }
public IActionResult Login(Login login) { User user = _context.Users.Where(u => u.Email == login.Email).FirstOrDefault(); if (user != null) { if (PasswordHandler.Validate(login.Password, user.Password)) { HttpContext.Session.SetInt32("userId", user.Id); return(RedirectToAction("Index", "Home")); } } ModelState.AddModelError(string.Empty, "Email or Password is incorrect."); return(View(login)); }
public ActionResult Create([Bind(Include = "Id,UserID,CompanyID,FirstName,LastName,OtherName,Phone,Password,Address,DoB,NextOfKin,NextOfKinNumber,SbDate,SbExpiry,TimeStamp")] Rider rider) { rider.TimeStamp = DateTime.Now; if (ModelState.IsValid) { rider.Password = PasswordHandler.CreatePasswordHash(rider.Password); rider.SbDate = DateTime.Now; rider.SbExpiry = DateTime.Now; db.Riders.Add(rider); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(rider)); }
private void btnpassword_Click(object sender, EventArgs e) { bool istrue = PasswordHandler.Validate(txtpassword.Text, txthash.Text); txtlog.Text += "\r\n > " + istrue; if (istrue == true) { MessageBox.Show("Login successful, you may continue.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); } // txtlog.Text += "\r\n >" + PasswordHandler.Validate(txtpassword.Text, txthash.Text); }
public static RsaKeyPair GenerateRsaPrivateKey(int bits = 2048, BigNumber e = null, RsaKeyGeneratorCallback cb = null, object cbArg = null) { if (e == null) { e = E_F4; } using (var rsa = new RSA()) { BigNumber.GeneratorHandler cbWrapper = null; if (cb != null) { cbWrapper = (x, y, z) => cb(x, y, z); } Cipher enc = null; string pwd = null; PasswordHandler pwdCb = null; // If we choose to encrypt: // Cipher.DES_CBC; // Cipher.DES_EDE3_CBC; // Cipher.Idea_CBC; // Cipher.AES_128_CBC; // Cipher.AES_192_CBC; // Cipher.AES_256_CBC; // and pwd != null || pwdCb != null // We can use a pwdCb to get a password interactively or we can // simply pass in a fixed password string (no cbPwd, just pwd) if (pwd != null) { pwdCb = DefaultPasswordHandler; } // Ref: http://openssl.org/docs/manmaster/crypto/RSA_generate_key_ex.html rsa.GenerateKeys(bits, e, cbWrapper, cbArg); using (var bio = BIO.MemoryBuffer()) { // Ref: http://openssl.org/docs/manmaster/crypto/PEM_write_bio_RSAPrivateKey.html rsa.WritePrivateKey(bio, enc, pwdCb, pwd); return(new RsaKeyPair(bits, e.ToHexString(), bio.ReadString())); } } }
public void AddDriver(object obj) { if (SelectedStatus == "Active") { CurrentDriver.Status = true; } else { CurrentDriver.Status = false; } CurrentDriver.Salt = PasswordHandler.GenerateSalt(); CurrentDriver.Password = PasswordHandler.Md5Encrypt(CurrentDriver.Password, CurrentDriver.Salt); service.Add(CurrentDriver); Messenger.Default.Send(CurrentDriver); new NavService().NavigateTo("Drivers"); }
public async Task <LoggedDto> Login(LoginDto entity, string uuid) { var user = _userService.GetAllByLogin(entity.Login); if (user == null || !PasswordHandler.Validate(entity.Password, user.PasswordHash)) { throw new ClientException("l-pass-log-inc"); } else if (user.Banned != null) { throw new ClientException("l-user-banned", user.Banned); } else if (_tokenService.CountLoggedDevices(user.Id) > 10) { throw new ClientException("l-too-many-devices"); } return(await Login(user, uuid)); }
public IActionResult Register(UserModel model) { if (ModelState.IsValid) { model.Password = PasswordHandler.Hash(model.Password); if (this.UserRepository.Register(model)) { Response.Redirect("/Account/Login"); //return null; } else { // Failed ModelState.AddModelError("FailedToRegister", "Something went wrong."); } } return(View(model)); }
public ActionResult <Response> Post(User user) { try { User userFromDb = appDbContext.Users.FirstOrDefault(u => u.Email == user.Email); if (userFromDb != null) { return(new Response(user, 409, "Email already exists")); } user.Password = PasswordHandler.Encrypt(user.Password, "sblw-3hn8-sqoy19"); appDbContext.Users.Add(user); appDbContext.SaveChanges(); return(new Response(user, 200, "User Created Successfully")); } catch (Exception ex) { return(new Response(null, 404, ex.Message)); } }
private void HandleNewAccount() { // Input validation. if (ValidateInput()) { // Get Random UserID int userID = MakeUserID(); // fill out a new customer info object with their info from // the fields CustomerInfo customerInfo = new() { Name = NameInput.Text, Address = AddressInput.Text, City = CityInput.Text, State = StateInput.Text, Zip = ZipInput.Text, PhoneNumber = PhoneInput.Text, Age = (int)AgeInput.Value, CreditCardNumber = CreditCardInput.Text }; // fill out a new user object with their info User user = new() { LoginId = userID.ToString(), HashedPass = PasswordHandler.HashPassword(PasswordInput.Password), UserRole = Role.CUSTOMER, CustInfo = customerInfo }; // add the user to the database UserUtilities.AddUserToDB(user); // and display information to the user about their account being created outputInfo.Title = "Account Creation Successful!"; outputInfo.Message = $"Your Login ID is: {userID}, please remember it for future logins!"; outputInfo.Severity = InfoBarSeverity.Success; outputInfo.IsOpen = true; } }
/// <summary> /// Method to create new users /// </summary> /// <param name="user"></param> /// <param name="password"></param> /// <returns></returns> public Users Create(Users user, string password) { // Validate password if (string.IsNullOrWhiteSpace(password)) { throw new AppException("Password is required"); } if (_context.Users.Any(x => x.UserName == user.UserName)) { throw new AppException("Username \"" + user.UserName + "\" is already taken"); } byte[] passwordHash, passwordSalt; PasswordHandler.CreatePasswordHash(password, out passwordHash, out passwordSalt); _context.Users.Add(user); _context.SaveChanges(); return(user); }
public ActionResult <Response> Post([FromBody] User user) { try { var fetched_user = appDbContext.Users.SingleOrDefaultAsync(p => p.Email == user.Email); if (fetched_user.Result != null && user.Password == PasswordHandler.Decrypt(fetched_user.Result.Password, "sblw-3hn8-sqoy19")) { HttpContext.Session.SetString("is_login", "true"); HttpContext.Session.SetString("userid", fetched_user.Result.Id.ToString()); return(new Response(null, 200, "Logged in succesfully")); } else { HttpContext.Session.SetString("is_login", "false"); return(new Response(null, 200, "Login Failed")); } } catch (Exception ex) { return(new Response(null, 404, ex.Message)); } }
public static User MapWithPasswordHashToEntity(UserDetailModel detailModel) { var passwordHandler = new PasswordHandler(); var user = new User { Id = detailModel.Id, Name = detailModel.Name, Email = detailModel.Email, Password = passwordHandler.HashPassword(detailModel.Password), }; foreach (var activity in detailModel.Activities) { user.Activities.Add(ActivityMapper.MapToEntity(activity)); } foreach (var team in detailModel.Teams) { user.Teams.Add(TeamUserMapper.MapToEntity(team, MapToListModel(user))); } return(user); }
/// <summary> /// Method for updating users /// </summary> /// <param name="userParam"></param> /// <param name="password"></param> public void Update(Users userParam, string password = null) { // Find user by id var user = _context.Users.Find(userParam.Id); // If there is no user throw app exception if (user == null) { throw new AppException("User not found"); } if (userParam.UserName != user.UserName) { // Username has changed so check if the new username is already taken if (_context.Users.Any(x => x.UserName == userParam.UserName)) { throw new AppException("Username " + userParam.UserName + " is already taken"); } } // Update user properties user.FirstName = userParam.FirstName; user.LastName = userParam.LastName; user.Email = userParam.Email; user.PhoneNumber = userParam.PhoneNumber; user.UserName = userParam.UserName; // update password if it was entered if (!string.IsNullOrWhiteSpace(password)) { byte[] passwordHash, passwordSalt; PasswordHandler.CreatePasswordHash(password, out passwordHash, out passwordSalt); //user.PasswordHash = ; } _context.Users.Update(user); _context.SaveChanges(); }
//Verify if user put the correct credentials on login menu and return a playerobject matching those credentials from the database if he did. public PlayerRef GetPlayerByCredentials(string playerName, string pw) { playerList = playerCollection.Find(new BsonDocument()).ToList(); foreach (var playerObject in playerList) { if (playerObject.Name.Equals(playerName)) { var decrypted = PasswordHandler.Decrypt(playerObject.Password, playerObject.Name); if (decrypted.Equals(pw)) { LoginSuccess = true; player = playerObject; hsCollection = playerObject.ScoreCollection; } else { LoginSuccess = false; } } } return(player); }
public ActionResult <Response> Put(User user) { try { if (!string.IsNullOrEmpty(HttpContext.Session.GetString("is_login"))) { var userId = int.Parse(HttpContext.Session.GetString("userid")); User userFromDb = appDbContext.Users.Where(u => u.Id == userId).FirstOrDefault(); if (userFromDb != null) { userFromDb.Email = user.Email; userFromDb.Name = user.Name; user.Password = PasswordHandler.Encrypt(user.Password, "sblw-3hn8-sqoy19"); userFromDb.Password = user.Password; userFromDb.ContactNumber = user.ContactNumber; userFromDb.Unit = user.Unit; userFromDb.Street = user.Street; userFromDb.City = user.City; userFromDb.PostalCode = user.PostalCode; userFromDb.AccountType = userFromDb.AccountType; appDbContext.SaveChanges(); return(new Response(userFromDb)); } else { return(new Response(null, 404, "No Data Found for User")); } } else { return(new Response(null, 403, "Authentication Failure")); } } catch (Exception ex) { return(new Response(null, 404, ex.Message)); } }
/// <summary> /// Starts the dictionary cracking process. /// </summary> public static void RunCracking() { List <string> usersRaw = ServerMessaging.SetupPasswords(); List <UserInfo> userInfos = PasswordHandler.ReadPasswordList(usersRaw); remainingPasswords = userInfos.Count; List <UserInfoClearText> result = new List <UserInfoClearText>(); while (ServerMessaging.SetupValidChunk()) { foreach (string line in Client.Instance.Chunk) { IEnumerable <UserInfoClearText> partialResult = CheckVariations.CheckWordWithVariations(line, userInfos); result.AddRange(partialResult); remainingPasswords -= partialResult.Count(); } if (result.Count > 0) { ServerMessaging.WriteResults(result); } result = new List <UserInfoClearText>(); } }
/* * Login + Logout + Register methods */ public int Login(string username, string password, string port) { /* * Return values: * 1 - Correct username and password * 2 - Correct username and password, but user already logged it * 3 - Correct username, but wrong password * 4 - Non-existent username */ var collection = database.GetCollection <UserModel>("User"); var filter = Builders <UserModel> .Filter.Eq("Username", username); var user = collection.Find(filter).FirstOrDefault(); if (user != null) { if (PasswordHandler.Validate(password, user.Password)) { if (!UserIsActive(username)) { return(1); } else { return(2); } } else { return(3); } } else { return(4); } }
public ActionResult Post([FromBody] User userObj) { try { User user = appDbContext.User.SingleOrDefault(p => p.Email == userObj.Email); if (user != null && userObj.Password == PasswordHandler.Decrypt(user.Password, "sblw-3hn8-sqoy19")) { string token = authService.Authenticate(user.Email); user.Token = token; user.Password = null; return(Ok(user)); } else { return(BadRequest(new { message = "Email or password is wrong", })); } } catch (Exception ex) { return(BadRequest(new { message = ex.Message })); } }
public IActionResult Post(User user) { if (user.Email.Equals(null) || user.Password.Equals(null)) { return(BadRequest(new { message = "Email or password can not be empty" })); } User userFromDb = appDb.User.FirstOrDefault(u => u.Email == user.Email); if (userFromDb != null) { return(BadRequest(new { message = "Email already exists", user.Email })); } user.Password = PasswordHandler.Encrypt(user.Password, "sblw-3hn8-sqoy19"); string token = authService.Authenticate(user.Email); appDb.User.Add(user); //string token = authService.Authenticate(user.Email); appDb.SaveChanges(); user.Token = token; user.Password = null; return(Ok(user)); }
public PasswordThunk(PasswordHandler client, object arg) { this.OnPassword = client; this.arg = arg; }
// Method to hash a password private string HashPassword(string password) { return(PasswordHandler.CreatePasswordHash(password)); }
/// <summary> /// Calls PEM_write_bio_RSAPrivateKey() /// </summary> /// <param name="bio"></param> /// <param name="enc"></param> /// <param name="passwd"></param> /// <param name="arg"></param> public void WritePrivateKey(BIO bio, Cipher enc, PasswordHandler passwd, object arg) { PasswordThunk thunk = new PasswordThunk(passwd, arg); Native.ExpectSuccess(Native.PEM_write_bio_RSAPrivateKey( bio.Handle, this.ptr, enc == null ? IntPtr.Zero : enc.Handle, null, 0, thunk.Callback, IntPtr.Zero)); }
/// <summary> /// Calls PEM_read_bio_RSAPrivateKey() /// </summary> /// <param name="bio"></param> /// <param name="callback"></param> /// <param name="arg"></param> /// <returns></returns> public static RSA FromPrivateKey(BIO bio, PasswordHandler callback, object arg) { PasswordThunk thunk = new PasswordThunk(callback, arg); IntPtr ptr = Native.PEM_read_bio_RSAPrivateKey(bio.Handle, IntPtr.Zero, thunk.Callback, IntPtr.Zero); return new RSA(Native.ExpectNonNull(ptr), true); }
public PasswordThunk(PasswordHandler client, object arg) { this.OnPassword = client; this.arg = arg; }
/// <summary> /// Loads the private key file from the specified path. Uses the password parameter to decrypt the /// file containing the password if it has one. /// </summary> /// <param name="pathToPrivateKey">The full path and name of the file containing the private key.</param> /// <param name="password">Uses the PasswordHandler to decrypt the private key file. Leave null if file is not password protected.</param> public void LoadCertificateSigningRequestPrivateKeyFromFile(string pathToPrivateKey, PasswordHandler password) { this.Key = FileHelpers.LoadRsaPrivateKeyFromFile(pathToPrivateKey, password); }
/// <summary> /// Calls PEM_read_bio_PrivateKey() /// </summary> /// <param name="bio"></param> /// <param name="handler"></param> /// <param name="arg"></param> /// <returns></returns> public static CryptoKey FromPrivateKey(BIO bio, PasswordHandler handler, object arg) { var thunk = new PasswordThunk(handler, arg); var ptr = Native.ExpectNonNull(Native.PEM_read_bio_PrivateKey( bio.Handle, IntPtr.Zero, thunk.Callback, IntPtr.Zero )); return new CryptoKey(ptr, true); }
/// <summary> /// Calls PEM_write_bio_PKCS8PrivateKey /// </summary> /// <param name="bp"></param> /// <param name="cipher"></param> /// <param name="handler"></param> /// <param name="arg"></param> public void WritePrivateKey(BIO bp, Cipher cipher, PasswordHandler handler, object arg) { var thunk = new PasswordThunk(handler, null); Native.ExpectSuccess(Native.PEM_write_bio_PKCS8PrivateKey(bp.Handle, ptr, cipher.Handle, IntPtr.Zero, 0, thunk.Callback, IntPtr.Zero)); }
private void btnhash_Click(object sender, EventArgs e) { txtlog.Text += "\r\n > " + PasswordHandler.CreatePasswordHash(txtpassword.Text); }