public void ShouldAggregateAndFilter()
        {
            var result = ExecuteScan("bookId=1&bizDate-granularity=daily");
            var objs   = SortByBizDateAndBook(result);

            var expected = new JArray(
                JObject.FromObject(new
            {
                version    = DigestUtils.Md5Hex("v1" + "v4"),
                attributes = new
                {
                    bizDate = "2010-01-15",
                    bookId  = "1"
                }
            }),
                JObject.FromObject(new
            {
                version    = DigestUtils.Md5Hex("v2"),
                attributes = new
                {
                    bizDate = "2010-01-16",
                    bookId  = "1"
                }
            })
                );

            AssertJsonEqual(expected, objs);
        }
Пример #2
0
        public void ShouldBucketByHundreds()
        {
            var buckets = new Dictionary <string, string> {
                { "someInt", "100s" }
            };
            var builder = new DigestBuilder(buckets);

            builder.Add("id1", new Dictionary <string, string> {
                { "someInt", "123" }
            }, "vsn1");
            builder.Add("id2", new Dictionary <string, string> {
                { "someInt", "234" }
            }, "vsn2");
            builder.Add("id3", new Dictionary <string, string> {
                { "someInt", "125" }
            }, "vsn3");

            var expected = new List <AggregateDigest>
            {
                new AggregateDigest(new List <string> {
                    "100"
                }, DigestUtils.Md5Hex("vsn1" + "vsn3")),
                new AggregateDigest(new List <string> {
                    "200"
                }, DigestUtils.Md5Hex("vsn2"))
            };
            var aggregateDigests = builder.GetDigests();

            // TODO fudged because Assert.AreEqual did not seem to work as expected on the actual AggregateDigest objects
            Assert.AreEqual(expected[0].Attributes, aggregateDigests[0].Attributes);
            Assert.AreEqual(expected[0].Digest, aggregateDigests[0].Digest);
            Assert.AreEqual(expected[1].Attributes, aggregateDigests[1].Attributes);
            Assert.AreEqual(expected[1].Digest, aggregateDigests[1].Digest);
        }
Пример #3
0
        private async Task OnFinish(EditContext editContext)
        {
            Console.WriteLine("开始提交表单[" + userEntity + "].");

            messageStore = new ValidationMessageStore(editContext);

            await this.ValidatorByUsername(editContext);

            await this.ValidatorByPassword(editContext);

            if (editContext.GetValidationMessages().Any())
            {
                editContext.NotifyValidationStateChanged();
                messageStore.Clear();

                return;
            }

            if (StringUtils.IsBlank(userId))
            {
                userEntity.Password = DigestUtils.Md5Hex(userEntity.PasswordNew);
            }

            await this.userService.SaveAsync(userEntity);

            _ = base.FeedbackRef.CloseAsync();
        }
Пример #4
0
        public static IWebHost BuildWebHost() =>
        WebHost.CreateDefaultBuilder()
        .UseKestrel(
            options =>
        {
#if DEBUG
            options.Listen(IPAddress.Loopback, 5000);
            backendServerPort = 5000;
#else
            // Get free TCP port and write it to STDOUT where the Electron frontend can catch it.
            backendServerPort = FindFreeTcpPort();
            options.Listen(IPAddress.Loopback, backendServerPort, listenOptions =>
            {
                var httpsOptions =
                    new HttpsConnectionAdapterOptions
                {
                    ServerCertificate =
                        CertificateGenerator
                        .GenerateCertificate(
                            $"CN={DigestUtils.GetDigestFromAssembly(typeof(Program).Assembly).ToLowerInvariant()}")
                };

                listenOptions.UseHttps(httpsOptions);
            });
#endif
        })
        .UseStartup <Startup>()
        .Build();
