internal WsAccount(Action onChange, IDataProtector protector, string userName, string userPasswordHash = null) : this(new WsSerializableAccount(userName), onChange, protector) { if (string.IsNullOrWhiteSpace(userPasswordHash) == false) { AccountConfig.UserPasswordHashEnc = _protector.Encrypt(userPasswordHash); } }
static void Main(string[] args) { Write("Enter a message that you want to encrypt: "); string message = ReadLine(); Write("Enter a password: "******"Encrypted text: {cryptoText}"); Write("Enter the password: "******"Decrypted text: {clearText}"); } catch (CryptographicException ex) { WriteLine("{0}\nMore details: {1}", arg0: "You entered the wrong password!", arg1: ex.Message); } catch (Exception ex) { WriteLine("Non-cryptographic exception: {0}, {1}", arg0: ex.GetType().Name, arg1: ex.Message); } }
private static void EncryptionPrompt() { Write("Enter text to encrypt: "); string message = ReadLine(); Write("Enter a password: "******"Encrypted text: {cryptoText}"); Write("Re-enter the password: "******"Decrypted text: {clearText}"); } catch (CryptographicException ex) { WriteLine($"{"You entered the wrong password!"}\nMore details: {ex.Message}"); } catch (Exception ex) { WriteLine("Non cryptographic exception: {0}, {1}", ex.GetType().Name, ex.Message); } }
static void Main(string[] args) { Write("Enter text to encrypt: "); string message = ReadLine(); Write("Enter Password: "******"Encrypted text: {cryptoText}"); Write("Enter password to decrypt: "); string passwordInput = ReadLine(); try { string clearText = Protector.Decrypt(cryptoText, passwordInput); WriteLine($"Decrypted text: {clearText}"); } catch (CryptographicException e) { WriteLine($"Wrong password. Details: {e.Message}"); } catch (Exception e) { WriteLine($"Something went wrong: {e.Message}"); } }
public void send(MeterCommand command) { var sender = JsonSerializer.Serialize(command); var encrypt = Protector.Encrypt(sender, "secret"); listener.Send(Encoding.UTF8.GetBytes(encrypt)); }
public ActionResult Register(RegisterModel model) { if (ModelState.IsValid) { using (db) { User user = db.Users.FirstOrDefault(u => u.Login == model.Name && u.Password == model.Password); if (user == null) { string encryptedPassword = Protector.Encrypt(model.Password); db.Users.Add(new User { Login = model.Name, Password = encryptedPassword, CreationDate = DateTime.Now, RoleId = 2 }); db.SaveChanges(); user = db.Users.Where(u => u.Login == model.Name && u.Password == encryptedPassword).FirstOrDefault(); if (user != null) { FormsAuthentication.SetAuthCookie(model.Name, true); return(RedirectToAction("Index", "Home")); } } else { ModelState.AddModelError("", "User with such login and password already exists"); } } } return(View(model)); }
static void Main(string[] args) { Write("Enter a message that you want to encrypt: "); string message = ReadLine(); Write("Enter a password: "******"Encrypted text: {cryptoText}"); Write("Enter a password: "******"Decrypted text: {clearText}"); } catch { WriteLine( "Enable to decrypt because you entered the wrong password!" ); } }
static void Main(string[] args) { Write("Enter a message that you want to encrypt : "); string message = ReadLine(); Write("Enter a password : "******"Encrypted text : {cryptoText}"); Write("Enter the password"); string getPassword = ReadLine(); try { string clearText = Protector.Decrypt(cryptoText, getPassword); WriteLine($"Decrypted text : {clearText}"); } catch (CryptographicException ex) { WriteLine($"You entered the wrong password ... UnU\n More Details : {ex.Message}"); } catch (Exception ex) { WriteLine($"Some other thing went wrong {ex.Message}"); } }
public ActionResult Login(LoginModel model) { if (ModelState.IsValid) { using (db) { string encryptedPassword = Protector.Encrypt(model.Password); // Searching user in db User user = db.Users.FirstOrDefault(u => u.Login == model.Name && u.Password == encryptedPassword); if (user != null) { FormsAuthentication.SetAuthCookie(model.Name, true); if (user.RoleId == 1) { return(RedirectToAction("Index", "Home", new { Area = "Admin" })); } return(RedirectToAction("Index", "Home")); } else { ModelState.AddModelError("", "There is no user with such login and password"); } } } return(View(model)); }
static void Main(string[] args) { Write("Enter a message you want to encrypt:"); string message = ReadLine(); Write("Enter a password:"******"\nEncrypted text: {cryptoText}"); Write("Enter the password:"******"\nDecrypted text: {clearText}"); } catch (CryptographicException ex) { WriteLine($"Wrong password entered. {ex.Message}"); } catch (System.Exception ex) { WriteLine($"Non crytographic exception: {ex.GetType()} has message {ex.Message}"); } }
static void BasicCrypto() { Console.Write("Enter a message that you want to encrypt: "); string message = Console.ReadLine(); Console.Write("Enter a password: "******"Encrypted text: {cryptoText}"); Console.Write("Enter the password: "******"Decrypted text: {clearText}"); } catch { Console.WriteLine("Enable to decrypt because you entered the wrong password!"); } }
private static void WritetoXmlFile(List <Customer> customers, string passwordToEncrypt) { // define an XML file to write to string xmlFile = Combine(CurrentDirectory, "..", "protected-customers.xml"); var xmlWriter = XmlWriter.Create(xmlFile, new XmlWriterSettings { Indent = true }); xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("customers"); foreach (Customer customer in customers) { xmlWriter.WriteStartElement("customer"); xmlWriter.WriteElementString("name", customer.Name); xmlWriter.WriteElementString("creditcard", Protector.Encrypt(customer.CreditCard, passwordToEncrypt)); // to protect the password we must salt and hash it, and store the random salt used var user = Protector.Register(customer.Name, customer.Password); xmlWriter.WriteElementString("password", user.SaltedHashedPassword); xmlWriter.WriteElementString("salt", user.Salt); xmlWriter.WriteEndElement(); // customer } xmlWriter.WriteEndElement(); // customers xmlWriter.WriteEndDocument(); xmlWriter.Close(); }
public async Task <AppUser> GetUser(AppUser appUser) { // Attempt to validate user var passwordEncrypted = Protector.Encrypt(appUser.Password, string.Empty); var userClaims = FindEntityBy(u => u.UserName.ToLower() == appUser.UserName.ToLower() && u.Password == passwordEncrypted); return(userClaims); }
public void ParseData() { var data = ParseCSV(Resources.TeamPlayerImportTemplate); foreach (var line in data) { var name = line[0].Trim(); var idNum = line[1].Trim(); string realIdNum = null; if (idNum.Length == 8) { realIdNum = "0" + idNum; } else if (idNum.Length == 9) { realIdNum = idNum; } /*else * { * var warning = true; * }*/ var email = line[2].Trim(); var birthStr = Convert.ToDateTime(line[3].Trim()); var city = line[6].Trim(); var teamId = Convert.ToInt32(line[8].Trim()); User user = db.Users.FirstOrDefault(u => u.IdentNum == realIdNum || u.IdentNum == idNum || u.Email == email); if (user == null) { user = new User { FullName = name, IdentNum = realIdNum, Email = email, BirthDay = birthStr, City = city, Password = Protector.Encrypt(realIdNum), TypeId = 4, GenderId = 0, IsActive = true, Image = idNum + ".jpg" }; user.TeamsPlayers.Add(new TeamsPlayer { TeamId = teamId, ShirtNum = 0, IsActive = true }); var us = db.Users.Add(user); int changes = db.SaveChanges(); } //break; } }
public void WriteTCP(MeterCommand command) { var sender = JsonSerializer.Serialize(command); var encrypt = Protector.Encrypt(sender, "secret"); foreach (var item in server.GetClients()) { server.Send(item, Encoding.UTF8.GetBytes(encrypt)); } }
static void Main(string[] args) { string plainText = "Hallo Baum"; string password = "******"; string cryptoText = Protector.Encrypt(plainText, password); Console.WriteLine($"cryptoText...: {cryptoText}"); string encryptedText = Protector.Decrypt(cryptoText, password); Console.WriteLine($"encryptedText: {encryptedText}"); }
public async Task <IHttpActionResult> PostRegisterFan(FanRegisterBindingModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (db.Users.Where(u => u.UserName == model.UserName).Count() > 0) { return(BadRequest(Messages.UsernameExists)); } if (db.Users.Where(u => u.Email == model.Email).Count() > 0) { return(BadRequest(Messages.EmailExists)); } var lang = db.Languages.FirstOrDefault(x => x.Code == model.Language); var user = new User() { UserName = model.UserName, Email = model.Email, Password = Protector.Encrypt(model.Password), UsersType = db.UsersTypes.FirstOrDefault(t => t.TypeRole == AppRole.Fans), IsActive = true, LangId = lang != null ? lang.LangId : 1 }; foreach (var item in model.Teams) { user.TeamsFans.Add(new TeamsFan { TeamId = item.TeamId, UserId = user.UserId, LeageId = item.LeagueId }); } var newUser = db.Users.Add(user); await db.SaveChangesAsync(); if (newUser != null) { return(Ok()); } else { return(InternalServerError()); } }
static void Main(string[] args) { Write("Enter a message that you want to encrypt: "); string message = ReadLine(); Write("Enter a password: "******"Encrypted text: {cryptoText}"); string clearText = Protector.Decrypt(cryptoText, password); WriteLine($"Decrypted text: {clearText}"); }
public ActionResult CreatePlayer(TeamPlayerForm frm) { //Thread.CurrentThread.CurrentCulture = new CultureInfo("he-IL"); var user = playersRepo.GetUserByIdentNum(frm.IdentNum); frm.Genders = new SelectList(playersRepo.GetGenders(), "GenderId", "Title"); frm.Positions = new SelectList(posRepo.GetByTeam(frm.TeamId), "PosId", "Title"); if (playersRepo.ShirtNumberExists(frm.TeamId, frm.ShirtNum)) { //Shirt number taken ModelState.AddModelError("ShirtNum", Messages.ShirtAlreadyExists); } if (user != null) { if (playersRepo.PlayerExistsInTeam(frm.TeamId, user.UserId)) { //Player exists in team ModelState.AddModelError("IdentNum", Messages.PlayerAlreadyInTeam); } } if (!ModelState.IsValid) { return(PartialView("_EditPlayer", frm)); } if (user == null) { //New User user = new User(); UpdateModel(user); user.Password = Protector.Encrypt(frm.IdentNum); user.TypeId = 4; // player usersRepo.Create(user); } var tp = new TeamsPlayer(); UpdateModel(tp); tp.UserId = user.UserId; tp.SeasonId = frm.SeasonId; playersRepo.AddToTeam(tp); playersRepo.Save(); TempData["Success"] = true; return(PartialView("_EditPlayer", frm)); }
private void saveEncryptedText( ) { string inputText = tboxTopLeft.Text; string password = tboxTopLeft2.Text; cleanTextBoxes( ); string encryptText = Protector.Encrypt(inputText, password); using (StreamWriter sw = File.CreateText(textFilePath)) { sw.Write(encryptText); } tbTopLeft.Text = $"Enctypted text to record: \n" + $"{encryptText}"; }
private static void Main(string[] args) { Console.WriteLine("Enter a message that you want to encrypt: "); var message = Console.ReadLine(); Console.WriteLine("Enter a password: "******"Encrypted text: {cryptoText}"); var clearText = Protector.Decrypt(cryptoText, password); Console.WriteLine($"Decrypted text: {clearText}"); Console.ReadLine(); }
private User UsernamePasswordLogin(DataEntities db, OAuthGrantResourceOwnerCredentialsContext context) { if (string.IsNullOrEmpty(context.Password) || string.IsNullOrEmpty(context.UserName)) { context.SetError("UsernamePassword_grant", Messages.UsernameOrPassMissing); return(null); } string encryptedPass = Protector.Encrypt(context.Password); User user = db.Users.FirstOrDefault(u => u.UserName == context.UserName && u.Password == encryptedPass); if (user == null) { context.SetError("UsernamePassword_grant", Messages.InvalidLogin); } return(user); }
public void EncryptTest() { //Arrange string messageToEncrypt = "There is a fox on the mountain of the tree where the fox is picking cottons"; string pass = "******"; //Act string Encrypted = Protector.Encrypt(messageToEncrypt, pass); Console.WriteLine("The encrypted message is:"); Console.WriteLine(Encrypted); string Decrypted = Protector.Decrypt(Encrypted, pass); //Assert Assert.AreEqual( messageToEncrypt, Decrypted); }
public ActionResult Edit(UserForm frm) { bool isExists = uRepo.IsUsernameExists(frm.UserName, frm.UserId); if (isExists) { ModelState.AddModelError("UserName", Messages.UserNameExists); } if (!ModelState.IsValid) { frm.RolesList = new SelectList(uRepo.GetTypes(), "TypeId", "TypeName"); return(PartialView("_Edit", frm)); } var user = new User(); if (frm.UserId != 0) { user = uRepo.GetById(frm.UserId); if (frm.IsBlocked) { LoginService.RemoveSession(user.SessionId); } } else { user.IsActive = true; uRepo.Create(user); } UpdateModel(user); user.Password = Protector.Encrypt(frm.Password); uRepo.Save(); return(Content("ok")); }
protected override void Seed(UserContext db) { Role admin = new Role { Name = "admin" }; Role user = new Role { Name = "user" }; string enryptedPassword = Protector.Encrypt("admin"); db.Roles.Add(admin); db.Roles.Add(user); db.Users.Add(new User { Id = 1, Login = "******", Password = enryptedPassword, CreationDate = DateTime.Now, Role = admin }); base.Seed(db); }
static void Main(string[] args) { Write("Enter your name: "); string name = ReadLine(); Write("Enter your credit card number: "); string creditCardNumber = ReadLine(); Write("Enter your password: "******"Customers", new XElement("Customer")); XElement customer = customers.Element("Customer"); customer.Add(new XElement("name", name)); customer.Add(new XElement("creditcard", encryptedCreditCardNumber)); customer.Add(new XElement("password", saltedAndHashedPassword)); string xmlPath = Path.Combine(Environment.CurrentDirectory, Path.GetRandomFileName() + ".xml"); using (StreamWriter stream = File.CreateText(xmlPath)) { stream.Write(customers.ToString()); } using (StreamReader stream = File.OpenText(xmlPath)) { string cusomersString = stream.ReadToEnd(); XDocument xml = XDocument.Parse(cusomersString); encryptedCreditCardNumber = xml.Element("Customers").Element("Customer").Element("creditcard").Value; creditCardNumber = Protector.Decrypt(encryptedCreditCardNumber, EncryptionPassword); WriteLine($"Decrypted credit card number: {creditCardNumber}"); } }
public ActionResult CreateWorker(CreateWorkerForm frm) { if (usersRepo.GetByIdentityNumber(frm.IdentNum) != null) { var tst = Messages.IdIsAlreadyExists; tst = string.Format(tst, "\""); ModelState.AddModelError("IdentNum", tst); } if (usersRepo.GetByEmail(frm.Email) != null) { var tst = Messages.EmailAlreadyExists; tst = string.Format(tst, "\""); ModelState.AddModelError("Email", tst); } switch (frm.RelevantEntityLogicalName) { case LogicaName.Union: frm.JobsList = new SelectList(jobsRepo.GetByUnion(frm.RelevantEntityId), "JobId", "JobName"); break; case LogicaName.League: frm.JobsList = new SelectList(jobsRepo.GetByLeague(frm.RelevantEntityId), "JobId", "JobName"); break; case LogicaName.Team: frm.JobsList = new SelectList(jobsRepo.GetByTeam(frm.RelevantEntityId), "JobId", "JobName"); break; case LogicaName.Club: frm.JobsList = new SelectList(jobsRepo.GetClubJobs(frm.RelevantEntityId), "JobId", "JobName"); break; default: frm.JobsList = new List <SelectListItem>(); break; } if (ModelState.IsValid) { var user = new User(); UpdateModel(user); user.Password = Protector.Encrypt(frm.Password); user.TypeId = 3; usersRepo.Create(user); var uJob = new UsersJob { JobId = frm.JobId, UserId = user.UserId, SeasonId = frm.SeasonId }; switch (frm.RelevantEntityLogicalName) { case LogicaName.Union: uJob.UnionId = frm.RelevantEntityId; break; case LogicaName.League: uJob.LeagueId = frm.RelevantEntityId; break; case LogicaName.Team: uJob.TeamId = frm.RelevantEntityId; break; case LogicaName.Club: uJob.ClubId = frm.RelevantEntityId; break; } var jRepo = new JobsRepo(); jRepo.AddUsersJob(uJob); jRepo.Save(); ViewBag.SeasonId = frm.SeasonId; TempData["WorkerAddedSuccessfully"] = true; } return(PartialView("_CreateWorker", frm)); }
public IHttpActionResult PostUpdateUser(UserDetails frm) { if (!ModelState.IsValid) { return(BadRequest("נתון לא תקין")); } var user = base.CurrentUser; if (!string.IsNullOrEmpty(frm.OldPassword) && !string.IsNullOrEmpty(frm.NewPassword)) { string pass = Protector.Encrypt(frm.OldPassword); if (user.Password != pass) { return(BadRequest("סיסמה שגוייה")); } user.Password = Protector.Encrypt(frm.NewPassword); } var lang = db.Languages.FirstOrDefault(x => x.Code == frm.Language); if (!string.IsNullOrEmpty(frm.Email)) { user.Email = frm.Email; } user.FullName = frm.FullName != null ? frm.FullName : user.FullName; user.UserName = frm.UserName != null ? frm.UserName : user.UserName; user.LangId = lang != null ? lang.LangId : user.LangId; if (frm.Teams != null && frm.Teams.Any()) { db.TeamsFans.RemoveRange(user.TeamsFans); user.TeamsFans.Clear(); foreach (var t in frm.Teams) { var team = db.Teams.FirstOrDefault(x => x.TeamId == t.TeamId); var league = db.Leagues.FirstOrDefault(x => x.LeagueId == t.LeagueId); if (team != null && league != null) { user.TeamsFans.Add(new TeamsFan { TeamId = t.TeamId, UserId = user.UserId, LeageId = t.LeagueId, Team = team, League = league, User = user }); } } } user.Notifications.ToList().ForEach(t => user.Notifications.Remove(t)); db.SaveChanges(); var notesList = db.Notifications.ToList(); if (!frm.IsStartAlert) { var nItem = notesList.FirstOrDefault(t => t.Type == "StartAlert"); user.Notifications.Add(nItem); } if (!frm.IsTimeChange) { var nItem = notesList.FirstOrDefault(t => t.Type == "TimeChange"); user.Notifications.Add(nItem); } if (!frm.IsGameRecords) { var nItem = notesList.FirstOrDefault(t => t.Type == "GameRecords"); user.Notifications.Add(nItem); } if (!frm.IsGameScores) { var nItem = notesList.FirstOrDefault(t => t.Type == "GameScores"); user.Notifications.Add(nItem); } db.SaveChanges(); return(Ok("saved")); }
public ActionResult Edit(PlayerFormView frm) { // Thread.CurrentThread.CurrentCulture = new CultureInfo("he-IL"); int maxFileSize = GlobVars.MaxFileSize * 1000; var savePath = Server.MapPath(GlobVars.ContentPath + "/players/"); if (!ModelState.IsValid) { if (frm.LeagueId != 0) { return(RedirectToAction("Edit", new { id = frm.UserId, seasonId = frm.SeasonId, leagueId = frm.LeagueId, teamId = frm.CurrentTeamId })); } return(RedirectToAction("Edit", new { id = frm.UserId, seasonId = frm.SeasonId, clubId = 0, teamId = frm.CurrentTeamId })); } var pl = new User(); if (frm.UserId != 0) { pl = usersRepo.GetById(frm.UserId); TeamsPlayer teamsPlayer = pl.TeamsPlayers .FirstOrDefault(x => x.UserId == pl.UserId && x.SeasonId == frm.SeasonId && x.TeamId == frm.CurrentTeamId); if (teamsPlayer == null) { return(RedirectToAction("NotFound", "Error")); } teamsPlayer.IsPlayereInTeamLessThan3year = frm.IsPlayereInTeamLessThan3year; teamsPlayer.HandicapLevel = frm.HandicapLevel; } else { usersRepo.Create(pl); } UpdateModel(pl); pl.Password = Protector.Encrypt(frm.Password); pl.TypeId = 4; usersRepo.Save(); var imageFile = GetPostedFile("ImageFile"); if (imageFile != null) { if (imageFile.ContentLength > maxFileSize) { ModelState.AddModelError("ImageFile", Messages.FileSizeError); } else { var newName = SaveFile(imageFile, pl.UserId); if (newName == null) { ModelState.AddModelError("ImageFile", Messages.FileError); } else { if (!string.IsNullOrEmpty(pl.Image)) { FileUtil.DeleteFile(savePath + pl.Image); } pl.Image = newName; } } } if (ModelState.IsValid) { usersRepo.Save(); TempData["Saved"] = true; } else { TempData["ViewData"] = ViewData; } if (frm.LeagueId != 0) { return(RedirectToAction("Edit", new { id = pl.UserId, seasonId = frm.SeasonId, leagueId = frm.LeagueId, teamId = frm.CurrentTeamId })); } return(RedirectToAction("Edit", new { id = pl.UserId, seasonId = frm.SeasonId, clubId = 0, teamId = frm.CurrentTeamId })); }
public void Index(string message, string password) { var cryptoText = Protector.Encrypt(message, password); var clearText = Protector.Decrypt(cryptoText, password); }