コード例 #1
0
        public Task <byte[]> HashAsync(byte[] password, byte[] salt)
        {
            var config = GenerateConfig(password, salt);
            var hasher = new Argon2(config);

            return(Task.FromResult(hasher.Hash().Buffer.ToArray()));
        }
コード例 #2
0
        public void TestArgon2RoundTrip()
        {
            var password = "******";

            byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
            byte[] salt          = new byte[16];
            Rng.GetBytes(salt);
            var config = new Argon2Config
            {
                Type       = Argon2Type.DataIndependentAddressing,
                Version    = Argon2Version.Nineteen,
                Password   = passwordBytes,
                Salt       = salt,
                TimeCost   = 3,
                MemoryCost = 65536,
                Lanes      = 4,
                Threads    = 2,
            };
            var argon2 = new Argon2(config);
            SecureArray <byte> hash = argon2.Hash();
            var passwordHash        = config.EncodeString(hash.Buffer);

            this.output.WriteLine($"Argon2 of {password} --> {passwordHash}");
            Assert.True(
                Argon2.Verify(passwordHash, passwordBytes, SecureArray.DefaultCall),
                $"expected verify to work for {passwordHash} (Argon2 hash of {password}");
        }
コード例 #3
0
        internal static void AddUser(string username, string password)
        {
            Argon2Config config = new Argon2Config
            {
                Type       = Argon2Type.DataIndependentAddressing,
                Version    = Argon2Version.Nineteen,
                TimeCost   = 3,
                MemoryCost = 32768,
                Lanes      = 4,
                Threads    = Environment.ProcessorCount,
                Password   = Encoding.ASCII.GetBytes(password),
                Salt       = Convert.FromBase64String(Properties.Settings.Default.Salt), // >= 8 bytes if not null
                HashLength = 20                                                          // >= 4
            };
            Argon2 argon2 = new Argon2(config);
            string passwordHash;

            using (SecureArray <byte> hashA = argon2.Hash())
            {
                passwordHash = config.EncodeString(hashA.Buffer);
            }
            var userCreated = new user()
            {
                username     = username,
                passwordHash = passwordHash,
                isAdmin      = false,
                isEnabled    = false
            };

            context.users.Add(userCreated);
            context.SaveChanges();
        }
コード例 #4
0
        /// <summary>
        /// Test <see cref="Argon2"/>.
        /// </summary>
        /// <returns>
        /// Result text.
        /// </returns>
        public static string TestArgon2RoundTrip2()
        {
            var password      = "******";
            var secret        = "secret1";
            var passedResults = new List <string>();
            var failedResults = new List <string>();

            foreach (var argon2Type in new[]
                     { Argon2Type.DataIndependentAddressing, Argon2Type.DataDependentAddressing, Argon2Type.HybridAddressing })
            {
                var argon2Name = argon2Type == Argon2Type.DataIndependentAddressing ? "Argon2i" :
                                 argon2Type == Argon2Type.DataDependentAddressing ? "Argon2d" : "Argon2id";

                var passwordHash = Argon2.Hash(password, secret, type: argon2Type);
                Console.WriteLine($"{argon2Name} of {password} --> {passwordHash}");

                if (Argon2.Verify(passwordHash, password, secret))
                {
                    passedResults.Add(argon2Name);
                    Console.WriteLine($"RoundTrip2 {argon2Name} Passed");
                }
                else
                {
                    failedResults.Add(argon2Name);
                    Console.WriteLine($"RoundTrip2 {argon2Name} FAILED");
                    Console.WriteLine($"    expected verify to work for {passwordHash} ({argon2Name} hash of {password})");
                }
            }

            return(failedResults.Any() ? $"RoundTrip2 FAILED: [{string.Join(", ", failedResults)}] (passed: [{string.Join(", ", passedResults)}])"
                : "RoundTrip2 Passed");
        }
コード例 #5
0
 public string Generate(string password)
 {
     return(Argon2.Hash(password,
                        settings.TimeCost ?? 3,
                        settings.MemoryCost ?? 65536,
                        settings.Parallelism ?? 1));
 }
