public static User Map(User oldUser, UpdateUserRequest request, IConfigurationUtility configurationUtility)
        {
            User newUser = new User
            {
                UserKey    = request.UserKey,
                Name       = request.Name,
                Company    = request.Company,
                CreateDate = oldUser.CreateDate,
                LastUpdate = DateTime.UtcNow,
                Options    = request.Options,
                Contacts   = request.Contacts,
                Address    = request.Address,
                Roles      = request.Roles
            };

            newUser.Contacts.Email = request.Contacts.Email.ToLowerInvariant().Trim();

            var passwordHash = (request.Password == null)
                ? oldUser.Security.PasswordHash
                : HashUtility.GenerateSha256(request.Password, configurationUtility.HashGap);

            newUser.Security = oldUser.Security;
            newUser.Security.PasswordHash = passwordHash;

            return(newUser);
        }
        public static User Map(CreateUserRequest request, IConfigurationUtility configurationUtility)
        {
            User user = new User
            {
                UserKey    = Guid.NewGuid(),
                Name       = request.Name,
                Company    = request.Company,
                CreateDate = DateTime.UtcNow
            };

            user.LastUpdate     = user.CreateDate;
            user.Options        = request.Options;
            user.Contacts       = request.Contacts;
            user.Contacts.Email = request.Contacts.Email.ToLowerInvariant().Trim();
            user.Address        = request.Address;
            user.Roles          = request.Roles;

            user.Security = new UserSecurityWithPass()
            {
                PasswordHash           = HashUtility.GenerateSha256(request.Password, configurationUtility.HashGap),
                EmailConfirmationToken = HashUtility.GenerateRandomSha256(),
                EmailConfirmed         = false,
                IsBlocked = false
            };

            return(user);
        }
示例#3
0
        private static void AggregateCore(
            MarkdownHeadingBlockToken headToken,
            IMarkdownTokenAggregateContext context,
            int offset,
            List <DfmTabItemBlockToken> items,
            IMarkdownToken terminator)
        {
            var md = items.Aggregate(StringBuffer.Empty, (s, t) => s + t.SourceInfo.Markdown);

            if (terminator != null)
            {
                md += terminator.SourceInfo.Markdown;
                offset++;
            }
            var groupId = HashUtility.GetSha256HashString(items[0].SourceInfo.File ?? string.Empty).Replace("/", "-").Remove(10);

            context.AggregateTo(
                new DfmTabGroupBlockToken(
                    DfmTabGroupBlockRule.Instance,
                    headToken.Context,
                    groupId,
                    items.ToImmutableArray(),
                    0,
                    headToken.SourceInfo.Copy(md.ToString())),
                offset);
        }
示例#4
0
        private static string ComputePluginHash(List <Assembly> assemblyList)
        {
            Logger.LogVerbose("Calculating plugin hash...");

            var result = string.Empty;

            if (assemblyList?.Count > 0)
            {
                var builder = new StringBuilder();
                foreach (var assembly in
                         from assembly in assemblyList
                         orderby assembly.FullName
                         select assembly)
                {
                    var hashPart = assembly.FullName;
                    builder.AppendLine(hashPart);
                    var fileVersion = assembly.GetCustomAttribute <AssemblyFileVersionAttribute>()?.Version;
                    Logger.LogVerbose($"New assembly info added: '{hashPart}'. Detailed file version: '{fileVersion}'");
                }
                result = HashUtility.GetSha256HashString(builder.ToString());
            }

            Logger.LogVerbose($"Plugin hash is '{result}'");
            return(result);
        }
示例#5
0
        public async Task <IActionResult> Authenticate(string username, string password)
        {
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return(BadRequest());
            }

            // create hashed version of password
            var salt          = Config.GetSection("GStore").GetValue <string>("password_salt");
            var password_hash = new HashUtility().MakeHash(password, salt);

            var user = await UnitOfWork.Repository <User>()
                       .GetSingleAsync(u => u.Username == username &&
                                       u.Password == password_hash &&
                                       u.Enabled &&
                                       !u.Deleted);

            if (user == null)
            {
                return(Forbid());
            }

            return(Ok(new
            {
                access = SecurityService.GenerateToken(user)
            }));
        }
