コード例 #1
0
ファイル: Program.cs プロジェクト: OliverZott/book-cs
        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}");
            }
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: tamim-kabir/C-Sharp-Ex
        static void testCryptoGraphy()
        {
            Write("Enter a massage :");
            string massage = ReadLine();

            Write("Enter a password :"******"Encrypted text :{cryptoText}");
            Write("Enter a password :"******"Decrypted text: {clearText}");
            }
            catch (CryptographicException cex)
            {
                WriteLine($"You Entered a wrong password! \nMore details: {cex.Message}");
            }
            catch (Exception ex)
            {
                WriteLine($"Non-Cryptographic Exception {ex.GetType().Name}, {ex.Message}");
            }
        }
コード例 #3
0
        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}");
            }
        }
コード例 #4
0
ファイル: Program.cs プロジェクト: aguimar/cs7dotnetcore2
        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!"
                    );
            }
        }
コード例 #5
0
        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);
            }
        }
コード例 #6
0
        public MeterCommand ReadTCP(DataReceivedFromClientEventArgs message)
        {
            var received = Encoding.UTF8.GetString(message.Data, 0, message.Data.Length);
            var decrypt  = Protector.Decrypt(received, "secret");

            return(JsonSerializer.Deserialize <MeterCommand>(decrypt));
        }
コード例 #7
0
        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}");
            }
        }
コード例 #8
0
        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!");
            }
        }
コード例 #9
0
        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);
            }
        }
コード例 #10
0
ファイル: Program.cs プロジェクト: AlexGruebel/CSharpTraining
        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}");
        }
コード例 #11
0
 public bool TryGetUserPasswordHash(out string userPasswordHash)
 {
     if (string.IsNullOrWhiteSpace(AccountConfig.UserPasswordHashEnc))
     {
         userPasswordHash = null;
     }
     else
     {
         userPasswordHash = _protector.Decrypt(AccountConfig.UserPasswordHashEnc);
     }
     return(userPasswordHash != null);
 }
コード例 #12
0
        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}");
        }
コード例 #13
0
        static void Main(string[] args)
        {
            Write("Password: "******"protected-customers.xml");

            if (!File.Exists(file))
            {
                WriteLine("File not found");
                return;
            }

            var xmlReader = XmlReader.Create(file, new XmlReaderSettings {
                IgnoreWhitespace = true
            });

            var decrypt = new Customer();

            while (xmlReader.Read())
            {
                if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == "customer")
                {
                    xmlReader.Read();
                    string Dname = xmlReader.ReadElementContentAsString();
                    string DcreditcardEncrypted = xmlReader.ReadElementContentAsString();
                    string Dcreditcard          = null;
                    try
                    {
                        Dcreditcard = Protector.Decrypt(DcreditcardEncrypted, password);
                    }
                    catch (System.Exception)
                    {
                        WriteLine($"Failed to decrypt {Dname}'s credit card.");
                        return;
                    }
                    string passwordHashed = xmlReader.ReadElementContentAsString();

                    decrypt = new Customer
                    {
                        name       = Dname,
                        creditCard = Dcreditcard,
                        password   = passwordHashed
                    };
                }

                WriteLine($"Decrypt result: {decrypt.name} {decrypt.password} {decrypt.creditCard}");
            }
        }
コード例 #14
0
        public ActionResult PasswordRecovery(PasswordRecoveryViewModel vm)
        {
            User usr = uRepo.GetByUsername(vm.UserName.Trim());

            if (usr == null)
            {
                ModelState.AddModelError("UserName", "המשתמש לא נמצא במערכת");
                return(View(vm));
            }
            else
            {
                vm.Password = Protector.Decrypt(usr.Password);
            }
            return(View(vm));
        }
コード例 #15
0
        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();
        }
コード例 #16
0
ファイル: JobsController.cs プロジェクト: md-prog/LL
        // CRUD Worker
        public ActionResult EditWorker(int id, int relevantEntityId, LogicaName logicalName, int seasonId, int?leagueId)
        {
            var frm = new CreateWorkerForm
            {
                RelevantEntityId          = relevantEntityId,
                RelevantEntityLogicalName = logicalName,
            };

            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;
            }

            UsersJob userJob = jobsRepo.GetUsersJobById(id);

            frm.InjectFrom(userJob.User);
            frm.JobId     = userJob.JobId;
            frm.UserJobId = userJob.Id;
            frm.SeasonId  = seasonId;
            if (!string.IsNullOrEmpty(userJob.User.Password))
            {
                frm.Password = Protector.Decrypt(userJob.User.Password);
            }
            return(PartialView("_EditWorker", frm));
        }
