Exemplo n.º 1
0
        public async Task <ActionResult> CalculateHashes()
        {
            // Получим информацию о файле
            var mime = Request.ContentType;

            if (mime == null)
            {
                return(StatusCode(415));                // Unsupported Media Type
            }
            var filePath = Path.GetTempFileName();

            using (var fs = new FileStream(filePath, FileMode.Create))
            {
                await Request.Body.CopyToAsync(fs);
            }

            var result = new HashResult();

            using (var img = new ImgProcessing(filePath))
            {
                result.AHash = img.Processing(Mode.CropAHash);
                result.PHash = img.Processing(Mode.CropPHash);
                result.DHash = img.Processing(Mode.CropDHash);
            }

            var file = new FileInfo(filePath);

            file.Delete();

            return(Ok(result));
        }
Exemplo n.º 2
0
        protected override void ProcessRecordInEH()
        {
            string encodingName = EncodingName;

            if (string.IsNullOrWhiteSpace(encodingName))
            {
                encodingName = EncodingFactory.EncodingNames.UTF8;
            }

            Encoding encoding = EncodingFactory.Get(encodingName);

            if (encoding == null)
            {
                throw new PSArgumentException(string.Format("Unsupported encoding: {0}", encodingName));
            }

            HashAlgorithm algorithm = HashAlgorithmFactory.Create(Algorithm);

            if (algorithm == null)
            {
                throw new PSArgumentException(string.Format("Unsupported algorithm: {0}", Algorithm));
            }

            byte[] hashBuffer = HashGenerator.ComputeStringHash(InputObject, algorithm, encoding);

            HashResult result = new HashResult()
            {
                Algorithm  = Algorithm,
                Hash       = hashBuffer.ToHex(),
                HashBuffer = hashBuffer,
            };

            WriteObject(result);
        }
Exemplo n.º 3
0
        static async Task <string> CreateOrderAsync()
        {
            KeyValuePair <string, string>[] payload = new[] {
                new KeyValuePair <string, string>("currency", "CLP"),
                new KeyValuePair <string, string>("description", "description"),
                new KeyValuePair <string, string>("merchant_order_id", "--order-id--"),
                new KeyValuePair <string, string>("notify_url", "http://notification.merchant.com"),
                new KeyValuePair <string, string>("price", "1500"),
                new KeyValuePair <string, string>("return_url", "http://final.merchant.com"),
                new KeyValuePair <string, string>("timeout", "60")
            };

            var formContent = new FormUrlEncodedContent(payload);

            // GENERATE HASH
            HashResult hashResult = GenerateHash("POST", "/merchant/orders/", payload);

            client.BaseAddress = new Uri("https://sandboxapi.pago46.com/");
            client.DefaultRequestHeaders.Add("merchant-key", merchantKey);
            client.DefaultRequestHeaders.Add("message-hash", hashResult.hash);
            client.DefaultRequestHeaders.Add("message-date", hashResult.date.ToString());

            HttpResponseMessage response = await client.PostAsync("merchant/orders/", formContent);

            string response_contents = await response.Content.ReadAsStringAsync();

            return(response_contents);
        }
Exemplo n.º 4
0
        public void HMACSHATest()
        {
            string str = "Hello world!";
            string key = "123456";

            string[] types = Enum.GetNames(typeof(HMACAlgorithmTypes));

            foreach (var item in types)
            {
#if !NFX
                if (item == "RIPEMD160")
                {
                    continue;
                }
#endif
                Console.WriteLine($"HMACAlgorithmType: {item}");

                HashResult result = HMAC.Encrypt((HMACAlgorithmTypes)Enum.Parse(typeof(HMACAlgorithmTypes), item), str, key);

                Type type = result.GetType();

                var props = type.GetProperties();

                foreach (var prop in props)
                {
                    if (prop.PropertyType == typeof(string))
                    {
                        Console.WriteLine($"{prop.Name}:{prop.GetValue(result, null)}");
                    }
                }

                Console.WriteLine();
            }
        }
Exemplo n.º 5
0
        public static string GetChecksum(string file)
        {
            IHash      crc64 = HashFactory.Checksum.CreateCRC64_ECMA();
            HashResult r     = crc64.ComputeFile(file);

            return(r.ToString());
        }