Пример #5
0
            /// <summary>
            /// 初始化临时账号
            /// </summary>
            /// <param name="fileKey">操作文件 key,可以为空,删除资源的时候不能为空</param>
            public async Task Init(string fileKey)
            {
                using (await AsyncLocker.LockAsync()) {
                    // 防止重复初始化
                    if (!IsTimeout())
                    {
                        return;
                    }
                    var rest = await fetchTmpCred(fileKey);

                    if (!HttpRestService.ForData(rest, out var cred))
                    {
                        throw new RestFailedException(rest.Message);
                    }
                    TmpCred = cred;
                    var    keyTime = $"{TimeHelper.GetTimestampSec(cred.StartTime)};{TimeHelper.GetTimestampSec(cred.ExpiredTime)}";
                    string signKey = DigestUtils.GetHamcSha1ToHexString(keyTime, Encoding.UTF8, cred.TmpSecretKey, Encoding.UTF8);
                    cloudCredentials = new SessionQCloudCredentials(
                        cred.TmpSecretId,
                        signKey,
                        cred.SessionToken,
                        keyTime
                        );
                }
            }
Пример #6
0
    public void MayFast()
    {
        Span <byte> hash = stackalloc byte[HashConstants.SM3Length];

        using var sm3 = DigestUtils.Create(DigestType.Sm3);
        sm3.UpdateFinal(_randombytes.Span, hash);
    }
Пример #7
0
        public override QCloudCredentials GetQCloudCredentials()
        {
            if (IsNeedUpdateNow())
            {
                Refresh();
            }

            if (tmpSecretId == null)
            {
                throw new CosClientException((int)CosClientError.InvalidCredentials, "secretId == null");
            }

            if (tmpSecretKey == null)
            {
                throw new CosClientException((int)CosClientError.InvalidCredentials, "secretKey == null");
            }

            if (keyTime == null)
            {
                throw new CosClientException((int)CosClientError.InvalidCredentials, "keyTime == null");
            }

            string signKey = DigestUtils.GetHamcSha1ToHexString(keyTime, Encoding.UTF8, tmpSecretKey, Encoding.UTF8);

            return(new SessionQCloudCredentials(tmpSecretId, signKey, token, keyTime));
        }
Пример #8
0
        /// <summary>
        /// $HttpString = [HttpMethod]\n[HttpURI]\n[HttpParameters]\n[HttpHeaders]\n
        /// </summary>
        /// <param name="method"></param>
        /// <param name="path"></param>
        /// <param name="queryParameters"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public string GenerateSource(string method, string path, Dictionary <string, string> queryParameters, Dictionary <string, string> headers)
        {
            StringBuilder formatString = new StringBuilder();

            formatString.Append(method.ToLower()).Append('\n'); // method
            formatString.Append(path).Append('\n');             // path

            //check header and parameter in request
            string headerResult    = CheckHeaders(headers);
            string parameterResult = CheckParameters(queryParameters);

            if (parameterResult != null)
            {
                formatString.Append(parameterResult);                          // parameters
            }
            formatString.Append('\n');
            if (headerResult != null)
            {
                formatString.Append(headerResult);                       // headers
            }
            formatString.Append('\n');
            StringBuilder stringToSign = new StringBuilder();

            stringToSign.Append(CosAuthConstants.SHA1).Append('\n');
            stringToSign.Append(signTime).Append('\n');
            stringToSign.Append(DigestUtils.GetSha1ToHexString(formatString.ToString(), Encoding.UTF8)).Append('\n');
            return(stringToSign.ToString());
        }
        public async Task <IActionResult> UploadXmlFile(List <IFormFile> files)
        {
            var file = this.Request?.Form?.Files?.FirstOrDefault();

            if (file == null)
            {
                return(this.BadRequest("Datei konnte nicht geladen werden."));
            }

            this.applicationState.CurrentSupplierFile          = new SupplierFile();
            this.applicationState.CurrentSupplierFile.Data     = new MemoryStream();
            this.applicationState.CurrentSupplierFile.Filename = file.FileName;
            await file.CopyToAsync(this.applicationState.CurrentSupplierFile.Data);

            this.applicationState.CurrentSupplierFile.DigestRipemd160 =
                DigestUtils.GetRipemd160(this.applicationState.CurrentSupplierFile.Data);

            this.applicationState.CurrentSupplierFile.DigestSha3 =
                DigestUtils.GetSha3(this.applicationState.CurrentSupplierFile.Data);

            try
            {
                this.applicationState.CurrentSupplierFile.Data.Position = 0;
                this.applicationState.CurrentSupplierFile.Xml           = XDocument.Load(this.applicationState.CurrentSupplierFile.Data);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to XML file: {0}", ex.Message);
                this.applicationState.CurrentSupplierFile.Xml = null;
                return(this.BadRequest("Datei konnte nicht geladen werden."));
            }

            return(this.Ok());
        }
