コード例 #1
0
        public async Task <AccountDto> CreateAccountAsync(AccountDto acct)
        {
            var salt         = PasswordProtector.GenerateSalt();
            var randPassword = PasswordProtector.GenerateSalt(10);

            var newAcct = _mapper.Map <Account>(acct);

            newAcct.PasswordSalt = salt;
            newAcct.PasswordHash = PasswordProtector.SaltString(salt, randPassword);
            newAcct.CreatedAt    = DateTime.Now;
            newAcct.UpdatedAt    = DateTime.Now;

            _accountUnitOfWork.Repository.Add(newAcct);

            await _accountUnitOfWork.SaveChangesAsync().ConfigureAwait(false);

            Task.Run(async() =>
            {
                try
                {
                    await _emailSender
                    .SendEmailAsync(acct.Email, "GradeBook account created", $"Account password: {randPassword}")
                    .ConfigureAwait(false);
                }
                catch (Exception)
                {
                    _logger.LogError($"Failed to send email with password to user {acct.Email}");
                }
            });

            return(await GetAccountAsync(newAcct.Login).ConfigureAwait(false));
        }
コード例 #2
0
        public async Task ResetPasswordAsync(string login)
        {
            var acctToUpdate = await _accountUnitOfWork.Repository.GetByLoginAsync(login).ConfigureAwait(false);

            if (acctToUpdate == null)
            {
                throw new ResourceNotFoundException($"Аккаунт {login} не знайдено");
            }

            var salt        = PasswordProtector.GenerateSalt();
            var newPassword = PasswordProtector.GenerateSalt(10);

            acctToUpdate.PasswordSalt = salt;
            acctToUpdate.PasswordHash = PasswordProtector.SaltString(salt, newPassword);
            acctToUpdate.UpdatedAt    = DateTime.Now;

            await _accountUnitOfWork.SaveChangesAsync().ConfigureAwait(false);

            Task.Run(async() =>
            {
                try
                {
                    await _emailSender
                    .SendEmailAsync(acctToUpdate.Login, "GradeBook password reset", $"New password: {newPassword}")
                    .ConfigureAwait(false);
                }
                catch (Exception)
                {
                    _logger.LogError($"Failed to send email with password to user {login}");
                }
            });
        }
コード例 #3
0
        public async Task <IActionResult> Register(UserAccount userAccount)
        {
            if (userAccount != null && !string.IsNullOrEmpty(userAccount.Email) &&
                !string.IsNullOrEmpty(userAccount.Password))
            {
                var passwordDetails = PasswordProtector.GetHashAndSalt(userAccount.Password);
                userAccount.Password      = passwordDetails.HashText;
                userAccount.PasswordSalt  = passwordDetails.SaltText;
                userAccount.HashIteration = passwordDetails.HashIteration;
                userAccount.HashLength    = passwordDetails.HashLength;
                userAccount.CreatedDate   = DateTime.Now;
                userAccount.UpdateDate    = DateTime.Now;
                userAccount.Version       = 1;
                userAccount.UserName      = userAccount.Email;

                this.inventoryDbContext.UserAccounts.Add(userAccount);
                await inventoryDbContext.SaveChangesAsync();
            }
            else
            {
                return(BadRequest("Required data for user registeration not found"));
            }

            return(Ok());
        }
コード例 #4
0
 private bool Encrypt()
 {
     if (IsAutoMode)
     {
         if (ComputerName.IsNullOrEmpty())
         {
             var protector = new PasswordProtector();
             EncryptedValue = protector.Protect(OriginalValue, PasswordProtectionScope.LocalMachine);
             return(true);
         }
         else
         {
             //var factory = new ImpersonatorFactory()
             //{
             //    IsEnabled = true,
             //    Username = "******",
             //    Password = "******",
             //    Domain = "LILI"
             //};
             //using (factory.Create())
             {
                 var powershell = new PowerShellExecutor(ComputerName);
                 if (powershell.Execute())
                 {
                     EncryptedValue = powershell.Result;
                     return(true);
                 }
             }
         }
         return(false);
     }
     return(true);
 }
コード例 #5
0
 public void TestUnProtect()
 {
     var password = "******";
     var protector = new PasswordProtector();
     var protectedPassword = protector.Protect(password, PasswordProtectionScope.LocalMachine);
     var finalPass = protector.UnProtect(protectedPassword);
     Assert.IsTrue(password == finalPass);
 }