コード例 #6
0
        public async Task <AccountMessage> Register(RegisterAccount _account)
        {
            Common.Models.Account accountUsername = _unitOfWorkAccountSearch.Account.GetByUsername(_account.Username);
            //Common.Models.Account accountEmail = await _dbContext.Account.FirstOrDefaultAsync(a => a.Username == _account.Username);

            if (accountUsername != null)
            {
                return(new AccountMessage()
                {
                    Success = false,
                    Message = "Username is already in use"
                });
            }

            Common.Models.Account acc = new Common.Models.Account()
            {
                Username = _account.Username,
                Password = Argon2.Hash(_account.Password)
            };

            _unitOfWorkAccount.Account.Add(acc);

            _unitOfWorkAccount.Save();

            return(new AccountMessage()
            {
                Success = true,
                Message = acc.GenerateJwt()
            });
        }
コード例 #7
0
        public async Task Post([FromBody] User user)
        {
            try
            {
                new MailAddress(user.Email);
                User users = await context.Users.Find(filter : new BsonDocument(Models.User.EMAILFIELD, user.Email)).FirstOrDefaultAsync();

                if (users != null)
                {
                    throw new Exception("User with such email exist.");
                }
                else
                {
                    Argon2Config config = new Argon2Config
                    {
                        Type     = Argon2Type.DataIndependentAddressing,
                        Version  = Argon2Version.Nineteen,
                        Salt     = Encoding.Default.GetBytes(Resources.LocalSalt),
                        Password = Encoding.Default.GetBytes(user.Password)
                    };
                    user.HPass = Argon2.Hash(config);
                    await context.Users.InsertOneAsync(user);

                    new StatusCodeResult(StatusCodes.Status200OK);
                }
            }
            catch (Exception exception)
            {
                Response.StatusCode = StatusCodes.Status500InternalServerError;
                await HttpContext.Response.WriteAsync(exception.Message.ToString());
            }
        }
コード例 #8
0
        public ActionResult Create([Bind(Include = "AccountId,Name,Password,PhoneNumber,ContactListId")] Account account)
        {
            if (ModelState.IsValid)
            {
                if (account.PhoneNumber.All(char.IsDigit))
                {
                    if (!accRep.AccountExists(account))
                    {
                        account.Password = Argon2.Hash(account.Password);
                        accRep.CreateAcccount(account);
                        return(RedirectToAction("LogIn", "Accounts"));
                    }
                    else
                    {
                        ModelState.AddModelError("reg-error", "Account already exists");
                        return(RedirectToAction("Create"));
                    }
                }
                else
                {
                    ModelState.AddModelError("phone-error", "PhoneNumber must only contain digits.");
                    return(RedirectToAction("Create"));
                }
            }

            return(View(account));
        }
コード例 #9
0
ファイル: AuthController.cs プロジェクト: deamonicnet/Pamaxie
        public async Task <ActionResult <string> > CreateUserTask()
        {
            using var reader = new StreamReader(HttpContext.Request.Body);
            var body = await reader.ReadToEndAsync();

            if (string.IsNullOrWhiteSpace(body))
            {
                return(BadRequest("Please specify a user to create"));
            }

            JObject googleSearch = JObject.Parse(body);
            var     user         = googleSearch["userData"].ToObject <PamaxieUser>();

            user.UniqueKey     = PamaxieCryptoHelpers.GetUserId(new System.Net.NetworkCredential(user.UserName, user.Password));
            user.Password      = Argon2.Hash(user.Password);
            user.EmailVerified = false;
            user.Disabled      = false;
            user.TTL           = DateTime.MaxValue;

            if (_dbDriver.Service.PamaxieUserData.Exists(user.UniqueKey))
            {
                return(BadRequest("The specified user already exists in the database"));
            }

            _dbDriver.Service.PamaxieUserData.Create(user);
            return(Created(String.Empty, null));
        }