コード例 #17
0
        public ActionResult Edit(int id = 0)
        {
            var vm = new UserForm();

            vm.RolesList = new SelectList(uRepo.GetTypes(), "TypeId", "TypeName");

            if (id != 0)
            {
                var user = uRepo.GetById(id);
                if (!string.IsNullOrEmpty(user.Password))
                {
                    user.Password = Protector.Decrypt(user.Password);
                }

                vm.InjectFrom(user);
            }

            return(PartialView("_Edit", vm));
        }
コード例 #18
0
        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);
        }
コード例 #19
0
ファイル: AccountController.cs プロジェクト: md-prog/LL
        public IHttpActionResult GetForgotPassword(UserMail userMail)
        {
            if (userMail == null || string.IsNullOrEmpty(userMail.Mail) || string.IsNullOrWhiteSpace(userMail.Mail))
            {
                return(NotFound());
            }

            var user = db.Users.FirstOrDefault(u => u.Email.Trim().ToLower() == userMail.Mail.Trim().ToLower());

            if (user == null)
            {
                return(NotFound());
            }
            EmailService             emailService = new EmailService();
            ForgotPasswordEmailModel model        = new ForgotPasswordEmailModel
            {
                Name     = user.UserName,
                Password = Protector.Decrypt(user.Password)
            };

            var templateService  = new RazorEngine.Templating.TemplateService();
            var templateFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Services", "Email", "ForgotPasswordEmailTemplate.cshtml");
            var emailHtmlBody    = templateService.Parse(File.ReadAllText(templateFilePath), model, null, null);

            try
            {
                IdentityMessage msg = new IdentityMessage();
                msg.Subject     = "Loglig";
                msg.Body        = emailHtmlBody;
                msg.Destination = user.Email;
                emailService.SendAsync(msg);
            }
            catch (Exception ex)
            {
                return(InternalServerError());
            }
            return(Ok());
        }
コード例 #20
0
        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}");
            }
        }
コード例 #21
0
ファイル: Program.cs プロジェクト: AngelBrambila91/Csharp7C
        static void Main(string[] args)
        {
            Write("Enter a message to encrypt : ");
            string message = ReadLine();

            Write("Enter a password : "******"Encrypted text : {cryptoText}");
            Write("Enter a password : "******"Decrypted text {clearText}");
            }
            catch (Exception ex)
            {
                WriteLine("Something went wrong");
            }
        }