Exemplo n.º 6
0
        public IActionResult RegisterUser([Bind] UserModel user)
        {
            WebDbContext db = HttpContext.RequestServices.GetService(typeof(Web.Utils.WebDbContext)) as WebDbContext;

            if (ModelState.IsValid)
            {
                // Check if email already exists in db
                if (db.GetLoginUsername(user) > 0)
                {
                    return(RedirectToAction("RegisterUserExists"));
                }

                // Generate new salt and hash password
                var            password       = user.Password.ToString();
                PasswordHasher pwHasher       = new PasswordHasher();
                HashResult     hashedPassword = pwHasher.HashNewSalt(password, 20, SHA512.Create());
                user.Salt     = hashedPassword.Salt;
                user.Password = hashedPassword.Digest;

                // Register new user
                db.RegisterUser(user);

                // Redirect to user area
                ModelState.Clear();
                return(RedirectToAction("UserLogin"));
            }

            // Model data invalid
            return(RedirectToAction("RegisterModelFailed"));
        }
Exemplo n.º 7
0
        public void MyTestMethod()
        {
            string str = "Hello world!";

            string[] types = Enum.GetNames(typeof(SHAAlgorithmTypes));

            foreach (var item in types)
            {
                Console.WriteLine($"SHAAlgorithmType: {item}");

                HashResult result = SHA.Encrypt((SHAAlgorithmTypes)Enum.Parse(typeof(SHAAlgorithmTypes), item), str);

                Type type = result.GetType();

                var props = type.GetProperties();

                foreach (var prop in props)
                {
                    if (prop.PropertyType == typeof(string))
                    {
                        Console.WriteLine($"{prop.Name}:{prop.GetValue(result, null)}");
                    }
                }

                Console.WriteLine();
            }
        }
Exemplo n.º 8
0
        public void StringTest()
        {
            IHash      hash       = HashFactory.Crypto.SHA3.CreateKeccak();
            HashResult hashResult = hash.ComputeString("This is a message!");

            Assert.True(hashResult.GetBytes().Length == 64);
        }
Exemplo n.º 9
0
        protected void TestMultipleTransforms(IHash a_multi, IHash a_hash, IList<int> a_list)
        {
            List<byte[]> v1 = new List<byte[]>(a_list.Count);

            foreach (int length in a_list)
            {
                byte[] ar = new byte[length];
                for (int i = 0; i < ar.Length; i++)
                    ar[i] = (byte)m_random.Next(Byte.MaxValue);
                v1.Add(ar);
            }

            int len = 0;
            foreach (byte[] ar in v1)
                len += ar.Length;

            byte[] v2 = new byte[len];

            int index = 0;
            foreach (byte[] ar in v1)
            {
                Array.Copy(ar, 0, v2, index, ar.Length);
                index += ar.Length;
            }

            a_multi.Initialize();

            for (int i = 0; i < v1.Count; i++)
                a_multi.TransformBytes(v1[i]);

            HashResult h1 = a_multi.TransformFinal();
            HashResult h2 = a_hash.ComputeBytes(v2);

            Assert.AreEqual(h2, h1, a_hash.Name);
        }