コード例 #10
0
        private async Task <bool> RegisterUser(string username, string password, UserRole role, IFormFile file)
        {
            if (context.People.Any(p => p.Login == username))
            {
                return(false);
            }
            string randomFile = null;

            if (file != null)
            {
                randomFile = $"{Path.GetRandomFileName()}.{Path.GetExtension(file.FileName)}";
            }
            Person person = new Person()
            {
                Login        = username,
                PasswordHash = Argon2.Hash(password),
                Role         = role,
                Avatar       = randomFile
            };
            await context.People.AddAsync(person);

            await context.SaveChangesAsync();

            if (file != null)
            {
                person = context.Entry(person).Entity;
                string userPath = Path.Combine(ImageFolder, person.Id.ToString());
                if (!Directory.Exists(userPath))
                {
                    Directory.CreateDirectory(userPath);
                }
                await file.WriteToFile(Path.Combine(userPath, randomFile));
            }
            return(true);
        }
コード例 #11
0
ファイル: JwtContext.cs プロジェクト: aHDPik/TestTemplate
 protected override void OnModelCreating(ModelBuilder modelBuilder)
 {
     base.OnModelCreating(modelBuilder);
     modelBuilder.Entity <Person>().HasData(new Person()
     {
         Id = 1, Login = "******", PasswordHash = Argon2.Hash("admin"), Role = UserRole.Admin
     });
 }
コード例 #12
0
        /// <summary>
        /// Compares a hash, salt and plain password and sets IsValid
        /// </summary>
        public SecuredPassword(string plainPassword, byte[] hash, byte[] salt, HashStrategyKind hashStrategy)
        {
            _hash = hash;
            _salt = salt;
            SetHashStrategy(hashStrategy);
            byte[] newKey;
            switch (hashStrategy)
            {
            case HashStrategyKind.Pbkdf210001Iterations:
                var numberOfIterations = (int)_hashingParameter;
                if (numberOfIterations <= 10000)
                {
                    throw new ArgumentException("Iterations must be greater than 10000");
                }
                using (var deriveBytes = new Rfc2898DeriveBytes(plainPassword, salt, numberOfIterations, HashAlgorithmName.SHA256))
                {
                    newKey  = deriveBytes.GetBytes(_saltSize);
                    IsValid = newKey.SequenceEqual(hash);
                }
                break;

            case HashStrategyKind.Argon2WorkCost:
                SecureArray <byte> hashB = null;
                try
                {
                    var passwordBytes            = Encoding.ASCII.GetBytes(plainPassword);
                    var configOfPasswordToVerify = new Argon2Config
                    {
                        Type       = Argon2Type.DataIndependentAddressing,
                        Version    = Argon2Version.Nineteen,
                        TimeCost   = 10,
                        MemoryCost = (int)_hashingParameter,
                        Lanes      = 5,
                        Threads    = Environment.ProcessorCount,
                        Salt       = _salt,
                        Password   = passwordBytes,
                        HashLength = 20
                    };
                    var hashString = Encoding.ASCII.GetString(_hash);
                    if (configOfPasswordToVerify.DecodeString(hashString, out hashB) && hashB != null)
                    {
                        var argon2ToVerify = new Argon2(configOfPasswordToVerify);
                        using (var hashToVerify = argon2ToVerify.Hash())
                        {
                            if (!hashB.Buffer.Where((b, i) => b != hashToVerify[i]).Any())
                            {
                                IsValid = true;
                            }
                        }
                    }
                }
                finally
                {
                    hashB?.Dispose();
                }
                break;
            }
        }
コード例 #13
0
        public string Hash(string text)
        {
            Validator.ValidateStringIsNotNullOrEmpty(text);

            _argon2Config.Password = Encoding.UTF8.GetBytes(text);
            var argon2A = new Argon2(_argon2Config);

            return(_argon2Config.EncodeString(argon2A.Hash().Buffer));
        }
コード例 #14
0
 public static Person ToPerson(this UserModel model)
 {
     return(new Person()
     {
         Login = model.Username,
         PasswordHash = Argon2.Hash(model.Password),
         Role = model.Role,
         Id = model.Id.HasValue?model.Id.Value:0
     });
 }
コード例 #15
0
        public static Credentials CreateFromRegistration(RegistrationRequest request)
        {
            Credentials credentials = new Credentials
            {
                Login    = request.Login,
                Password = Argon2.Hash(request.Password)
            };

            return(credentials);
        }