示例#6
0
        public void UpdateBuildVersionInfoPerDependencyGraph()
        {
            if (CurrentBuildVersionInfo.Dependency == null)
            {
                return;
            }
            var fileAttributes = CurrentBuildVersionInfo.Attributes;
            var nodesToUpdate  = CurrentBuildVersionInfo.Dependency.GetAllDependentNodes().Except(fileAttributes.Keys, FilePathComparer.OSPlatformSensitiveStringComparer);

            foreach (var node in nodesToUpdate)
            {
                RelativePath path = RelativePath.TryParse(node);
                if (path == null)
                {
                    continue;
                }
                string fullPath = Path.Combine(EnvironmentContext.BaseDirectory, path.RemoveWorkingFolder());
                if (File.Exists(fullPath))
                {
                    fileAttributes[node] = new FileAttributeItem
                    {
                        File             = node,
                        LastModifiedTime = File.GetLastWriteTimeUtc(fullPath),
                        Hash             = HashUtility.GetSha256HashString(File.ReadAllText(fullPath)),
                    };
                }
            }
        }
        /// <summary>
        /// 创建补丁清单文件到输出目录
        /// </summary>
        private void CreatePatchManifestFile(AssetBundleBuilder.BuildParametersContext buildParameters,
                                             BuildMapContext buildMapContext, TaskEncryption.EncryptionContext encryptionContext)
        {
            int resourceVersion = buildParameters.Parameters.BuildVersion;

            // 创建新补丁清单
            PatchManifest patchManifest = new PatchManifest();

            patchManifest.EnableAddressable = buildParameters.Parameters.EnableAddressable;
            patchManifest.ResourceVersion   = buildParameters.Parameters.BuildVersion;
            patchManifest.BuildinTags       = buildParameters.Parameters.BuildinTags;
            patchManifest.BundleList        = GetAllPatchBundle(buildParameters, buildMapContext, encryptionContext);
            patchManifest.AssetList         = GetAllPatchAsset(buildParameters, buildMapContext, patchManifest);

            // 创建补丁清单文件
            string manifestFilePath = $"{buildParameters.PipelineOutputDirectory}/{YooAssetSettingsData.GetPatchManifestFileName(resourceVersion)}";

            BuildRunner.Log($"创建补丁清单文件:{manifestFilePath}");
            PatchManifest.Serialize(manifestFilePath, patchManifest);

            // 创建补丁清单哈希文件
            string manifestHashFilePath = $"{buildParameters.PipelineOutputDirectory}/{YooAssetSettingsData.GetPatchManifestHashFileName(resourceVersion)}";
            string manifestHash         = HashUtility.FileMD5(manifestFilePath);

            BuildRunner.Log($"创建补丁清单哈希文件:{manifestHashFilePath}");
            FileUtility.CreateFile(manifestHashFilePath, manifestHash);

            // 创建静态版本文件
            string staticVersionFilePath = $"{buildParameters.PipelineOutputDirectory}/{YooAssetSettings.VersionFileName}";
            string staticVersion         = resourceVersion.ToString();

            BuildRunner.Log($"创建静态版本文件:{staticVersionFilePath}");
            FileUtility.CreateFile(staticVersionFilePath, staticVersion);
        }
示例#8
0
        private static void PrepareFiles(IWebHostEnvironment env, Options options)
        {
            var imageFilePath  = options.ImageFilePath;
            var fileDir        = options.InputDirectory;
            var workingDirName = HashUtility.ComputeFileMd5Hash(imageFilePath);
            var workingPath    = Path.Combine(env.WebRootPath, workingDirName);

            if (Directory.Exists(workingPath))
            {
                Directory.Delete(workingPath, true);
            }

            Directory.CreateDirectory(workingPath);

            var coverPath = Path.Combine(workingPath, $"cover{Path.GetExtension(imageFilePath)}");

            File.Copy(imageFilePath, coverPath);

            EnsureItunesCompliantImage(coverPath);

            var srcFiles = Directory.GetFiles(fileDir).OrderBy(s => s).ToArray();

            for (var i = 0; i < srcFiles.Length; ++i)
            {
                var mediaPath = Path.Combine(workingPath, $@"file{i}{Path.GetExtension(srcFiles[i])}");

                File.Copy(srcFiles[i], mediaPath);
            }
        }
示例#9
0
        private void GridControl_ItemsSourceChangeCompleted(object sender, EventArgs e)
        {
            if (this.dataTableControl?.Source == null)
            {
                return;
            }

            var tableID   = this.dataTableControl.Source.TableID;
            var columnsID = this.dataTableControl.Source.Columns.Select(item => (object)item.ColumnID).ToArray();

            this.columnsHashValue = HashUtility.GetHashValue(columnsID);

            if (this.Configs.TryParse <string>(this.GetType(), $"{nameof(this.columnsHashValue)}-{tableID}", out var columnsHashValue) == true)
            {
                if (this.columnsHashValue != columnsHashValue)
                {
                    return;
                }
            }

            if (this.Configs.TryParse <Xceed.Wpf.DataGrid.Settings.SettingsRepository>(this.GetType(), tableID.ToString(), out var settings) == true)
            {
                this.gridControl.LoadUserSettings(settings, Xceed.Wpf.DataGrid.Settings.UserSettings.All);
            }
        }