Exemplo n.º 10
0
        public override IHashResult TransformFinal()
        {
            var result = new HashResult(Hash);

            Initialize();
            return(result);
        }
        public void GivenAnEmptySaltCacheHashWillGenerateSalt()
        {
            var mockSaltCache  = new Mock <ISaltCache>();
            var savedSaltKey   = "";
            var savedSaltValue = "";

            mockSaltCache.Setup(s => s.TryAdd(It.IsAny <string>(), It.IsAny <string>())).Callback <string, string>(
                (key, value) =>
            {
                savedSaltKey   = key;
                savedSaltValue = value;
            });

            var mockHashProvider = new Mock <IHashProvider>();
            var hashResult       = new HashResult(Root.Any.String(), Root.Any.String());

            mockHashProvider.Setup(h => h.CreateHash(It.IsAny <string>(), It.IsAny <string>())).Returns(hashResult);

            var sut = new HashRepository(mockHashProvider.Object, mockSaltCache.Object, true);

            const string unhashed = "unhashed";
            var          entity   = new WordMetric(unhashed, unhashed, Root.Any.Integer(), null);

            var hashedEntities = sut.Hash(new[] { entity });
            var hashedEntity   = hashedEntities.First();

            Assert.IsFalse(unhashed == hashedEntity.Id);
            Assert.AreEqual(hashResult.Hash, hashedEntity.Id);

            Assert.AreEqual(hashResult.Salt, hashedEntity.Salt);

            Assert.AreEqual(hashResult.Salt, savedSaltValue);
            Assert.AreEqual(unhashed, savedSaltKey);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Calculates a SHA3-512 hash signature.
        /// </summary>
        /// <param name="input">The byte array for which to calculate the hash</param>
        /// <returns>The SHA3-512 digest.</returns>
        public static byte[] SHA3_512(byte[] input)
        {
            IHash      hash = HashFactory.Crypto.SHA3.CreateKeccak512();
            HashResult res  = hash.ComputeBytes(input);

            return(res.GetBytes());
        }
Exemplo n.º 13
0
        /// <summary>
        /// Hashes a byte array through MD4.
        /// </summary>
        /// <param name="input">The byte array for which to calculate the hash</param>
        /// <returns>The MD4 digest.</returns>
        public static byte[] MD4(byte[] input)
        {
            IHash      hash = HashFactory.Crypto.CreateMD4();
            HashResult res  = hash.ComputeBytes(input);

            return(res.GetBytes());
        }
Exemplo n.º 14
0
    private static long Solve(string salt, int md5Count)
    {
        HashResult[] arr = new HashResult[MaxIndexToCalculateFor];
        ComputeHashResultsParallel(arr, salt, md5Count, 0, MaxIndexToCalculateFor, 8);

        int keyCount = 0;
        int j        = -1;

        while (keyCount < 64)
        {
            j++;

            var curr = arr[j];
            if (curr.Triplet != null)
            {
                for (int k = j + 1; k < j + 1001; k++)
                {
                    if (arr[k].Fives != null && arr[k].Fives.Contains(curr.Triplet))
                    {
                        keyCount++;
                    }
                }
            }
        }

        return(j);
    }
Exemplo n.º 15
0
        internal static HashResult ComputeHash(FileInfo fileInfo, int bytes)
        {
            DateTime   dtStart = DateTime.Now;
            HashResult result  = new HashResult
            {
                FileInfo    = fileInfo,
                HashedBytes = bytes
            };

            try
            {
                byte[] buffer = ReadFirstFileBytes(fileInfo.FullName, bytes);
                result.HashBeginning = ComputeHash(buffer);


                buffer            = ReadLastFileBytes(fileInfo.FullName, bytes);
                result.HashEnding = ComputeHash(buffer);

                result.Success = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            result.Duration = DateTime.Now - dtStart;
            return(result);
        }
Exemplo n.º 16
0
            protected override void RewriteCore(HtmlDocument document)
            {
                var newPrefix = $"{this._controller.Request.Scheme}://{this._controller.Request.Host.ToUriComponent()}/pypi/pythonhosted-packages/";

                foreach (var el in document.DocumentNode?.SelectNodes("/html/body/a") ?? Enumerable.Empty <HtmlNode>())
                {
                    var href = el.GetAttributeValue("href", null);
                    if (href != null)
                    {
                        var relHref = href.Replace(PythonHostedPackagesController.Prefix, "");

                        var match = HashRegex.Match(relHref);
                        if (match.Success)
                        {
                            var key   = match.Groups[1].Value;
                            var value = new HashResult(HashAlgorithmName.SHA256, match.Groups[3].Value);
                            this._controller._memoryCache.Set(key, value);

                            el.SetAttributeValue("href", newPrefix + relHref);
                        }
                        else
                        {
                            this._controller._logger.LogWarning("Unable to parse hash value from {}", href);
                        }
                    }
                }
            }
Exemplo n.º 17
0
        public static string GetHash(string str)
        {
            IHash      hash = Hash;
            HashResult res  = hash.ComputeString(str);

            return(GetString(res.GetBytes()));
        }
Exemplo n.º 18
0
        public async Task <AuthenticationTicket> GetRootAuthenticateTicketAsync(string username, string password)
        {
            var user = await _dbContext.Set <CcUiAuthen>().AsNoTracking().FirstOrDefaultAsync(p => p.Login == username);

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

            IHash      hash            = HashFactory.Crypto.CreateWhirlpool();
            HashResult r               = hash.ComputeString(password, Encoding.ASCII);
            string     passwordEncoded = Regex.Replace(r.ToString(), "-", string.Empty).ToLower();

            if (user.PwdEncoded != passwordEncoded)
            {
                return(null);
            }
            var identity = new ClaimsIdentity();

            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Userid.ToString()));
            identity.AddClaim(new Claim(ClaimTypes.Role, "Administrator"));
            var principal = new ClaimsPrincipal(identity);
            var prop      = new AuthenticationProperties()
            {
                IssuedUtc  = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.AddDays(1)
            };

            return(new AuthenticationTicket(principal, prop, "application"));
        }