コード例 #16
0
ファイル: LoginService.cs プロジェクト: ninjapretzel/ExServer
 /// <summary> Creates an Argon2 <see cref="HashFn"/> with the given parameters. </summary>
 /// <param name="iterations"> Iterations/'timeCost' to use </param>
 /// <param name="secret"> Optional secret to use </param>
 /// <param name="memoryCost"> Memory Cost to use </param>
 /// <param name="threads"> Threads to use </param>
 /// <param name="type"> Variant of Argon2 to use </param>
 /// <param name="size"> Hash length </param>
 /// <returns> <see cref="HashFn"/> that performs Argon2 with the given parameters </returns>
 public static HashFn Argon2Hash(int iterations = 3, int memoryCost = 1024 *32, int threads = 8, string secret = null, Argon2Type type = Argon2Type.HybridAddressing, int size = 32)
 {
     return((pass) => {
         DateTime start = DateTime.UtcNow;
         var result = Argon2.Hash(pass, secret, iterations, memoryCost, threads, type, size);
         DateTime end = DateTime.UtcNow;
         Log.Debug($"Argon2.Hash({iterations}, {memoryCost}, {threads}, {type}, {size}) completed in {(end - start).TotalMilliseconds}ms");
         return result;
     });
 }
コード例 #17
0
        public void TestArgon2RoundTrip2()
        {
            var password     = "******";
            var passwordHash = Argon2.Hash(password);

            this.output.WriteLine($"Argon2 of {password} --> {passwordHash}");
            Assert.True(
                Argon2.Verify(passwordHash, password, SecureArray.DefaultCall),
                $"expected verify to work for {passwordHash} (Argon2 hash of {password}");
        }
コード例 #18
0
        public static Credentials CreateFromCliModel(RegistrateAdministrator model)
        {
            Credentials credentials = new Credentials
            {
                Login    = model.Login,
                Password = Argon2.Hash(model.Password)
            };

            return(credentials);
        }
コード例 #19
0
        public async Task <APIResponse> PostRecordToCollection(string collectionName, string id, [FromBody] ExpandoObject payload)
        {
            _logger.LogInformation($"PostRecordToCollection request recieved");

            id = id.Replace("[NewGuid]", Guid.NewGuid().ToString());

            var payloadDictionary = (IDictionary <String, object>)payload;

            if (!payloadDictionary.ContainsKey("timestamp"))
            {
                payloadDictionary.Add("timestamp", DateTime.UtcNow);
            }

            if (payloadDictionary.ContainsKey("id"))
            {
                payloadDictionary["id"] = id;
            }
            else
            {
                payloadDictionary.Add("id", id);
            }

            if (payloadDictionary.ContainsKey("passwordToHash"))
            {
                var passwordToHash = payloadDictionary["passwordToHash"].ToString();
                var hashedPassword = Argon2.Hash(passwordToHash);
                payloadDictionary.Remove("passwordToHash");
                payloadDictionary.Add("hashedPassword", hashedPassword);
            }

            var collection = await GetCollection(collectionName).ConfigureAwait(false);

            if (collection == null)
            {
                return(APIResponse.NotOk(Request.ToRequestString(), $"Cant find collection with name {collectionName}", HttpStatusCode.BadRequest));
            }

            var response = await _elasticBand.Index <object>(collection.Index, payload, id).ConfigureAwait(false);

            if (response.Ok)
            {
                return new APIResponse
                       {
                           Request    = Request.ToRequestString(),
                           Ok         = true,
                           Result     = response.Result,
                           StatusCode = response.StatusCode,
                           Data       = $"{collection.Index}/_doc/{response.Id}"
                       }
            }
            ;

            return(APIResponse.NotOk(Request.ToRequestString(), "Failed to index data", HttpStatusCode.BadRequest));
        }