示例#10
0
        public string Post([FromBody] string user)
        {
            Users           userr      = JsonConvert.DeserializeObject <Users>(user);
            MySqlConnection Connection = WebApiConfig.Connection();


            MySqlCommand QuerySelectUser = Connection.CreateCommand();

            QuerySelectUser.CommandText = "SELECT Users.Email from Users where Email=@email;";
            QuerySelectUser.Parameters.AddWithValue("@email", userr.Email);


            MySqlCommand QueryInsertUser = Connection.CreateCommand();

            QueryInsertUser.CommandText = "INSERT INTO Users (Name,Surname,Password,Email) VALUES (@name,@surname,@password,@email);" + " SELECT last_insert_id();";
            QueryInsertUser.Parameters.AddWithValue("@name", userr.Name);
            QueryInsertUser.Parameters.AddWithValue("@password", HashUtility.HashPassword(userr.Password));
            QueryInsertUser.Parameters.AddWithValue("@surname", userr.Surname);
            QueryInsertUser.Parameters.AddWithValue("@email", userr.Email);


            try
            {
                Connection.Open();

                string UserEmail = Convert.ToString(QuerySelectUser.ExecuteScalar());

                if (UserEmail == userr.Email)
                {
                    Connection.Close();
                    return("WrongEmail");
                }


                Token tok = Token.GenerateNewInicializationToken();

                MySqlCommand QueryInsertTokensUsers = Connection.CreateCommand();



                int UserId = Convert.ToInt32(QueryInsertUser.ExecuteScalar());

                QueryInsertTokensUsers.CommandText = "INSERT INTO TokensUsers (IdToken,IdUser) VALUES (@idToken,@idUser);";
                QueryInsertTokensUsers.Parameters.AddWithValue("@idToken", tok.ID);
                QueryInsertTokensUsers.Parameters.AddWithValue("@idUser", UserId);

                QueryInsertTokensUsers.ExecuteNonQuery();
            }
            catch (MySql.Data.MySqlClient.MySqlException ex)
            {
                return("ConnectionWithDatabaseProblem");
            }


            Connection.Close();


            return("OK");
        }
示例#11
0
        public static void GenerateSha256_Should_Return_Hash_For_Specific_String()
        {
            // arrange / act
            var hash = HashUtility.GenerateSha256("test");

            // assert
            Assert.Equal(hash, "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08");
        }
        public void CreateHash_ShouldCreateHash_WhenUsingCodePage1252CharactersInPassword()
        {
            string password = TestAssets.CodePage1252Characters;

            string hash = HashUtility.CreateHash(password);

            Assert.True(PasswordHashIsValid(hash));
        }
        public void CreateHash_ShouldCreateHash_WhenUsingAllPrintableAsciiCharactersInPassword()
        {
            string password = TestAssets.AllPrintableAsciiCharacters;

            string hash = HashUtility.CreateHash(password);

            Assert.True(PasswordHashIsValid(hash));
        }
        public void CreateHash_ShouldCreateHash_WhenSingleColonProvidedAsPassword()
        {
            string password = "******";

            string hash = HashUtility.CreateHash(password);

            Assert.True(PasswordHashIsValid(hash));
        }
        public void CreateHash_ShouldCreateHash_WhenOnlyColonsProvidedInPassword()
        {
            string password = "******";

            string hash = HashUtility.CreateHash(password);

            Assert.True(PasswordHashIsValid(hash));
        }
        public void ValidatePassword_ShouldThrowAnArgumentNullException_WhenPasswordAndCorrectHashAreWhiteSpace()
        {
            string password = "******";

            string correctHash = "   ";

            Assert.Throws <ArgumentNullException>(() => HashUtility.AreEqual(password, correctHash));
        }
        public void CreateHash_ShouldCreateHash_WhenColonProvidedInPassword()
        {
            string password = "******";

            string hash = HashUtility.CreateHash(password);

            Assert.True(PasswordHashIsValid(hash));
        }
        public void ValidatePassword_ShouldReturnTrue_WhenPasswordHashAndCorrectHashMatchUsingCodePage1252Characters()
        {
            string password = "******"¡#¢$£%¤&¥'¦(§)¨*©+ª,«-¬./®0¯1°2±3²4³5´6µ7¶8·9¸¹;º<»=¼>½?¾@¿AÀBÁCÂDÃEÄFÅGÆHÇIÈJÉKÊLËMÌNÍOÎPÏQÐRÑSÒTÓUÔVÕWÖX×YØZÙ[Ú\\Û]Ü^Ý_Þ`ßaàbácâdãeäfågæhçièjékêlëmìníoîpïqðrñsòtóuôvõwöx÷yøzù{ú|û}ü~ý";

            string correctHash = HashUtility.CreateHash(password);

            Assert.True(HashUtility.AreEqual(password, correctHash));
        }
        public void ValidatePassword_ShouldReturnTrue_WhenPasswordHashAndCorrectHashMatchUsingAllPrintableAsciiCharacters()
        {
            string password = "******"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";

            string correctHash = HashUtility.CreateHash(password);

            Assert.True(HashUtility.AreEqual(password, correctHash));
        }
