Exemple #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="pInput"></param>
        /// <param name="pSalt"></param>
        /// <param name="pEncoding"></param>
        /// <returns></returns>
        public string GetSecureHash(string pInput, string pSalt, Encoding pEncoding, HashFormat pFormat)
        {
            int DERIVED_KEY_LENGTH = 32;
            int ITERATION_COUNT    = 24000; //TODO: Konfigurasyondan mı alınmalı

            byte[] hashValue;
            byte[] salt         = Convert.FromBase64String(pSalt);
            string stringToHash = string.IsNullOrEmpty(pInput) ? string.Empty : pInput;

            byte[] bytesToHash = pEncoding.GetBytes(stringToHash);

            using (Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(bytesToHash, salt, ITERATION_COUNT)) {
                hashValue = pbkdf2.GetBytes(DERIVED_KEY_LENGTH);
            }

            string hashString;

            if (pFormat == HashFormat.Base64)
            {
                hashString = Convert.ToBase64String(hashValue);
            }
            else
            {
                hashString = BitConverter.ToString(hashValue).Replace("-", string.Empty);
            }

            return(hashString);
        }
        public static RelayDocument Parse(DocumentInfo documentInfo, string sourceText)
        {
            if (documentInfo is null)
            {
                throw new ArgumentNullException(nameof(documentInfo));
            }

            if (string.IsNullOrEmpty(sourceText))
            {
                throw new ArgumentException(
                          "The source text mustn't be null or empty.",
                          nameof(sourceText));
            }

            HashFormat format    = documentInfo.HashFormat ?? HashFormat.Hex;
            string     algorithm = documentInfo.HashAlgorithm?.ToUpperInvariant() ?? "MD5";
            var        queries   = new List <RelayQuery>();

            foreach (var query in Parse(sourceText))
            {
                queries.Add(new RelayQuery(
                                $"{documentInfo.Name}_{query.Item1}",
                                new DocumentHash(
                                    query.hash,
                                    algorithm,
                                    format),
                                query.sourceText));
            }

            return(new RelayDocument(documentInfo.Name, queries));
        }
Exemple #3
0
        /// <summary> 获取 Hash 加密方法 </summary>
        private static HashAlgorithm GetHashAlgorithm(HashFormat hashFormat)
        {
            HashAlgorithm algorithm = null;

            switch (hashFormat)
            {
            case HashFormat.MD516:
            case HashFormat.MD532:
                algorithm = System.Security.Cryptography.MD5.Create();
                break;

            //case HashFormat.RIPEMD160:
            //    algorithm = RIPEMD160.Create();
            //    break;
            case HashFormat.SHA1:
                algorithm = SHA1.Create();
                break;

            case HashFormat.SHA256:
                algorithm = SHA256.Create();
                break;

            case HashFormat.SHA384:
                algorithm = SHA384.Create();
                break;

            case HashFormat.SHA512:
                algorithm = SHA512.Create();
                break;
            }

            return(algorithm);
        }
 public static String ComputeCrc16(this byte[] bytes, HashFormat hashFormat)
 {
     using (var hashImpl = new CRC16())
     {
         var hashBytes = hashImpl.ComputeHash(bytes);
         return(ConvertToString(hashBytes, hashFormat));
     }
 }
Exemple #5
0
 public HashRecord(string file, byte[] hash, HashType htype = HashType.MD5, HashFormat hformat = HashFormat.Default)
 {
     m_file    = file;
     m_hash    = hash;
     m_htype   = htype;
     m_hformat = hformat;
     m_valid   = true;
 }
Exemple #6
0
 public HashRecord()
 {
     m_file    = null;
     m_hash    = null;
     m_htype   = HashType.Invalid;
     m_hformat = HashFormat.Invalid;
     m_valid   = false;
 }
 public static String ComputeSha512(this byte[] bytes, HashFormat hashFormat)
 {
     using (var hashImpl = SHA512.Create())
     {
         var hashBytes = hashImpl.ComputeHash(bytes);
         return(ConvertToString(hashBytes, hashFormat));
     }
 }
 public static IQueryExecutionBuilder AddMD5DocumentHashProvider(
     this IQueryExecutionBuilder builder,
     HashFormat format)
 {
     builder.RemoveService <IDocumentHashProvider>();
     builder.Services.AddSingleton <IDocumentHashProvider>(
         new MD5DocumentHashProvider(format));
     return(builder);
 }