コード例 #20
0
        /* { "execFun": "registration",
         *      "data": {
         *          "login": "******",
         *          "password": "******",
         *          "nickName": "gosha",
         *          "transactionId": "80f7efc032dd4a7c97f69fca51ad3001"
         *      }
         *  }
         */

        public OutputSocketMessageWithUsers Execute(object val, string myLogin, Guid actId)
        {
            OutputSocketMessage          output = new OutputSocketMessage("registration", actId, true, "", new { });
            OutputSocketMessageWithUsers rez    = new OutputSocketMessageWithUsers();


            RegistrationInfo info = DeserializeObject.ParseJSON <RegistrationInfo>(val, output, out rez);

            if (info == null)
            {
                return(rez);
            }

            using (var db = new RaidaContext())
            {
                if (db.Members.Any(it => it.login.Equals(info.login.Trim(), StringComparison.CurrentCultureIgnoreCase)))
                {
                    output.success  = false;
                    output.msgError = "This login already exists";
                }
                else
                {
                    Guid privateId = Guid.NewGuid();
                    while (db.Members.Any(it => it.private_id == privateId))
                    {
                        privateId = Guid.NewGuid();
                    }

                    info.password = Argon2.Hash(info.password, 1, 512, 8); //Hashing password
                    Members member = new Members
                    {
                        private_id           = privateId,
                        login                = info.login.Trim().ToLower(),
                        pass                 = info.password,
                        nick_name            = info.nickName,
                        last_use             = SystemClock.GetInstance().CurrentTime,
                        description_fragment = "",
                        photo_fragment       = "",
                        kb_bandwidth_used    = 0,
                        online               = false,
                    };
                    db.Members.Add(member);
                    Transaction.saveTransaction(db, info.transactionId, Transaction.TABLE_NAME.MEMBERS, privateId.ToString(), member);

                    db.SaveChanges();
                }
            }

            rez.msgForOwner = output;
            return(rez);
        }
コード例 #21
0
ファイル: DataHasher.cs プロジェクト: joao-neves95/Amplifir
        public static string Argon2Hash(string data)
        {
            Argon2Config config = DataHasher.Argon2Config;

            config.Password = Encoding.UTF8.GetBytes(data);

            byte[] salt = new byte[18];
            RNG.GetBytes(salt);
            config.Salt = Encoding.UTF8.GetBytes(System.Convert.ToBase64String(salt));

            using Argon2 argon2 = new Argon2(DataHasher.Argon2Config);
            using SecureArray <byte> hash = argon2.Hash();
            return(DataHasher.Argon2Config.EncodeString(hash.Buffer));
        }
コード例 #22
0
        /// <summary>
        /// Test <see cref="Argon2"/>.
        /// </summary>
        /// <returns>
        /// The result text.
        /// </returns>
        public static string TestArgon2RoundTrip()
        {
            var password = "******";

            byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
            byte[] salt          = new byte[16];
            Rng.GetBytes(salt);
            var secret = "secret1";

            byte[] secretBytes   = Encoding.UTF8.GetBytes(secret);
            var    failedResults = new List <string>();
            var    passedResults = new List <string>();

            foreach (var argon2Type in new[] { Argon2Type.DataIndependentAddressing, Argon2Type.DataDependentAddressing, Argon2Type.HybridAddressing })
            {
                var argon2Name = argon2Type == Argon2Type.DataIndependentAddressing ? "Argon2i" :
                                 argon2Type == Argon2Type.DataDependentAddressing ? "Argon2d" : "Argon2id";
                var config = new Argon2Config
                {
                    Type       = argon2Type,
                    Version    = Argon2Version.Nineteen,
                    Password   = passwordBytes,
                    Salt       = salt,
                    Secret     = secretBytes,
                    TimeCost   = 3,
                    MemoryCost = 65536,
                    Lanes      = 4,
                    Threads    = 2,
                };
                var argon2 = new Argon2(config);
                SecureArray <byte> hash = argon2.Hash();
                var passwordHash        = config.EncodeString(hash.Buffer);
                Console.WriteLine($"{argon2Name} of {password} --> {passwordHash}");
                if (Argon2.Verify(passwordHash, passwordBytes, secretBytes, SecureArray.DefaultCall))
                {
                    passedResults.Add(argon2Name);
                    Console.WriteLine($"Round Trip {argon2Name} Passed");
                }
                else
                {
                    failedResults.Add(argon2Name);
                    Console.WriteLine($"Round Trip {argon2Name} FAILED");
                    Console.WriteLine($"    expected verify to work for {passwordHash} (Argon2 hash of {password})");
                }
            }

            return(failedResults.Any() ? $"RoundTrip FAILED: [{string.Join(", ", failedResults)}] (passed: [{string.Join(", ", passedResults)}])"
                : "RoundTrip Passed");
        }