示例#20
0
 /// <summary>
 /// Computes a SHA-1 hash value of the specified <see cref="string"/> value.
 /// </summary>
 /// <param name="value">The <see cref="string"/> value to compute a hash code for.</param>
 /// <returns>A <see cref="string"/> containing the computed SHA-1 hash value of <paramref name="value"/>.</returns>
 /// <remarks>Do override this method if you prefer another hashing than SHA-1.</remarks>
 protected virtual string ComputeHash(string value)
 {
     return(HashUtility.ComputeHash(value, o =>
     {
         o.AlgorithmType = HashAlgorithmType.SHA1;
         o.Encoding = Encoding;
     }).ToHexadecimal());
 }
        public void ValidatePassword_ShouldReturnTrue_WhenPasswordHashAndCorrectHashMatch()
        {
            string password = "******";

            string correctHash = HashUtility.CreateHash(password);

            Assert.True(HashUtility.AreEqual(password, correctHash));
        }
 /// <summary>
 /// Returns the hash code for this instance.
 /// </summary>
 /// <returns>A 32-bit signed integer that is the hash code for this instance.</returns>
 public override int GetHashCode()
 {
     return(HashUtility.CombineHash(
                position.GetHashCode(),
                startTime.GetHashCode(),
                endTime.GetHashCode()
                ));
 }
        public void ValidatePassword_ShouldReturnFalse_WhenCorrectHashDoesNotContainIntegerAsFirstElement()
        {
            string password = "******";

            string correctHash = "foo:Bar:fluff";

            Assert.False(HashUtility.AreEqual(password, correctHash));
        }
        public void ValidatePassword_ShouldThrowAnInvalidOperationException_WhenCorrectHashSplitLengthIsTooLarge()
        {
            string password = "******";

            string correctHash = "as:djlkdsf:jkfa:fsdf";

            Assert.Throws <InvalidOperationException>(() => HashUtility.AreEqual(password, correctHash));
        }
示例#25
0
        public static void GenerateRandomSha256_Should_Return_Hash_For_Specific_String_With_Gap()
        {
            // arrange / act
            var hash = HashUtility.GenerateSha256("test", "gap");

            // assert
            Assert.Equal(hash, "2b104763f73d857260e81bd2394c89e98cf87df5e8fb99bc82a508b693aadc94");
        }
        public void ValidatePassword_ShouldReturnFalse_WhenPasswordHashAndCorrectHashDoNotMatch()
        {
            string password = "******";

            string correctHash = HashUtility.CreateHash("!something.Different*");

            Assert.False(HashUtility.AreEqual(password, correctHash));
        }
        public void ValidatePassword_ShouldThrowAFormatException_WhenCorrectHashPasswordHashElementIsEmpty()
        {
            string password = "******";

            string correctHash = "123:Bar:";

            Assert.Throws <FormatException>(() => HashUtility.AreEqual(password, correctHash));
        }
        public void ValidatePassword_ShouldThrowAnArgumentNullException_WhenPasswordIsNullAndCorrectHashIsEmpty()
        {
            string password = null;

            string correctHash = "";

            Assert.Throws <ArgumentNullException>(() => HashUtility.AreEqual(password, correctHash));
        }
示例#29
0
        public string HashBlockHeaderAndTransactions(BlockHeader header, List <Transaction> transactions)
        {
            header.Hash = null;
            string headerHash = HashUtility.SHA256(JsonConvert.SerializeObject(header));
            string txHash     = HashBlockTransactions(transactions);

            return(HashUtility.SHA256(headerHash + txHash));
        }
        public void ValidatePassword_ShouldThrowAFormatException_WhenCorrectHashSaltElementIsNotAMultipleOf4()
        {
            string password = "******";

            string correctHash = "123:Bar:ABCD";

            Assert.Throws <FormatException>(() => HashUtility.AreEqual(password, correctHash));
        }