Exemple #9
0
 public DocumentHash(
     string hash,
     string algorithm,
     HashFormat format = HashFormat.Hex)
 {
     Hash      = hash;
     Algorithm = algorithm;
     Format    = format;
 }
 public static IServiceCollection AddSha256DocumentHashProvider(
     this IServiceCollection services,
     HashFormat format = HashFormat.Base64)
 {
     services.RemoveAll<IDocumentHashProvider>();
     services.AddSingleton<IDocumentHashProvider>(
         new Sha256DocumentHashProvider(format));
     return services;
 }
Exemple #11
0
        private static String ConvertToString(byte[] bytes, HashFormat hashFormat)
        {
            if (bytes == null || bytes.Length == 0)
            {
                return(null);
            }

            switch (hashFormat)
            {
            case HashFormat.Base64:
                return(Convert.ToBase64String(bytes));

            case HashFormat.Binary:
            {
                var sb = new StringBuilder();

                foreach (var b in bytes)
                {
                    var bin = Convert.ToString(b, 2).PadLeft(8, '0');
                    sb.Append(bin);
                }

                return(sb.ToString());
            }

            case HashFormat.Bytes:
            {
                return(String.Join(",", bytes));
            }

            case HashFormat.Dec:
            {
                var binaryNumber = ConvertToString(bytes, HashFormat.Binary);
                return(NumberBaseConverter.ChangeBase(binaryNumber, 2, 10));
            }

            case HashFormat.Hex:
            {
                using (var writer = new StringWriter())
                {
                    writer.Write("0x");

                    foreach (var b in bytes)
                    {
                        writer.Write("{0:x2}", b);
                    }

                    return(writer.ToString());
                }
            }
            }

            return(null);
        }
Exemple #12
0
 public QueryFile(
     string name,
     string sourceText,
     string?hash,
     string hashAlgorithm,
     HashFormat hashFormat)
 {
     Name          = name;
     SourceText    = sourceText;
     Hash          = hash;
     HashAlgorithm = hashAlgorithm;
     HashFormat    = hashFormat;
 }
Exemple #13
0
        /// <summary> 对字符串进行 Hash 加密 </summary>
        public static string Hash(string inputString, HashFormat hashFormat = HashFormat.SHA1)
        {
            var algorithm = GetHashAlgorithm(hashFormat);

            algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString));

            if (hashFormat == HashFormat.MD516)
            {
                return(BitConverter.ToString(algorithm.Hash).Replace("-", "").Substring(8, 16).ToUpper());
            }

            return(BitConverter.ToString(algorithm.Hash).Replace("-", "").ToUpper());
        }
Exemple #14
0
        public string HMAC(string pInput, string pKey, HMACAlgorithms pAlgorithm, HashFormat pFormat)
        {
            UTF8Encoding utf8Encoding = new UTF8Encoding();

            byte[] keyBytes   = utf8Encoding.GetBytes(pKey);
            byte[] inputBytes = utf8Encoding.GetBytes(pInput);
            HMAC   hmac       = null;

            switch (pAlgorithm)
            {
            case HMACAlgorithms.HMACMD5:
                hmac = new HMACMD5(keyBytes);
                break;

            case HMACAlgorithms.HMACRIPEMD160:
                hmac = new HMACRIPEMD160(keyBytes);
                break;

            case HMACAlgorithms.HMACSHA1:
                hmac = new HMACSHA1(keyBytes);
                break;

            case HMACAlgorithms.HMACSHA256:
                hmac = new HMACSHA256(keyBytes);
                break;

            case HMACAlgorithms.HMACSHA384:
                hmac = new HMACSHA384(keyBytes);
                break;

            case HMACAlgorithms.HMACSHA512:
                hmac = new HMACSHA512(keyBytes);
                break;
            }


            byte[] hmacBytes = hmac.ComputeHash(inputBytes);

            string result = string.Empty;

            if (pFormat == HashFormat.Hex)
            {
                result = BitConverter.ToString(hmacBytes).Replace("-", string.Empty);
            }
            else if (pFormat == HashFormat.Base64)
            {
                result = Convert.ToBase64String(hmacBytes);
            }

            return(result);
        }