Пример #10
0
    public void Default()
    {
        Span <byte> hash = stackalloc byte[HashConstants.Sha384Length];

        using var sha384 = DigestUtils.Create(DigestType.Sha384);
        sha384.UpdateFinal(_randombytes.Span, hash);
    }
Пример #11
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: public java.io.File prepareDirectoryForTest(String test) throws java.io.IOException
        public virtual File PrepareDirectoryForTest(string test)
        {
            string dir = DigestUtils.md5Hex(_jvmExecutionHash + test);

            EvaluateClassBaseTestFolder();
            Register(test, dir);
            return(CleanDirectory(dir));
        }
Пример #12
0
        /// <summary>Each message sent to Realex should have a hash, attached. For a message using the remote
        /// interface this is generated using the This is generated from the TIMESTAMP, MERCHANT_ID,
        /// ORDER_ID, AMOUNT, and CURRENCY fields concatenated together with "." in between each field.
        /// This confirms the message comes
        /// from the client and
        /// Generate a hash, required for all messages sent to IPS to prove it was not tampered with.
        /// <p>
        /// Hashing takes a string as input, and produce a fixed size number (160 bits for SHA-1 which
        /// this implementation uses). This number is a hash of the input, and a small change in the
        /// input results in a substantial change in the output. The functions are thought to be secure
        /// in the sense that it requires an enormous amount of computing power and time to find a string
        /// that hashes to the same value. In others words, there's no way to decrypt a secure hash.
        /// Given the larger key size, this implementation uses SHA-1 which we prefer that you, but Realex
        /// has retained compatibilty with MD5 hashing for compatibility with older systems.
        /// <p>
        /// <p>
        /// To construct the hash for the remote interface follow this procedure:
        ///
        /// To construct the hash for the remote interface follow this procedure:
        /// Form a string by concatenating the above fields with a period ('.') in the following order
        /// <p>
        /// (TIMESTAMP.MERCHANT_ID.ORDER_ID.AMOUNT.CURRENCY)
        /// <p>
        /// Like so (where a field is empty an empty string "" is used):
        /// <p>
        /// (20120926112654.thestore.ORD453-11.29900.EUR)
        /// <p>
        /// Get the hash of this string (SHA-1 shown below).
        /// <p>
        /// (b3d51ca21db725f9c7f13f8aca9e0e2ec2f32502)
        /// <p>
        /// Create a new string by concatenating this string and your shared secret using a period.
        /// <p>
        /// (b3d51ca21db725f9c7f13f8aca9e0e2ec2f32502.mysecret )
        /// <p>
        /// Get the hash of this value. This is the value that you send to Realex Payments.
        /// <p>
        /// (3c3cac74f2b783598b99af6e43246529346d95d1)
        ///
        /// This method takes the pre-built string of concatenated fields and the secret and returns the
        /// SHA-1 hash to be placed in the request sent to Realex.
        ///
        /// @param toHash
        /// @param secret
        /// @return the hash as a hex string
        /// </summary>
        /// <param name="toHash"></param>
        /// <param name="secret"></param>
        ///<returns>string</returns>
        public static string GenerateHash(string toHash, string secret)
        {
            string toHashFirstPass = DigestUtils.Sha1Hex(toHash);

            string toHashSecondPass = new StringBuilder(toHashFirstPass).Append(".").Append(secret).ToString();

            return(DigestUtils.Sha1Hex(toHashSecondPass));
        }
Пример #13
0
 /// <summary>
 /// Returns a tracking identifier that can be used to associate usages of a
 /// token across multiple client sessions.
 /// </summary>
 /// <remarks>
 /// Returns a tracking identifier that can be used to associate usages of a
 /// token across multiple client sessions.
 /// Currently, this function just returns an MD5 of {
 /// <see cref="GetBytes()"/>
 /// .
 /// </remarks>
 /// <returns>tracking identifier</returns>
 public virtual string GetTrackingId()
 {
     if (trackingId == null)
     {
         trackingId = DigestUtils.Md5Hex(GetBytes());
     }
     return(trackingId);
 }