コード例 #6
0
        public void EncryptThenDecryptStringTest()
        {
            // Act
            string encrypted = PasswordProtector.GetEncryptedString(secureSample);
            var    decrypted = PasswordProtector.DecryptString(encrypted);

            Debug.WriteLine(encrypted);

            // Assert
            Assert.AreEqual(secureSample.Length, decrypted.Length);
            Assert.AreEqual(secureSample.ToInsecureString(), decrypted.ToInsecureString());
        }
コード例 #7
0
        /// <summary>
        /// Default constructor of the DI connection mockup.
        /// </summary>
        public DiConnectionMockup(DiConnectionModel connection, string passwordPath)
        {
            if (!File.Exists(passwordPath))
            {
                throw new ArgumentException("The password file does not exist.");
            }

            // Unprotect the SAP DI user password given its encrypted binary file path.
            var passProtector = new PasswordProtector();
            var password      = passProtector.Unprotect(passwordPath);

            MessageBox.Show($"Server: {connection.Server}, Company: {connection.Company}, User: {connection.Username}, Password: {password}");
        }
コード例 #8
0
        public async Task <bool> VerifyPasswordAsync(string login, string password)
        {
            var account = await _accountUnitOfWork.Repository.GetByLoginAsync(login);

            if (account == null)
            {
                return(false);
            }

            var saltedPassword = PasswordProtector.SaltString(account.PasswordSalt, password);

            return(saltedPassword.Equals(account.PasswordHash));
        }