Exemplo n.º 19
0
        public void hashFugue()
        {
            string     paramIn  = "73ed6f3bd1805c003de63ae11f76630d35602c1a1b9504ba3f42233176425213622c9c630c830175b4f8a81f633e8bb98c663e142bcc88b0baaa7dd9e73a6907";
            string     paramOut = "af72d939050259913e440b23bee62e3b9604129ec8424d265a6ee4916e060000e51eead6ded2b584283ac0e04c1ea582e1a757245b5e8c408520216139e17848";
            HashResult result   = HashFactory.Crypto.SHA3.CreateFugue512().ComputeBytes(Encoders.Hex.DecodeData(paramIn));

            Assert.Equal(paramOut, Encoders.Hex.EncodeData(result.GetBytes()));
        }
Exemplo n.º 20
0
        public void hashSkeinCustom()
        {
            string     paramIn  = "317024467e25cb6f1014f1b7a98c63b2ccc925b05a72180b0cdf23f42fabe653ddf51d11ce471dca48282b22261bbc7f5a729189c52554443a635889c7d47db6";
            string     paramOut = "a4d126f16372bd2df3e22bc95f61e696a72a1bee32e62ca90fedc24e94dbdf314446dc00a5e6bc2907d73c7210e6cb780be00b49b26b7a6f2db29249f2bd884b";
            HashResult result   = HashFactory.Crypto.SHA3.CreateSkein512_Custom().ComputeBytes(Encoders.Hex.DecodeData(paramIn));

            Assert.Equal(paramOut, Encoders.Hex.EncodeData(result.GetBytes()));
        }
Exemplo n.º 21
0
        } // end function Initialize

        override public IHashResult TransformFinal()
        {
            IHashResult result = new HashResult(hash);

            Initialize();

            return(result);
        } // end function TransformFinal
Exemplo n.º 22
0
        public void hashSIMD()
        {
            string     paramIn  = "0bb309f45b7ec5b115a3318f0b2f0e431c8e415a3d6848087e7905e4e47c52874b79947e4bdee71668d1b1487716da57ac1f8d87e149ce1eee9080d6cc2827df";
            string     paramOut = "921ca1f5fc388ff8217e5bc787acb7e5b462063c12dca18b56b8bff0791d5c338b6604b74cd2c77ed7ac3a5a3843deb27e82f077c71a11a7308fc90864a0bd89";
            HashResult result   = HashFactory.Crypto.SHA3.CreateSIMD512().ComputeBytes(Encoders.Hex.DecodeData(paramIn));

            Assert.Equal(paramOut, Encoders.Hex.EncodeData(result.GetBytes()));
        }
Exemplo n.º 23
0
        public void hashSHAvite3Custom()
        {
            string     paramIn  = "50ddc199803de46305083d0852bc4005fc473ed05ec56347ae65e9875c0571da7375bb227678805e7ef868015bd4bf714bae038937538dd7819cc58b6d03ca7b";
            string     paramOut = "0bb309f45b7ec5b115a3318f0b2f0e431c8e415a3d6848087e7905e4e47c52874b79947e4bdee71668d1b1487716da57ac1f8d87e149ce1eee9080d6cc2827df";
            HashResult result   = HashFactory.Crypto.SHA3.CreateSHAvite3_512_Custom().ComputeBytes(Encoders.Hex.DecodeData(paramIn));

            Assert.Equal(paramOut, Encoders.Hex.EncodeData(result.GetBytes()));
        }
Exemplo n.º 24
0
        public void hashCubeHash()
        {
            string     paramIn  = "8bc3589bea395cdd461226ccbea9cfa463edc5d556ff8c60f8053502135781747ae56b521ced7208fcf6c30dc6f9169b51f5452021b6951fa3d8240f3972d740";
            string     paramOut = "50ddc199803de46305083d0852bc4005fc473ed05ec56347ae65e9875c0571da7375bb227678805e7ef868015bd4bf714bae038937538dd7819cc58b6d03ca7b";
            HashResult result   = HashFactory.Crypto.SHA3.CreateCubeHash512().ComputeBytes(Encoders.Hex.DecodeData(paramIn));

            Assert.Equal(paramOut, Encoders.Hex.EncodeData(result.GetBytes()));
        }