コード例 #22
0
        public ActionResult Edit(int id = 0, int seasonId = 0, int leagueId = 0, int clubId = 0, int teamId = 0)
        {
            //
            Thread.CurrentThread.CurrentCulture = new CultureInfo("he-IL");
            var vm = new PlayerFormView
            {
                LeagueId = leagueId,
                Genders  = new SelectList(usersRepo.GetGenders(), "GenderId", "Title")
            };

            if (id != 0)
            {
                vm.ClubId        = clubId;
                vm.CurrentTeamId = teamId;
                vm.SeasonId      = seasonId;

                if (leagueId > 0)
                {
                    League league = leagueRepo.GetById(leagueId);
                    if (league != null)
                    {
                        vm.IsHadicapEnabled = league.Union.IsHadicapEnabled;
                        vm.SeasonId         = league.SeasonId ?? vm.SeasonId;
                    }
                }

                User pl = usersRepo.GetById(id);
                if (pl == null && pl.IsArchive)
                {
                    return(RedirectToAction("NotFound", "Error"));
                }


                if (teamId > 0)
                {
                    TeamsPlayer teamsPlayer = pl.TeamsPlayers
                                              .FirstOrDefault(x => x.UserId == pl.UserId &&
                                                              x.SeasonId == vm.SeasonId &&
                                                              x.TeamId == teamId);
                    if (teamsPlayer == null)
                    {
                        return(RedirectToAction("NotFound", "Error"));
                    }

                    vm.HandicapLevel = teamsPlayer.HandicapLevel;
                    vm.IsPlayereInTeamLessThan3year = teamsPlayer.IsPlayereInTeamLessThan3year;
                    vm.NumberOfTeamsUserPlays       = pl.TeamsPlayers.Count;
                }

                vm.InjectFrom <IgnoreNulls>(pl);

                if (!string.IsNullOrEmpty(pl.Password))
                {
                    vm.Password = Protector.Decrypt(pl.Password);
                }
                vm.IsValidUser     = User.IsInAnyRole(AppRole.Admins, AppRole.Editors);
                vm.ManagerTeams    = new List <TeamDto>();
                vm.PlayerTeams     = new List <TeamDto>();
                vm.PlayerHistories = new List <PlayerHistoryFormView>();

                var currDate = DateTime.Now;
                if (pl.UsersType.TypeRole == AppRole.Players)
                {
                    List <TeamDto> teams = pl.TeamsPlayers.Where(t => !t.Team.IsArchive &&
                                                                 seasonsRepository.GetAllCurrent().Select(s => s.Id).Contains(t.SeasonId ?? 0))
                                           .Select(t => new TeamDto
                    {
                        TeamId   = t.TeamId,
                        Title    = t.Team.Title,
                        SeasonId = t.SeasonId,
                        ClubId   = t.Team.ClubTeams.Where(ct => ct.SeasonId == t.SeasonId).FirstOrDefault()?.ClubId ?? 0,
                        LeagueId = t.Team.LeagueTeams.Where(lt => lt.SeasonId == t.SeasonId).FirstOrDefault()?.LeagueId ?? 0
                    })
                                           .ToList();
                    vm.PlayerTeams = teams;
                    if (!vm.IsValidUser)
                    {
                        var managerTeams = AuthSvc.FindTeamsByManagerId(base.AdminId)
                                           .Select(t => new {
                            TeamId = t.TeamId,
                            Title  = t.Title,
                            Club   = teamRepo.GetClubByTeamId(t.TeamId, currDate),
                            League = teamRepo.GetLeagueByTeamId(t.TeamId, currDate)
                        })
                                           .Select(t => new TeamDto
                        {
                            TeamId   = t.TeamId,
                            Title    = t.Title,
                            SeasonId = t.League.SeasonId ?? t.Club?.SeasonId,
                            ClubId   = t.Club?.ClubId ?? 0,
                            LeagueId = t.League?.LeagueId ?? 0
                        });
                        vm.ManagerTeams = managerTeams;
                    }
                }

                vm.PlayerHistories = usersRepo.GetPlayerHistory(id, vm.SeasonId).ToViewModel();
            }

            if (TempData["ViewData"] != null)
            {
                ViewData = (ViewDataDictionary)TempData["ViewData"];
            }

            return(View(vm));
        }