コード例 #9
0
        public static ISimpleEncryption Create(EncryptionAlgorithm algorithm)
        {
            SecureString key = PasswordProtector.DecryptString(Properties.Settings.Default.Key);
            var          tripleDesKeySize = (TripleDesKeySize)Properties.Settings.Default.TripleDesKeySize;

            return(algorithm switch
            {
                EncryptionAlgorithm.None => throw new NotImplementedException(),
                EncryptionAlgorithm.AES => new SimpleAes(key),
                EncryptionAlgorithm.DES => new SimpleDes(key),
                EncryptionAlgorithm.TripleDES => new SimpleTripleDes(key, tripleDesKeySize),
                _ => throw new InvalidOperationException($"{algorithm} is not a valid algorithm"),
            });
コード例 #10
0
        /// <summary>
        /// Main function of a simple application developed to protect/unprotect
        /// Alala passwords used for SAP DI connection.
        /// </summary>
        /// <param name="args">An array of arguments including application options and
        /// the input data depending on the specific option.</param>
        static void Main(string[] args)
        {
            // Check whether there is 2 arguments...
            if (args.Length != 2)
            {
                // If not, print error/help messages to the console and return.
                Console.WriteLine("Wrong syntax... Please use one of the following calls:");
                Console.WriteLine("SecureDiogenesPasswords.exe -p <original password>");
                Console.WriteLine("SecureDiogenesPasswords.exe -u <encrypted password>");
                return;
            }

            var option = args[0];
            var input  = args[1];

            switch (option)
            {
            case "-p":
            {
                // Protect an input (plaintext) password.
                var protector = new PasswordProtector();
                protector.Protect(input);
                break;
            }

            case "-u":
            {
                // Unprotect a password stored in an encrypted binary file.
                // The input of "unprotect" is the path of the binary file.
                var protector        = new PasswordProtector();
                var originalPassword = protector.Unprotect(input);

                // Print to the console the original password value.
                Console.WriteLine($"The original password is: {originalPassword}");
                break;
            }

            default:
            {
                // In case of wrong option, print error/help messages to the console and return.
                Console.WriteLine("Wrong option... Please use one of the following calls:");
                Console.WriteLine("SecureDiogenesPasswords.exe -p <original password>");
                Console.WriteLine("SecureDiogenesPasswords.exe -u <encrypted password>");
                break;
            }
            }
        }
コード例 #11
0
        public async Task ChangePasswordAsync(int accountId, string newPassword)
        {
            var acctToUpdate = await _accountUnitOfWork.Repository.GetByIdAsync(accountId).ConfigureAwait(false);

            if (acctToUpdate == null)
            {
                throw new ResourceNotFoundException($"Аккаунт {accountId} не знайдено");
            }

            var salt = PasswordProtector.GenerateSalt();

            acctToUpdate.PasswordSalt = salt;
            acctToUpdate.PasswordHash = PasswordProtector.SaltString(salt, newPassword);
            acctToUpdate.UpdatedAt    = DateTime.Now;

            await _accountUnitOfWork.SaveChangesAsync().ConfigureAwait(false);
        }
コード例 #12
0
        public void RandomProtectAndCompareTest()
        {
            const string passwordToProtect = "MyC0013ncrypti0nP@$$w0rd!";

            using (var protector = new PasswordProtector()) {
                ProtectedPassword protectedPassword = protector.Protect(passwordToProtect);
                Assert.NotNull(protectedPassword);

                Assert.NotNull(protectedPassword.Password);

                Assert.True(protectedPassword.Password.Length <= 64); // The Size of SHA-256
                Assert.True(protectedPassword.Password.Length >= 32); // The Size of MD5

                Assert.NotNull(protectedPassword.Salt);
                Assert.True(protectedPassword.IterationCount > 0);

                Assert.True(protector.CompareProtectedPassword(passwordToProtect, protectedPassword));
            }
        }
コード例 #13
0
        /// <summary>
        /// Constructor of the DI connection controller;
        /// initializes the company object based on a given
        /// DI connection model.
        /// </summary>
        /// <param name="connection">The given model represents the DI connection details.</param>
        public DiConnectionController(DiConnectionModel connection, string passwordPath)
        {
            if (!File.Exists(passwordPath))
            {
                throw new ArgumentException("The password file does not exist.");
            }

            // Unprotect the SAP DI user password given its encrypted binary file path.
            var passProtector = new PasswordProtector();
            var password      = passProtector.Unprotect(passwordPath);

            Company = new Company
            {
                Server       = connection.Server,
                DbServerType = BoDataServerTypes.dst_MSSQL2014,
                CompanyDB    = connection.Company,
                UserName     = connection.Username,
                Password     = password,
                language     = BoSuppLangs.ln_English
            };
        }
コード例 #14
0
        public async Task <IActionResult> Login(SignInModel signInModel)
        {
            if (signInModel != null && !string.IsNullOrEmpty(signInModel.UserName) && !string.IsNullOrEmpty(signInModel.Password))
            {
                var user = await inventoryDbContext.UserAccounts.FirstOrDefaultAsync(x => x.Email.Equals(signInModel.UserName));

                if (user != null && !string.IsNullOrEmpty(user.Password) && !string.IsNullOrEmpty(user.PasswordSalt))
                {
                    bool passwordVerification = PasswordProtector.VerifyPassword
                                                    (signInModel.Password,
                                                    user.Password,
                                                    user.PasswordSalt,
                                                    user.HashLength
                                                    , user.HashIteration);

                    if (passwordVerification)
                    {
                        string jwtToken = JwtTokenGenerator.GetJwtToken(user, this.configuration);

                        return(Ok(jwtToken));
                    }
                    else
                    {
                        return(Unauthorized("User authentication failed. Please enter valid user account details for sign in."));
                    }
                }
                else
                {
                    return(NotFound("User not found. Please enter valid user name"));
                }
            }
            else
            {
                return(BadRequest("Required data for user sign in not found"));
            }
        }
コード例 #15
0
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.InsertData("AssestmentTypes", "Description", "Екзамен");
            migrationBuilder.InsertData("AssestmentTypes", "Description", "Залік");
            migrationBuilder.InsertData("AssestmentTypes", "Description", "Диференційний залік");

            var adminTmpPassword = "******";
            var salt             = PasswordProtector.GenerateSalt();
            var saltedPassword   = PasswordProtector.SaltString(salt, adminTmpPassword);

            migrationBuilder.InsertData("Accounts", new []
            {
                "FirstName",
                "LastName",
                "MiddleName",
                "CreatedAt",
                "UpdatedAt",
                "Role",
                "PasswordHash",
                "PasswordSalt",
                "IsActive",
                "Login"
            }, new object[]
            {
                "Admin",
                "Gradebook",
                "Api",
                DateTime.Now,
                DateTime.Now,
                Roles.Admin,
                saltedPassword,
                salt,
                true,
                "*****@*****.**"
            });
        }
コード例 #16
0
 public void TestUnProtectInvalidFormat()
 {
     var protector = new PasswordProtector();
     protector.UnProtect(Convert.ToBase64String(Encoding.UTF8.GetBytes(new String('a', 1000))));
 }
コード例 #17
0
 public void TestUnProtectInvalidBase64()
 {
     var protector = new PasswordProtector();
     protector.UnProtect(new String('a', 1000));
 }
コード例 #18
0
 public void TestProtect()
 {
     var password = "******";
     var protector = new PasswordProtector();
     protector.Protect(password, PasswordProtectionScope.LocalMachine);
 }