コード例 #23
0

        
コード例 #24
0
        /// <summary>
        /// Given a plain password and a hash strategy, calculate the salt and hash
        /// </summary>
        public SecuredPassword(string plainPassword, HashStrategyKind hashStrategy)
        {
            if (string.IsNullOrWhiteSpace(plainPassword))
            {
                throw new ArgumentNullException(plainPassword);
            }
            SetHashStrategy(hashStrategy);

            switch (hashStrategy)
            {
            case HashStrategyKind.Pbkdf210001Iterations:
                var numberOfIterations = (int)_hashingParameter;
                if (numberOfIterations <= 10000)
                {
                    throw new ArgumentException("Iterations must be greater than 10000");
                }
                using (var deriveBytes = new Rfc2898DeriveBytes(plainPassword, _saltSize, numberOfIterations, HashAlgorithmName.SHA256))
                {
                    _salt = deriveBytes.Salt;
                    _hash = deriveBytes.GetBytes(_saltSize);
                }
                break;

            case HashStrategyKind.Argon2WorkCost:
                byte[] passwordBytes = Encoding.UTF8.GetBytes(plainPassword);
                _salt = new byte[_saltSize];
                RandomNumberGenerator.GetBytes(_salt);
                var config = new Argon2Config
                {
                    Type       = Argon2Type.DataIndependentAddressing,
                    Version    = Argon2Version.Nineteen,
                    TimeCost   = 10,
                    MemoryCost = (int)_hashingParameter,
                    Lanes      = 5,
                    Threads    = Environment.ProcessorCount,
                    Password   = passwordBytes,
                    Salt       = _salt,
                    HashLength = 20
                };
                var argon2A = new Argon2(config);
                using (SecureArray <byte> hashArgon = argon2A.Hash())
                {
                    _hash = Encoding.ASCII.GetBytes(config.EncodeString(hashArgon.Buffer));
                }
                break;
            }
            IsValid = true;
        }
コード例 #25
0
 public void InitializeTests()
 {
     _testAccount = new Account()
     {
         Password     = Argon2.Hash("P@ssw0rd"),
         Id           = Guid.Empty,
         Applications = new List <Application>()
         {
             new Application()
             {
                 Active       = true,
                 Address      = "http://example.com",
                 TrackingCode = "abcdefg",
                 Type         = "web",
                 Name         = "example.com",
                 Statistic    = new List <ApplicationStatistic>()
                 {
                     new ApplicationStatistic()
                     {
                         PageViews = 10,
                         Visits    = 10,
                         Timestamp = new DateTime(2000, 10, 1),
                     }
                 },
                 BrowserStatistic = new List <ApplicationStatisticBrowser>()
                 {
                     new ApplicationStatisticBrowser()
                     {
                         PageViews = 10,
                         Visits    = 10,
                         Timestamp = new DateTime(2000, 10, 1),
                         Browser   = "TestBrowser"
                     }
                 },
                 PathStatistic = new List <ApplicationStatisticPath>()
                 {
                     new ApplicationStatisticPath()
                     {
                         PageViews = 10,
                         Visits    = 10,
                         Timestamp = new DateTime(2000, 10, 1),
                         Path      = "/test/example"
                     }
                 }
             }
         }
     };
 }
 /// <auto-generated />
 protected override void Up(MigrationBuilder migrationBuilder)
 {
     migrationBuilder.InsertData("Users",
                                 new[]
     {
         "Id",
         "UserName",
         "PasswordHash"
     },
                                 new object[]
     {
         SecurityHelper.CreateCryptographicallySecureGuid(),
         "admin",
         Argon2.Hash("admin")
     });
 }
コード例 #27
0
        public async Task RegisterAsync(AuthData registerData)
        {
            var random  = new Random();
            var courier = new Courier()
            {
                Status    = CourierStatus.Sleep,
                Login     = registerData.Login,
                Password  = Argon2.Hash(registerData.Password),
                Longitude = random.Next(1000) + random.NextDouble(),
                Latitude  = random.Next(1000) + random.NextDouble()
            };

            await _context.CreateAndSaveAsync(courier);

            _logger.LogInformation("Courier registered");
        }