Exemple #15
0
        /// <summary>
        /// String olarak verilen input verisinin ilgili encoding'e göre byte array karşılığının
        /// istenen algoritma için hash'ini üretir.
        /// </summary>
        /// <param name="input"></param>
        /// <param name="encoding"></param>
        /// <param name="alg"></param>
        /// <returns></returns>
        public string GetHash(string input, Encoding encoding, HashAlgorithms alg, HashFormat pFormat)
        {
            byte[] buffer = encoding.GetBytes(input);

            byte[] hash = GetHash(buffer, HashAlgorithms.MD5);

            if (pFormat == HashFormat.Base64)
            {
                return(Convert.ToBase64String(GetHash(hash, alg)));
            }
            else
            {
                return(BitConverter.ToString(hash).Replace("-", string.Empty));
            }
        }
Exemple #16
0
        public static string ToHashString(byte[] hash, string path, HashType htype = HashType.MD5,
                                          HashFormat format = HashFormat.Default)
        {
            string strHash;
            string ret;

            strHash = HexConverter.ToHexString(hash, HexConverter.OPTION.Lower);

            switch (format)
            {
            case HashFormat.Default:
                ret = strHash + "  " + path;
                break;

            case HashFormat.BSD:
                switch (htype)
                {
                case HashType.MD5:
                    ret = "MD5 (" + path + ") = " + strHash;
                    break;

                case HashType.SHA1:
                    ret = "SHA1 (" + path + ") = " + strHash;
                    break;

                case HashType.SHA256:
                    ret = "SHA256 (" + path + ") = " + strHash;
                    break;

                case HashType.SHA384:
                    ret = "SHA384 (" + path + ") = " + strHash;
                    break;

                case HashType.SHA512:
                    ret = "SHA512 (" + path + ") = " + strHash;
                    break;

                default:
                    throw new HashException("invalid hash algorithm");
                }
                break;

            default:
                throw new HashException("invalid hash format");
            }

            return(ret);
        }
Exemple #17
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="data"></param>
        /// <param name="keyStr"></param>
        /// <returns></returns>
        public string Encrypt(string data, string keyStr, HashFormat pFormat)
        {
            // Encrypt the string to an array of bytes.
            byte[]           plainText = Encoding.Unicode.GetBytes(data);
            ICryptoTransform transform = getEncryptionObject(keyStr).CreateEncryptor();

            byte[] cipherText = transform.TransformFinalBlock(plainText, 0, plainText.Length);
            if (pFormat == HashFormat.Base64)
            {
                return(Convert.ToBase64String(cipherText));
            }
            else
            {
                return(BitConverter.ToString(cipherText).Replace("-", string.Empty));
            }
        }
Exemple #18
0
        public WritePersistedQueryMiddleware(
            QueryDelegate next,
            IWriteStoredQueries writeStoredQueries,
            IDocumentHashProvider documentHashProvider)
        {
            if (documentHashProvider is null)
            {
                throw new ArgumentNullException(nameof(documentHashProvider));
            }

            _next = next
                    ?? throw new ArgumentNullException(nameof(next));
            _writeStoredQueries = writeStoredQueries
                                  ?? throw new ArgumentNullException(nameof(writeStoredQueries));
            _hashName   = documentHashProvider.Name;
            _hashFormat = documentHashProvider.Format;
        }
Exemple #19
0
        public static HashRecord GetHashRecordFromString(string line)
        {
            string file = null;

            byte[]     hash   = null;
            HashFormat format = HashFormat.Invalid;
            HashType   htype  = HashType.Invalid;
            HashRecord hr     = null;
            string     tmp    = null;

            format = GetHashFormatFromString(line);

            if (format == HashFormat.Default)
            {
                htype = GetHashTypeFromString(line, format);

                if (htype == HashType.Invalid)
                {
                    return(null);
                }

                tmp  = line.Substring(0, line.IndexOf(" "));
                file = line.Substring(line.IndexOf(" ") + 2);
            }
            else if (format == HashFormat.BSD)
            {
                htype = GetHashTypeFromString(line, format);

                if (htype == HashType.Invalid)
                {
                    return(null);
                }

                tmp  = line.Substring(line.LastIndexOf(" = ") + 3);
                file = line.Substring(line.IndexOf('(') + 1, line.LastIndexOf(')') - line.IndexOf('(') - 1);
            }
            else
            {
                return(null);
            }

            hash = HexConverter.ToByteArray(tmp);
            hr   = new HashRecord(file, hash, htype, format);
            return(hr);
        }