Пример #14
0
        public static ulong CalcCRC32(byte[] input, int len)
        {
            using var hash = DigestUtils.Create(DigestType.Crc32);
            var t = new byte[hash.Length];

            hash.UpdateFinal(input.AsSpan(0, len), t);
            return(BinaryPrimitives.ReadUInt32BigEndian(t));
        }
        public static byte[] SHA1(ReadOnlySpan <byte> input)
        {
            var output = new byte[HashConstants.Sha1Length];

            using var hash = DigestUtils.Create(DigestType.Sha1);
            hash.UpdateFinal(input, output);
            return(output);
        }
Пример #16
0
        public ScanResultEntry ToScanResultEntry()
        {
            if (_digest == null)
            {
                _digest = DigestUtils.Md5Hex(_builder.ToString());
            }

            return(ScanResultEntry.ForAggregate(Attributes, _digest));
        }
Пример #17
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="customerKey"></param>
 public void SetCosServerSideEncryptionWithCustomerKey(string customerKey)
 {
     if (customerKey != null)
     {
         SetRequestHeader("x-cos-server-side-encryption-customer-algorithm", "AES256");
         SetRequestHeader("x-cos-server-side-encryption-customer-key", DigestUtils.GetBase64(customerKey, Encoding.UTF8));
         SetRequestHeader("x-cos-server-side-encryption-customer-key-MD5", DigestUtils.GetMd5ToBase64(customerKey, Encoding.UTF8));
     }
 }
Пример #18
0
        public static void SetCRC32(byte[] buffer)
        {
            using var hash = DigestUtils.Create(DigestType.Crc32);
            var t = new byte[hash.Length];

            hash.UpdateFinal(buffer.AsSpan(0, buffer.Length - 4), t);
            var x = ~BinaryPrimitives.ReadUInt32BigEndian(t);

            BinaryPrimitives.WriteUInt32LittleEndian(buffer.AsSpan(buffer.Length - 4), x);
        }