コード例 #28
0
 public void TestArgon2()
 {
     foreach (var testVector in Argon2TestVectors)
     {
         var  encoded   = new StringBuilder();
         uint tagLength = (uint)testVector.TagLength;
         try
         {
             var config = new Argon2Config
             {
                 Type           = testVector.Type,
                 Version        = testVector.Version,
                 TimeCost       = testVector.Iterations,
                 MemoryCost     = testVector.MemoryKBytes,
                 Lanes          = testVector.Parallelism,
                 Threads        = testVector.Parallelism,
                 Password       = testVector.Password,
                 Salt           = testVector.Salt,
                 Secret         = testVector.Secret,
                 AssociatedData = testVector.AssociatedData,
                 HashLength     = testVector.TagLength
             };
             var argon2 = new Argon2(config);
             SecureArray <byte> hash = argon2.Hash();
             Assert.False(
                 hash.Buffer.Where((b, i) => b != testVector.Tag[i]).Any(),
                 $"Test {testVector.Name}: Got{Environment.NewLine}{BitConverter.ToString(hash.Buffer)}{Environment.NewLine}expected{Environment.NewLine}{BitConverter.ToString(testVector.Tag)}");
             this.output.WriteLine(
                 "Passed Argon2:\r\n"
                 + $"             Version 0x{(int)testVector.Version:X} ({(int)testVector.Version})\r\n"
                 + $"                Type {testVector.Type}\r\n"
                 + $"          Iterations {testVector.Iterations}\r\n"
                 + $"       Memory KBytes {testVector.MemoryKBytes}\r\n"
                 + $"         Parallelism {testVector.Parallelism}\r\n"
                 + $"            Password {BitConverter.ToString(testVector.Password)}\r\n"
                 + $"                Salt {BitConverter.ToString(testVector.Salt)}\r\n"
                 + $"              Secret {BitConverter.ToString(testVector.Secret)}\r\n"
                 + $"       AssciatedData {BitConverter.ToString(testVector.AssociatedData)}\r\n"
                 + $"  Gave expected hash {BitConverter.ToString(hash.Buffer)}\r\n"
                 + $"             encoded {encoded}");
         }
         catch (Exception e)
         {
             Assert.False(true, e.Message);
         }
     }
 }
コード例 #29
0
        public async Task <IActionResult> EditUser(EditUserModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            Person person = context.People.Find(model.Id);

            if (person != null)
            {
                bool taken = person.Login != model.Username && context.People.Any(p => p.Login == model.Username);
                if (taken)
                {
                    ModelState.AddModelError("Username", "Данное имя уже занято");
                    return(View(model));
                }
                if (model.Avatar != null)
                {
                    string userDir = Path.Combine(ImageFolder, person.Id.ToString());
                    if (person.Avatar != null)
                    {
                        System.IO.File.Delete(Path.Combine(userDir, person.Avatar));
                    }
                    else if (!Directory.Exists(userDir))
                    {
                        Directory.CreateDirectory(userDir);
                    }
                    person.Avatar = $"{Path.GetRandomFileName()}.{Path.GetExtension(model.Avatar.FileName)}";
                    await model.Avatar.WriteToFile(Path.Combine(userDir, person.Avatar));
                }
                person.Login = model.Username;
                if (!string.IsNullOrEmpty(model.NewPassword))
                {
                    person.PasswordHash = Argon2.Hash(model.NewPassword);
                }
                person.Role = model.Role;
                await context.SaveChangesAsync();

                return(Redirect("/Home/Index"));
            }
            else
            {
                ModelState.AddModelError("", "Неверный ID");
                return(View(model));
            }
        }
コード例 #30
0
 public bool Create(UserEntity user)
 {
     try
     {
         var password = Encoding.UTF8.GetString(Convert.FromBase64String(user.Password));
         var hash     = Argon2.Hash(password);
         context.Users.Add(new Users {
             CustomerId = user.CustomerId, UserEmail = user.Email, UserFirstName = user.FirstName, UserId = user.Id, UserIsActive = true, UserLastName = user.LastName, UserPassword = hash
         });
         context.SaveChanges();
         return(true);
     }
     catch (Exception e)
     {
         throw e;
     }
 }