Exemple #20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="data"></param>
        /// <param name="keyStr"></param>
        /// <returns></returns>
        public string Decrypt(string data, string keyStr, HashFormat pFormat)
        {
            // Decrypt the bytes to a string.
            ICryptoTransform transform = getEncryptionObject(keyStr).CreateDecryptor();

            byte[] dataBytes = null;
            if (pFormat == HashFormat.Base64)
            {
                dataBytes = Convert.FromBase64String(data);
            }
            else
            {
                dataBytes = Toolkit.Instance.HexStringToByteArray(data);
            }
            byte[] decDataBytes = transform.TransformFinalBlock(dataBytes, 0, dataBytes.Length);

            return(Encoding.Unicode.GetString(decDataBytes));
        }
Exemple #21
0
        private static int ComputeHash(string file, HashType htype, HashFormat hformat)
        {
            byte[] hash;

            try {
                if (!file.Equals("-"))
                {
                    hash = Hash.ComputeHash(file, htype);
                }
                else
                {
                    hash = Hash.ComputeHash(Console.OpenStandardInput(), htype);
                }

                Console.WriteLine(Hash.ToHashString(hash, file, htype, hformat));
            } catch (Exception ex) {
                ShowException(ex, assName, file);
                return(1);
            }

            return(0);
        }
Exemple #22
0
        private const int RIJNDAEL_BLOCK_SIZE_BITS = 128;                   //AES-256 uyumlu olabilmesi için! (AES tüm anahtar uzunlukları için (218,192,256) 128bit blok kullanır)
        #endregion

        #region Public Method(s)
        /// <summary>
        /// Bir grup nesnenin sırasına göre combine hash'ini alır.
        /// </summary>
        /// <param name="alg"></param>
        /// <param name="inputs"></param>
        /// <returns></returns>
        public string GetHash(HashAlgorithms alg, HashFormat pFormat, params object[] inputs)
        {
            List <byte> buffer = new List <byte>();

            foreach (var obj in inputs)
            {
                if (obj == null)
                {
                    continue;
                }
                buffer.AddRange(getBytes(obj));
            }

            byte[] hash = this.GetHash(buffer.ToArray(), alg);

            if (pFormat == HashFormat.Base64)
            {
                return(Convert.ToBase64String(hash));
            }
            else
            {
                return(BitConverter.ToString(hash).Replace("-", string.Empty));
            }
        }
        /// <summary> 获取 Hash 加密方法 </summary>
        private static HashAlgorithm GetHashAlgorithm(HashFormat hashFormat)
        {
            HashAlgorithm algorithm;

            switch (hashFormat)
            {
            case HashFormat.MD516:
            case HashFormat.MD532:
                algorithm = System.Security.Cryptography.MD5.Create();
                break;

            //case HashFormat.RIPEMD160:
            //    algorithm = RIPEMD160.Create();
            //    break;
            case HashFormat.SHA1:
                algorithm = SHA1.Create();
                break;

            case HashFormat.SHA256:
                algorithm = SHA256.Create();
                break;

            case HashFormat.SHA384:
                algorithm = SHA384.Create();
                break;

            case HashFormat.SHA512:
                algorithm = SHA512.Create();
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(hashFormat), hashFormat, null);
            }

            return(algorithm);
        }
Exemple #24
0
        /// <summary>
        /// 对字符串进行 Hash 加密
        /// </summary>
        /// <param name="inputString"></param>
        /// <param name="hashFormat"></param>
        /// <returns></returns>
        public static string Hash(string inputString, HashFormat hashFormat)
        {
            HashAlgorithm algorithm = GetHashAlgorithm(hashFormat);
            algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString));

            if (hashFormat == HashFormat.MD516) return BitConverter.ToString(algorithm.Hash).Replace("-", "").Substring(8, 16).ToUpper();

            return BitConverter.ToString(algorithm.Hash).Replace("-", "").ToUpper();
        }