コード例 #23
0
ファイル: LoginController.cs プロジェクト: md-prog/LL
        public ActionResult Index(LoginForm frm, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("LgnErr", "נא מלא את פרטי ההתחברות");
                return(View(frm));
            }

            bool isCaptcha = IsCaptchaCookie();

            if (isCaptcha && !IsValidCaptcha(frm.Captcha))
            {
                ModelState.AddModelError("LgnErr", "קוד אבטחה שגוי");
                ModelState.AddModelError("Captcha", "Err");
                frm.IsSecure = true;

                return(View(frm));
            }

            int tries = AnonymousTries();

            if (tries == 1)
            {
                SetCaptchaCookie(true);
            }

            var uRep = new UsersRepo();
            var usr  = uRep.GetByUsername(frm.UserName.Trim());

            if (usr == null)
            {
                usr = uRep.GetByIdentityNumber(frm.UserName.Trim());
            }

            if (usr == null)
            {
                AnonymousTriesAdd();

                ModelState.AddModelError("LgnErr", "שם משתמש או סיסמה שגויים");
                ModelState.AddModelError("Password", "Err");
                return(View(frm));
            }

            if (usr.IsBlocked)
            {
                ModelState.AddModelError("LgnErr", "משתמש זה נחסם, יש לפנות להנהלת האתר");
                return(View(frm));
            }

            string usrPass = Protector.Decrypt(usr.Password);

            if (frm.Password != usrPass)
            {
                ModelState.AddModelError("LgnErr", "שם משתמש או סיסמה שגויים");
                usr.TriesNum += 1;

                if (usr.TriesNum > 2)
                {
                    frm.IsSecure = true;
                    SetCaptchaCookie(true);
                }

                if (usr.TriesNum >= 10)
                {
                    usr.TriesNum  = 0;
                    usr.IsBlocked = true;
                }

                uRep.Save();
                return(View(frm));
            }

            SetCaptchaCookie(false);

            string currSession = usr.SessionId;

            usr.TriesNum  = 0;
            usr.SessionId = Session.SessionID;
            uRep.Save();

            string userData = usr.UsersType.TypeRole + "^" + usr.SessionId;
            string userId   = usr.UserId.ToString();

            LoginService.UpdateSessions(usr.SessionId, currSession);

            var ticket = new FormsAuthenticationTicket(1, userId,
                                                       DateTime.Now,
                                                       DateTime.Now.AddHours(3),
                                                       frm.IsRemember,
                                                       userData,
                                                       FormsAuthentication.FormsCookiePath);

            string encTicket = FormsAuthentication.Encrypt(ticket);
            var    cookie    = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);

            cookie.Expires = ticket.Expiration;
            Response.Cookies.Add(cookie);

            SetAdminCookie(usr.FullName, usr.UsersType.TypeRole);

            if (!string.IsNullOrEmpty(returnUrl))
            {
                Redirect(returnUrl);
            }

            //For Testing
            //var test = uRep.GetById(54);
            //System.Diagnostics.Debug.WriteLine("*" + test.UserName + "*");
            //System.Diagnostics.Debug.WriteLine("*" + Protector.Decrypt(test.Password) + "*");

            //test = uRep.GetById(13);
            //System.Diagnostics.Debug.WriteLine("*" + test.UserName + "*");
            //System.Diagnostics.Debug.WriteLine("*" + Protector.Decrypt(test.Password) + "*");

            return(Redirect(FormsAuthentication.DefaultUrl));
        }
コード例 #24
0
        static void Main(string[] args)
        {
            WriteLine("You must enter the correct password to decrypt the document.");
            Write("Password: "******"..", "protected-customers.xml");

            if (!File.Exists(xmlFile))
            {
                WriteLine($"{xmlFile} does not exist!");
                return;
            }

            var xmlReader = XmlReader.Create(xmlFile,
                                             new XmlReaderSettings {
                IgnoreWhitespace = true
            });

            while (xmlReader.Read())
            {
                if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == "customer")
                {
                    xmlReader.Read(); // move to <name>
                    string name = xmlReader.ReadElementContentAsString();
                    string creditcardEncrypted = xmlReader.ReadElementContentAsString();
                    string creditcard          = null;
                    string errorMessage        = null;
                    try
                    {
                        creditcard = Protector.Decrypt(creditcardEncrypted, password);
                    }
                    catch (CryptographicException)
                    {
                        errorMessage = $"Failed to decrypt {name}'s credit card.";
                    }
                    string passwordHashed = xmlReader.ReadElementContentAsString();
                    string salt           = xmlReader.ReadElementContentAsString();

                    customers.Add(new Customer
                    {
                        Name       = name,
                        CreditCard = creditcard ?? errorMessage,
                        Password   = passwordHashed,
                        Salt       = salt
                    });
                }
            }

            xmlReader.Close();

            WriteLine();
            int number = 0;

            WriteLine("    {0,-20} {1,-20}",
                      arg0: "Name",
                      arg1: "Credit Card");

            foreach (var customer in customers)
            {
                WriteLine("[{0}] {1,-20} {2,-20}",
                          arg0: number,
                          arg1: customer.Name,
                          arg2: customer.CreditCard);

                number++;
            }
            WriteLine();

            Write("Press the number of a customer to log in as: ");

            string customerName = null;

            try
            {
                number       = int.Parse(ReadKey().KeyChar.ToString());
                customerName = customers[number].Name;
            }
            catch
            {
                WriteLine();
                WriteLine("Not a valid customer selection.");
                return;
            }

            WriteLine();
            Write($"Enter {customerName}'s password: "******"Correct!");
            }
            else
            {
                WriteLine("Wrong!");
            }
        }
コード例 #25
0
        public void Index(string message, string password)
        {
            var cryptoText = Protector.Encrypt(message, password);

            var clearText = Protector.Decrypt(cryptoText, password);
        }