Exemplo n.º 25
0
        public void hashKeccak()
        {
            string     paramIn  = "c295dd0155177a9104a80ec27b245600f0de17db4aee4a16a1cf386db29b6a8e5ea74c32bb6c317f388f6585d4b338e53959399e75fcaa16045a4094da19cb6d";
            string     paramOut = "c4f7a14f01cab51c317b7b0064932004ac72a85d8686a9165e1f8b8a968113cd7a3398554ef1c92a3c296c192f9314a2365bc0f7775d4e478787055a9b2ce897";
            HashResult result   = HashFactory.Crypto.SHA3.CreateKeccak512().ComputeBytes(Encoders.Hex.DecodeData(paramIn));

            Assert.Equal(paramOut, Encoders.Hex.EncodeData(result.GetBytes()));
        }
Exemplo n.º 26
0
        public void hashJH()
        {
            string     paramIn  = "a4d126f16372bd2df3e22bc95f61e696a72a1bee32e62ca90fedc24e94dbdf314446dc00a5e6bc2907d73c7210e6cb780be00b49b26b7a6f2db29249f2bd884b";
            string     paramOut = "c295dd0155177a9104a80ec27b245600f0de17db4aee4a16a1cf386db29b6a8e5ea74c32bb6c317f388f6585d4b338e53959399e75fcaa16045a4094da19cb6d";
            HashResult result   = HashFactory.Crypto.SHA3.CreateJH512().ComputeBytes(Encoders.Hex.DecodeData(paramIn));

            Assert.Equal(paramOut, Encoders.Hex.EncodeData(result.GetBytes()));
        }
Exemplo n.º 27
0
        public void hashEcho()
        {
            string     paramIn  = "921ca1f5fc388ff8217e5bc787acb7e5b462063c12dca18b56b8bff0791d5c338b6604b74cd2c77ed7ac3a5a3843deb27e82f077c71a11a7308fc90864a0bd89";
            string     paramOut = "ad8f8a4b105ffb83bb7546da799e29caa5bc9f2d0b584bdbf7d3275c65bdaae849e277187321d7d323e827c901530f6073bb967a198f3e3ba52c3a01716a442b";
            HashResult result   = HashFactory.Crypto.SHA3.CreateEcho512().ComputeBytes(Encoders.Hex.DecodeData(paramIn));

            Assert.Equal(paramOut, Encoders.Hex.EncodeData(result.GetBytes()));
        }
Exemplo n.º 28
0
        public void hashHamsi()
        {
            string     paramIn  = "ad8f8a4b105ffb83bb7546da799e29caa5bc9f2d0b584bdbf7d3275c65bdaae849e277187321d7d323e827c901530f6073bb967a198f3e3ba52c3a01716a442b";
            string     paramOut = "73ed6f3bd1805c003de63ae11f76630d35602c1a1b9504ba3f42233176425213622c9c630c830175b4f8a81f633e8bb98c663e142bcc88b0baaa7dd9e73a6907";
            HashResult result   = HashFactory.Crypto.SHA3.CreateHamsi512().ComputeBytes(Encoders.Hex.DecodeData(paramIn));

            Assert.Equal(paramOut, Encoders.Hex.EncodeData(result.GetBytes()));
        }
Exemplo n.º 29
0
        public void hashLuffa()
        {
            string     paramIn  = "c4f7a14f01cab51c317b7b0064932004ac72a85d8686a9165e1f8b8a968113cd7a3398554ef1c92a3c296c192f9314a2365bc0f7775d4e478787055a9b2ce897";
            string     paramOut = "8bc3589bea395cdd461226ccbea9cfa463edc5d556ff8c60f8053502135781747ae56b521ced7208fcf6c30dc6f9169b51f5452021b6951fa3d8240f3972d740";
            HashResult result   = HashFactory.Crypto.SHA3.CreateLuffa512().ComputeBytes(Encoders.Hex.DecodeData(paramIn));

            Assert.Equal(paramOut, Encoders.Hex.EncodeData(result.GetBytes()));
        }
Exemplo n.º 30
0
        public void hashGroestl()
        {
            string     paramIn  = "b2e1d72db8a3807d6d929a0e1349250cae0e99475d94bd869d0163755574a89078e08f604ff32833585dc45d28a69c0b269abb3fcd5c4ee09afc8ca32fa7e40d";
            string     paramOut = "317024467e25cb6f1014f1b7a98c63b2ccc925b05a72180b0cdf23f42fabe653ddf51d11ce471dca48282b22261bbc7f5a729189c52554443a635889c7d47db6";
            HashResult result   = HashFactory.Crypto.SHA3.CreateGroestl512().ComputeBytes(Encoders.Hex.DecodeData(paramIn));

            Assert.Equal(paramOut, Encoders.Hex.EncodeData(result.GetBytes()));
        }