Exemple #25
0
 public MD5DocumentHashProvider(HashFormat format)
     : base(format)
 {
 }
        public async Task ActivePersistedQueries_SaveQuery_InvalidHash_MD5(
            HashFormat format)
        {
            // arrange
            var serviceCollection = new ServiceCollection();

            // configure presistence
            serviceCollection.AddGraphQLSchema(b => b
                                               .AddDocumentFromString("type Query { foo: String }")
                                               .AddResolver("Query", "foo", "bar"));
            serviceCollection.AddQueryExecutor(b => b
                                               .AddMD5DocumentHashProvider(format)
                                               .UseActivePersistedQueryPipeline());

            // add in-memory query storage
            serviceCollection.AddSingleton <InMemoryQueryStorage>();
            serviceCollection.AddSingleton <IReadStoredQueries>(sp =>
                                                                sp.GetRequiredService <InMemoryQueryStorage>());
            serviceCollection.AddSingleton <IWriteStoredQueries>(sp =>
                                                                 sp.GetRequiredService <InMemoryQueryStorage>());

            IServiceProvider services =
                serviceCollection.BuildServiceProvider();

            IQueryExecutor executor =
                services.GetRequiredService <IQueryExecutor>();

            var hashProvider =
                services.GetRequiredService <IDocumentHashProvider>();
            var storage = services.GetRequiredService <InMemoryQueryStorage>();

            var    query = new QuerySourceText("{ foo }");
            string hash  = hashProvider.ComputeHash(query.AsSpan());

            // act and assert
            IExecutionResult result = await executor.ExecuteAsync(
                QueryRequestBuilder.New()
                .SetQueryName(hash)
                .AddExtension("persistedQuery",
                              new Dictionary <string, object>
            {
                { hashProvider.Name, hash }
            })
                .Create());

            result.MatchSnapshot(new SnapshotNameExtension(
                                     "Query_Not_Found_" + format));

            result = await executor.ExecuteAsync(
                QueryRequestBuilder.New()
                .SetQueryName(hash)
                .SetQuery("{ foo }")
                .AddExtension("persistedQuery",
                              new Dictionary <string, object>
            {
                { hashProvider.Name, hash }
            })
                .Create());

            result.MatchSnapshot(new SnapshotNameExtension(
                                     "Query_Stored_" + format));

            result = await executor.ExecuteAsync(
                QueryRequestBuilder.New()
                .SetQueryName(hash)
                .AddExtension("persistedQuery",
                              new Dictionary <string, object>
            {
                { hashProvider.Name, hash }
            })
                .Create());

            result.MatchSnapshot(new SnapshotNameExtension(
                                     "Query_Loaded_From_Cache_" + format));
        }
Exemple #27
0
 /// <inheritdoc />
 public IConversion SetHashFormat(HashFormat hashFormat)
 {
     _hashFormat = $"-hash {hashFormat.ToString()} ";
     return(this);
 }
Exemple #28
0
        /// <summary>
        /// 获取加密方法
        /// </summary>
        /// <param name="hashFormat"></param>
        /// <returns></returns>
        private static HashAlgorithm GetHashAlgorithm(HashFormat hashFormat)
        {
            HashAlgorithm algorithm = null;

            switch (hashFormat)
            {
                case HashFormat.MD516:
                    algorithm = MD5.Create();
                    break;

                case HashFormat.MD532:
                    algorithm = MD5.Create();
                    break;

                case HashFormat.RIPEMD160:
                    algorithm = RIPEMD160.Create();
                    break;

                case HashFormat.SHA1:
                    algorithm = SHA1.Create();
                    break;

                case HashFormat.SHA256:
                    algorithm = SHA256.Create();
                    break;

                case HashFormat.SHA384:
                    algorithm = SHA384.Create();
                    break;

                case HashFormat.SHA512:
                    algorithm = SHA512.Create();
                    break;
            }

            return algorithm;
        }
Exemple #29
0
        public static String ComputeCrc16Ccitt(this String text, Encoding encoding, HashFormat hashFormat)
        {
            var bytes = encoding.GetBytes(text);

            return(bytes.ComputeCrc16Ccitt(CRC16CCITT.Seeds.Zeros, hashFormat));
        }
Exemple #30
0
        public static String ComputeCrc32(this String text, Encoding encoding, HashFormat hashFormat)
        {
            var bytes = encoding.GetBytes(text);

            return(bytes.ComputeCrc32(hashFormat));
        }
Exemple #31
0
 public static String ComputeCrc32(this String text, HashFormat hashFormat)
 {
     return(ComputeCrc32(text, Encoding.UTF8, hashFormat));
 }
Exemple #32
0
 public static String ComputeCrc16Ccitt(this byte[] bytes, CRC16CCITT.Seeds seed, HashFormat hashFormat)
 {
     using (var hashImpl = new CRC16CCITT(seed))
     {
         var hashBytes = hashImpl.ComputeHash(bytes);
         return(ConvertToString(hashBytes, hashFormat));
     }
 }