Пример #19
0
 public static IMac Create(DigestType type, ReadOnlySpan <byte> key)
 {
     return(type switch
     {
         DigestType.Md5 => Create(key, HashAlgorithmName.MD5),
         DigestType.Sha1 => Create(key, HashAlgorithmName.SHA1),
         DigestType.Sha256 => Create(key, HashAlgorithmName.SHA256),
         DigestType.Sha384 => Create(key, HashAlgorithmName.SHA384),
         DigestType.Sha512 => Create(key, HashAlgorithmName.SHA512),
         _ => Create(key, DigestUtils.Create(type))
     });
Пример #20
0
 public void SetCosServerSideEncryptionWithKMS(string customerKeyID, string json)
 {
     SetRequestHeader("x-cos-server-side-encryption", "cos/kms");
     if (customerKeyID != null)
     {
         SetRequestHeader("x-cos-server-side-encryption-cos-kms-key-id", customerKeyID);
     }
     if (json != null)
     {
         SetRequestHeader("x-cos-server-side-encryption-context", DigestUtils.GetBase64(json, Encoding.UTF8));
     }
 }
Пример #21
0
        public void Sign(Request request, IQCloudSignSource qcloudSignSource, QCloudCredentials qcloudCredentials)
        {
            if (request == null)
            {
                throw new ArgumentNullException("Request == null");
            }

            if (qcloudCredentials == null)
            {
                throw new ArgumentNullException("QCloudCredentials == null");
            }

            if (qcloudSignSource == null || !(qcloudSignSource is CosXmlSignSourceProvider))
            {
                throw new ArgumentNullException("CosXmlSourceProvider == null");
            }

            CosXmlSignSourceProvider cosXmlSourceProvider = (CosXmlSignSourceProvider)qcloudSignSource;


            string signTime = cosXmlSourceProvider.GetSignTime();

            if (signTime == null)
            {
                signTime = qcloudCredentials.KeyTime;
                cosXmlSourceProvider.SetSignTime(signTime);
            }

            string        signature   = DigestUtils.GetHamcSha1ToHexString(cosXmlSourceProvider.Source(request), Encoding.UTF8, qcloudCredentials.SignKey, Encoding.UTF8);
            StringBuilder signBuilder = new StringBuilder();


            signBuilder.Append(CosAuthConstants.Q_SIGN_ALGORITHM).Append('=').Append(CosAuthConstants.SHA1).Append('&')
            .Append(CosAuthConstants.Q_AK).Append('=').Append(qcloudCredentials.SecretId).Append('&')
            .Append(CosAuthConstants.Q_SIGN_TIME).Append('=').Append(signTime).Append('&')
            .Append(CosAuthConstants.Q_KEY_TIME).Append('=').Append(qcloudCredentials.KeyTime).Append('&')
            .Append(CosAuthConstants.Q_HEADER_LIST).Append('=').Append(cosXmlSourceProvider.GetHeaderList()).Append('&')
            .Append(CosAuthConstants.Q_URL_PARAM_LIST).Append('=').Append(cosXmlSourceProvider.GetParameterList()).Append('&')
            .Append(CosAuthConstants.Q_SIGNATURE).Append('=').Append(signature);
            string sign = signBuilder.ToString();

            request.AddHeader(CosRequestHeaderKey.AUTHORIZAIION, sign);

            if (qcloudCredentials is SessionQCloudCredentials)
            {
                request.AddHeader(CosRequestHeaderKey.COS_SESSION_TOKEN, ((SessionQCloudCredentials)qcloudCredentials).Token);
            }

            if (cosXmlSourceProvider.onGetSign != null)
            {
                cosXmlSourceProvider.onGetSign(request, sign);
            }
        }
Пример #22
0
        public static string GenerateSign(string method, string path, Dictionary <string, string> queryParameters, Dictionary <string, string> headers, string signTime, QCloudCredentials qcloudCredentials)
        {
            if (qcloudCredentials == null)
            {
                throw new ArgumentNullException("QCloudCredentials == null");
            }

            CosXmlSignSourceProvider cosXmlSourceProvider = new CosXmlSignSourceProvider();

            if (signTime == null)
            {
                signTime = qcloudCredentials.KeyTime;
            }

            cosXmlSourceProvider.SetSignTime(signTime);

            if (headers != null)
            {
                foreach (string key in headers.Keys)
                {
                    cosXmlSourceProvider.AddHeaderKey(key);
                }
            }

            if (queryParameters != null)
            {
                foreach (string key in queryParameters.Keys)
                {
                    cosXmlSourceProvider.AddParameterKey(key);
                }
            }

            string signature = DigestUtils.GetHamcSha1ToHexString(cosXmlSourceProvider.GenerateSource(method, path, queryParameters, headers), Encoding.UTF8,
                                                                  qcloudCredentials.SignKey, Encoding.UTF8);

            StringBuilder signBuilder = new StringBuilder();

            signBuilder.Append(CosAuthConstants.Q_SIGN_ALGORITHM).Append('=').Append(CosAuthConstants.SHA1).Append('&')
            .Append(CosAuthConstants.Q_AK).Append('=').Append(qcloudCredentials.SecretId).Append('&')
            .Append(CosAuthConstants.Q_SIGN_TIME).Append('=').Append(cosXmlSourceProvider.GetSignTime()).Append('&')
            .Append(CosAuthConstants.Q_KEY_TIME).Append('=').Append(qcloudCredentials.KeyTime).Append('&')
            .Append(CosAuthConstants.Q_HEADER_LIST).Append('=').Append(cosXmlSourceProvider.GetHeaderList()).Append('&')
            .Append(CosAuthConstants.Q_URL_PARAM_LIST).Append('=').Append(cosXmlSourceProvider.GetParameterList()).Append('&')
            .Append(CosAuthConstants.Q_SIGNATURE).Append('=').Append(signature);

            if (qcloudCredentials is SessionQCloudCredentials)
            {
                signBuilder.Append("&").Append(CosRequestHeaderKey.COS_SESSION_TOKEN).Append("=").Append(((SessionQCloudCredentials)qcloudCredentials).Token);
            }

            return(signBuilder.ToString());
        }
Пример #23
0
 public override string GetMD5()
 {
     try
     {
         fileStream.Seek(fileOffset, SeekOrigin.Begin);
         return(DigestUtils.GetMd5ToBase64(fileStream, contentLength));
     }
     catch (Exception ex)
     {
         QLog.Error(TAG, ex.Message, ex);
         throw;
     }
 }
Пример #24
0
        public AggregateDigest ToDigest()
        {
            if (_digest == null)
            {
                _digest = DigestUtils.Md5Hex(_builder.ToString());
            }
            var keys = Attributes.Keys.ToArray();

            Array.Sort(keys);
            var attributes = keys.Select(key => Attributes[key]).ToList();

            return(new AggregateDigest(attributes, _digest));
        }
Пример #25
0
        /// <summary>
        /// Gets the digest of the specified file.
        /// </summary>
        /// <param name="item">The item to calculate the digest for.</param>
        private void GetDigest(DigestItem item)
        {
            var directory = Path.GetDirectoryName(this.GetType().Assembly.Location);
            var filepath  = Path.Combine(directory, item.Filepath);

            if (File.Exists(filepath))
            {
                item.Digest = DigestUtils.GetRipemd160(filepath).AddSpace(4).Value;
            }
            else
            {
                item.Digest = "nicht gefunden";
            }
        }
Пример #26
0
            public Dictionary <string, string> GetFormParameters()
            {
                Dictionary <string, string> formParameters = new Dictionary <string, string>();

                if (acl != null)
                {
                    formParameters.Add("Acl", acl);
                }

                foreach (KeyValuePair <string, string> pair in headers)
                {
                    formParameters.Add(pair.Key, pair.Value);
                }

                formParameters.Add("key", key);

                if (successActionRedirect != null)
                {
                    formParameters.Add("success_action_redirect", successActionRedirect);
                }

                if (successActionStatus != null)
                {
                    formParameters.Add("success_action_status", successActionStatus);
                }

                foreach (KeyValuePair <string, string> pair in customHeaders)
                {
                    formParameters.Add(pair.Key, pair.Value);
                }

                if (xCosStorageClass != null)
                {
                    formParameters.Add("x-cos-storage-class", xCosStorageClass);
                }

                if (xCOSTrafficLimit != null)
                {
                    formParameters.Add(CosRequestHeaderKey.X_COS_TRAFFIC_LIMIT, xCOSTrafficLimit);
                }

                if (policy != null)
                {
                    formParameters.Add("policy", DigestUtils.GetBase64(policy.Content(), Encoding.UTF8));
                }

                return(formParameters);
            }
        private static TimeStampToken RequestTST(byte[] contentToTimestamp, string tsaService, Oid hashAlg, string policy, string nonce, bool certReq, UserCredentials credentials, TimestampResult result)
        {
            byte[] nonceBytes    = null;
            byte[] hashedMessage = DigestUtils.ComputeDigest(contentToTimestamp, hashAlg);
            if (!string.IsNullOrEmpty(nonce))
            {
                nonceBytes = HexStringToBytes(nonce);
            }

            var request = new Request(hashedMessage, hashAlg, nonceBytes, policy, certReq);

            result.TimeStampRequest = request;
            result.Tsq = request.ToByteArray();

            return(TimeStampClient.RequestTimeStampToken(tsaService, request, credentials));
        }
Пример #28
0
        public static void testMd5(string path1, string path2)
        {
            Stream fileInputStream = new FileStream(path1, FileMode.Open, FileAccess.Read);
            string md51            = DigestUtils.GetMd5ToBase64(fileInputStream);

            fileInputStream.Close();

            Stream fileInputStream2 = new FileStream(path2, FileMode.Open, FileAccess.Read);
            string md52             = DigestUtils.GetMd5ToBase64(fileInputStream2);

            fileInputStream2.Close();

            Console.WriteLine(md51);
            Console.WriteLine(md52);
            Console.WriteLine(md51.CompareTo(md52));
        }
Пример #29
0
        /// <summary>Each message sent to Realex should have a hash, attached. For a message using the remote
        /// interface this is generated using the This is generated from the TIMESTAMP, MERCHANT_ID,
        /// ORDER_ID, AMOUNT, and CURRENCY fields concatenated together with "." in between each field.
        /// This confirms the message comes
        /// from the client and
        /// Generate a hash, required for all messages sent to IPS to prove it was not tampered with.
        /// <p>
        /// Hashing takes a string as input, and produce a fixed size number (160 bits for SHA-1 which
        /// this implementation uses). This number is a hash of the input, and a small change in the
        /// input results in a substantial change in the output. The functions are thought to be secure
        /// in the sense that it requires an enormous amount of computing power and time to find a string
        /// that hashes to the same value. In others words, there's no way to decrypt a secure hash.
        /// Given the larger key size, this implementation uses SHA-1 which we prefer that you, but Realex
        /// has retained compatibilty with MD5 hashing for compatibility with older systems.
        /// <p>
        /// <p>
        /// To construct the hash for the remote interface follow this procedure:
        ///
        /// To construct the hash for the remote interface follow this procedure:
        /// Form a string by concatenating the above fields with a period ('.') in the following order
        /// <p>
        /// (TIMESTAMP.MERCHANT_ID.ORDER_ID.AMOUNT.CURRENCY)
        /// <p>
        /// Like so (where a field is empty an empty string "" is used):
        /// <p>
        /// (20120926112654.thestore.ORD453-11.29900.EUR)
        /// <p>
        /// Get the hash of this string (SHA-1 shown below).
        /// <p>
        /// (b3d51ca21db725f9c7f13f8aca9e0e2ec2f32502)
        /// <p>
        /// Create a new string by concatenating this string and your shared secret using a period.
        /// <p>
        /// (b3d51ca21db725f9c7f13f8aca9e0e2ec2f32502.mysecret )
        /// <p>
        /// Get the hash of this value. This is the value that you send to Realex Payments.
        /// <p>
        /// (3c3cac74f2b783598b99af6e43246529346d95d1)
        ///
        /// This method takes the pre-built string of concatenated fields and the secret and returns the
        /// SHA-1 hash to be placed in the request sent to Realex.
        ///
        /// @param toHash
        /// @param secret
        /// @return the hash as a hex string
        /// </summary>
        /// <param name="toHash"></param>
        /// <param name="secret"></param>
        ///<returns>string</returns>
        public static string GenerateHash(string toHash, string secret = null, ShaHashType shaType = ShaHashType.SHA1)
        {
            if (toHash == null)
            {
                return(toHash);
            }

            string toHashFirstPass = shaType == ShaHashType.SHA1 ? DigestUtils.Sha1Hex(toHash, shaType) : DigestUtils.ShaHex(toHash, shaType);

            if (secret != null)
            {
                string toHashSecondPass = new StringBuilder(toHashFirstPass).Append(".").Append(secret).ToString();
                return(shaType == ShaHashType.SHA1 ? DigestUtils.Sha1Hex(toHashSecondPass, shaType): DigestUtils.ShaHex(toHashSecondPass, shaType));
            }
            return(toHashFirstPass);
        }
        public async Task <IActionResult> DownloadFile(string url, string username, string password)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    if (!string.IsNullOrWhiteSpace(username) || !string.IsNullOrWhiteSpace(password))
                    {
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
                            "Basic",
                            Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{username}:{password}")));
                    }

                    var request = new HttpRequestMessage(HttpMethod.Get, url);

                    using (var response = await client.SendAsync(request))
                    {
                        if (response.IsSuccessStatusCode)
                        {
                            this.applicationState.CurrentSupplierFile      = new SupplierFile();
                            this.applicationState.CurrentSupplierFile.Data =
                                new MemoryStream(await response.Content.ReadAsByteArrayAsync());
                            this.applicationState.CurrentSupplierFile.DownloadUrl = url;
                            this.applicationState.CurrentSupplierFile.Username    = username;
                            this.applicationState.CurrentSupplierFile.Password    = password;

                            this.applicationState.CurrentSupplierFile.DigestRipemd160 =
                                DigestUtils.GetRipemd160(this.applicationState.CurrentSupplierFile.Data);

                            this.applicationState.CurrentSupplierFile.DigestSha3 =
                                DigestUtils.GetSha3(this.applicationState.CurrentSupplierFile.Data);

                            this.applicationState.CurrentSupplierFile.Data.Position = 0;
                            this.applicationState.CurrentSupplierFile.Xml           = XDocument.Load(this.applicationState.CurrentSupplierFile.Data);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(this.BadRequest(ex.Message));
            }

            return(this.Ok());
        }