コード例 #1
0
ファイル: HashedFile.cs プロジェクト: kaosborn/Filebert
                public void AddActual(string name, byte[] storedActualHash, HashMode hashStyle = HashMode.Binary)
                {
                    var item = new HashedFile(name, storedActualHash, hashStyle, storedActualHash);

                    Data.items.Add(item);
                    item.IsMatch = storedActualHash == null? (bool?)null : true;
                }
コード例 #2
0
        public async Task Submit(HashMode hashMode, string name, string description, string descriptionUrl, IList <string> files, string filter)
        {
            logger.LogInformation("Editing AppInstaller job {0} with {1} files", name, files.Count());

            var cert = await keyVaultService.GetCertificateAsync().ConfigureAwait(false);

            var publisher = cert.SubjectName.Name;

            // We need to open the files, and update the publisher value
            foreach (var file in files)
            {
                XDocument manifest;
                using (var fs = File.OpenRead(file))
                {
                    manifest = XDocument.Load(fs, LoadOptions.PreserveWhitespace);
                    XNamespace ns = "http://schemas.microsoft.com/appx/appinstaller/2017/2";

                    var idElement = manifest.Root?.Element(ns + "MainBundle");
                    idElement?.SetAttributeValue("Publisher", publisher);
                }

                using (var fs = File.Create(file))
                {
                    manifest.Save(fs);
                }
            }
        }
        async Task SubmitInternal(HashMode hashMode, string name, string description, string descriptionUrl, IList <string> files)
        {
            logger.LogInformation("Signing NuGetKeyVaultSignTool job {0} with {1} files", name, files.Count());

            var args = new SignArgs
            {
                HashAlgorithm     = HashAlgorithmName.SHA256,
                TimestampUrl      = keyVaultService.CertificateInfo.TimestampUrl,
                PublicCertificate = await keyVaultService.GetCertificateAsync(),
                Rsa = await keyVaultService.ToRSA()
            };

            try
            {
                var tasks = files.Select(file =>
                {
                    telemetryLogger.OnSignFile(file, signToolName);
                    return(Sign(file, args));
                });

                await Task.WhenAll(tasks);
            }
            finally
            {
                args.Rsa?.Dispose();
            }
        }
        // Inspired from https://github.com/squaredup/bettersigntool/blob/master/bettersigntool/bettersigntool/SignCommand.cs

        bool Sign(string args, string inputFile, HashMode hashMode, RSA rsaPrivateKey, X509Certificate2 publicCertificate, string timestampUrl)
        {
            var retry   = TimeSpan.FromSeconds(5);
            var attempt = 1;

            do
            {
                if (attempt > 1)
                {
                    logger.LogInformation($"Performing attempt #{attempt} of 3 attempts after {retry.TotalSeconds}s");
                    Thread.Sleep(retry);
                }

                if (RunSignTool(args, inputFile, hashMode, rsaPrivateKey, publicCertificate, timestampUrl))
                {
                    logger.LogInformation($"Signed successfully");
                    return(true);
                }

                attempt++;

                retry = TimeSpan.FromSeconds(Math.Pow(retry.TotalSeconds, 1.5));
            } while (attempt <= 3);

            logger.LogError($"Failed to sign. Attempts exceeded");

            return(false);
        }
コード例 #5
0
        /// <summary>
        /// Verifies the hash.
        /// </summary>
        /// <param name="mode">The mode.</param>
        /// <param name="input">The input to check.</param>
        /// <param name="salt">The salt.</param>
        /// <param name="hash">The hash to compare.</param>
        /// <returns>Compare result of Hash.</returns>
        public static bool VerifyHash(HashMode mode, string input, string salt, string hash)
        {
            string         hashOfInput = CreateHash(mode, input, salt);
            StringComparer comparer    = StringComparer.OrdinalIgnoreCase;

            return(0 == comparer.Compare(hashOfInput, hash));
        }
コード例 #6
0
        public static string FindHash(string hash, HashMode mode)
        {
            var str = String.Empty;

            switch (mode)
            {
            case HashMode.MD5:
                while (MD5_Hash(str) != hash)
                {
                    str = str.GetNext(PasswordCharacters.Visible);
                }
                break;

            case HashMode.SHA1:
                while (SHA1_Hash(str) != hash)
                {
                    str = str.GetNext(PasswordCharacters.Visible);
                }
                break;

            case HashMode.SHA2:
                while (SHA2_Hash(str) != hash)
                {
                    str = str.GetNext(PasswordCharacters.Visible);
                }
                break;
            }
            return(str);
        }
コード例 #7
0
        async Task SubmitInternal(HashMode hashMode, string name, string description, string descriptionUrl, IList <string> files)
        {
            logger.LogInformation("Signing OpenVsixSignTool job {0} with {1} files", name, files.Count());

            // Dual isn't supported, use sha256
            var alg = hashMode == HashMode.Sha1 ? HashAlgorithmName.SHA1 : HashAlgorithmName.SHA256;

            var config = new RsaSignConfigurationSet
            {
                FileDigestAlgorithm = alg,
                PkcsDigestAlgorithm = alg,
                SigningCertificate  = await keyVaultService.GetCertificateAsync(),
                Rsa = await keyVaultService.ToRSA()
            };

            try
            {
                var tasks = files.Select(file =>
                {
                    telemetryLogger.OnSignFile(file, signToolName);
                    return(Sign(file, config, keyVaultService.CertificateInfo.TimestampUrl, alg));
                });

                await Task.WhenAll(tasks);
            }
            finally
            {
                config.Rsa?.Dispose();
            }
        }
コード例 #8
0
ファイル: JEMMD5.cs プロジェクト: TylkoDemon/SMC
        /// <summary>
        /// Calculates MD5 hash.
        /// </summary>
        /// <param name="stringToHash">String to hash.</param>
        /// <param name="mode">Mode of hash.</param>
        /// <param name="lowCase"></param>
        /// <returns>Generate string in low case?</returns>
        public static string Hash(string stringToHash, HashMode mode = HashMode.PerChar, bool lowCase = true)
        {
            var format = lowCase ? "x2" : "X2";

            switch (mode)
            {
            case HashMode.PerChar:
            {
                var md5        = MD5.Create();
                var inputBytes = Encoding.ASCII.GetBytes(stringToHash);
                var hash       = md5.ComputeHash(inputBytes);
                var sb         = new StringBuilder();
                foreach (var t in hash)
                {
                    sb.Append(t.ToString(format));
                }

                return(sb.ToString());
            }

            case HashMode.FromByte:
            {
                var    bytes = Encoding.ASCII.GetBytes(stringToHash);
                string hash;

                using (var md5 = MD5.Create())
                    hash = string.Concat(md5.ComputeHash(bytes).Select(x => x.ToString(format)));

                return(hash);
            }

            default:
                throw new ArgumentOutOfRangeException(nameof(mode), mode, null);
            }
        }
コード例 #9
0
        public async Task Submit(HashMode hashMode, string name, string description, string descriptionUrl, IList <string> files)
        {
            // split by code sign service and fallback to default

            var grouped = (from kvp in codeSignServices
                           join file in files on kvp.Key equals Path.GetExtension(file).ToLowerInvariant()
                           group file by kvp.Value into g
                           select g).ToList();

            // get all files and exclude existing;

            // This is to catch PE files that don't have the correct extension set
            var defaultFiles = files.Except(grouped.SelectMany(g => g))
                               .Where(IsPeFile)
                               .Select(f => new { defaultCodeSignService, f })
                               .GroupBy(a => a.defaultCodeSignService, k => k.f)
                               .SingleOrDefault();      // one group here

            if (defaultFiles != null)
            {
                grouped.Add(defaultFiles);
            }


            await Task.WhenAll(grouped.Select(g => g.Key.Submit(hashMode, name, description, descriptionUrl, g.ToList())));
        }
 /// <summary>
 /// Initialize method implementation
 /// </summary>
 public override void Initialize(BaseProviderParams externalsystem)
 {
     try
     {
         if (!_isinitialized)
         {
             if (externalsystem is OTPProviderParams)
             {
                 OTPProviderParams param = externalsystem as OTPProviderParams;
                 TOTPShadows     = param.TOTPShadows;
                 Algorithm       = param.Algorithm;
                 Enabled         = param.Enabled;
                 WizardEnabled   = param.EnrollWizard;
                 ForceEnrollment = param.ForceWizard;
                 PinRequired     = param.PinRequired;
                 _isinitialized  = true;
                 return;
             }
             else
             {
                 throw new InvalidCastException("Invalid OTP Provider !");
             }
         }
     }
     catch (Exception ex)
     {
         this.Enabled = false;
         throw ex;
     }
 }
コード例 #11
0
        public static void SignFile(string path, HashMode hashMode, RSA rsaPrivateKey, X509Certificate2 publicCertificate, string timestampUrl)
        {
            var useSha256 = hashMode == HashMode.Sha256;

            try
            {
                XmlDocument manifestDom = new XmlDocument();
                manifestDom.PreserveWhitespace = true;
                manifestDom.Load(path);
                SignedCmiManifest2 signedCmiManifest2 = new SignedCmiManifest2(manifestDom, useSha256);
                CmiManifestSigner2 signer             = !useSha256 || !(rsaPrivateKey is RSACryptoServiceProvider) ? new CmiManifestSigner2((AsymmetricAlgorithm)rsaPrivateKey, publicCertificate, useSha256) : new CmiManifestSigner2((AsymmetricAlgorithm)SignedCmiManifest2.GetFixedRSACryptoServiceProvider(rsaPrivateKey as RSACryptoServiceProvider, useSha256), publicCertificate, useSha256);
                if (timestampUrl == null)
                {
                    signedCmiManifest2.Sign(signer);
                }
                else
                {
                    signedCmiManifest2.Sign(signer, timestampUrl);
                }
                manifestDom.Save(path);
            }
            catch (Exception ex)
            {
                switch (Marshal.GetHRForException(ex))
                {
                case -2147012889:
                case -2147012867:
                    throw new ApplicationException("SecurityUtil.TimestampUrlNotFound", ex);

                default:
                    throw new ApplicationException(ex.Message, ex);
                }
            }
        }
コード例 #12
0
        void SubmitInternal(HashMode hashMode, string name, string description, string descriptionUrl, IList <string> files)
        {
            logger.LogInformation("Signing SignTool job {0} with {1} files", name, files.Count());

            var descArgsList = new List <string>();

            if (!string.IsNullOrWhiteSpace(description))
            {
                if (description.Contains("\""))
                {
                    throw new ArgumentException(nameof(description));
                }

                descArgsList.Add($@"-d ""{description}""");
            }
            if (!string.IsNullOrWhiteSpace(descriptionUrl))
            {
                if (descriptionUrl.Contains("\""))
                {
                    throw new ArgumentException(nameof(descriptionUrl));
                }

                descArgsList.Add($@"-du ""{descriptionUrl}""");
            }

            var    descArgs            = string.Join(" ", descArgsList);
            string keyVaultAccessToken = null;

            keyVaultAccessToken = keyVaultService.GetAccessTokenAsync().Result;

            // loop through all of the files here, looking for appx/eappx
            // mark each as being signed and strip appx
            Parallel.ForEach(files, (file, state) =>
            {
                telemetryLogger.OnSignFile(file, signToolName);

                // check to see if it's an appx and strip it first
                var ext = Path.GetExtension(file).ToLowerInvariant();
                if (".appx".Equals(ext, StringComparison.OrdinalIgnoreCase) || ".eappx".Equals(ext, StringComparison.OrdinalIgnoreCase))
                {
                    StripAppx(file);
                }
            });

            // generate a file list for sining
            using (var fileList = new TemporaryFile())
            {
                // generate a file of files
                File.WriteAllLines(fileList.FileName, files);

                var args = $@"sign -ifl ""{fileList.FileName}"" -v -tr {keyVaultService.CertificateInfo.TimestampUrl} -fd sha256 -td sha256 {descArgs} -kvu {keyVaultService.CertificateInfo.KeyVaultUrl} -kvc {keyVaultService.CertificateInfo.CertificateName} -kva {keyVaultAccessToken}";

                if (!Sign(args))
                {
                    throw new Exception($"Could not append sign one of \n{string.Join("\n", files)}");
                }
            }
        }
コード例 #13
0
ファイル: HashedFile.cs プロジェクト: kaosborn/Filebert
 private HashedFile(string name, byte[] storedHash, HashMode mode, byte[] actualHash = null)
 {
     this.storedHash = storedHash;
     this.actualHash = actualHash;
     this.FileName   = name;
     this.IsMatch    = null;
     this.IsFound    = null;
     this.IsRelative = !Path.IsPathRooted(name);
     this.Mode       = mode;
 }
コード例 #14
0
        public Task Submit(HashMode hashMode, string name, string description, string descriptionUrl, IList <string> files, string filter)
        {
            // Explicitly put this on a thread because Parallel.ForEach blocks
            if (hashMode == HashMode.Sha1 || hashMode == HashMode.Dual)
            {
                throw new ArgumentOutOfRangeException(nameof(hashMode), "Only Sha256 is supported");
            }

            return(Task.Run(() => SubmitInternal(hashMode, name, description, descriptionUrl, files)));
        }
コード例 #15
0
        void SubmitInternal(HashMode hashMode, string name, string description, string descriptionUrl, IList <string> files)
        {
            logger.LogInformation("Signing SignTool job {0} with {1} files", name, files.Count());

            var descArgsList = new List <string>();

            if (!string.IsNullOrWhiteSpace(description))
            {
                if (description.Contains("\""))
                {
                    throw new ArgumentException(nameof(description));
                }

                descArgsList.Add($@"/d ""{description}""");
            }
            if (!string.IsNullOrWhiteSpace(descriptionUrl))
            {
                if (descriptionUrl.Contains("\""))
                {
                    throw new ArgumentException(nameof(descriptionUrl));
                }

                descArgsList.Add($@"/du ""{descriptionUrl}""");
            }

            var descArgs = string.Join(" ", descArgsList);


            Parallel.ForEach(files, options, (file, state) =>
            {
                string args;
                if (hashMode == HashMode.Dual)
                {
                    // Sign it with sha1

                    args = $@"sign /t {timeStampUrl} {descArgs} /sha1 {thumbprint} ""{file}""";

                    if (!Sign(args))
                    {
                        throw new Exception($"Could not sign {file}");
                    }
                }

                var appendParam = hashMode == HashMode.Dual ? "/as" : string.Empty;

                args = $@"sign /tr {timeStampUrl} {appendParam} /fd sha256 /td sha256 {descArgs} /sha1 {thumbprint} ""{file}""";
                // Append a sha256 signature
                if (!Sign(args))
                {
                    throw new Exception($"Could not append sign {file}");
                }
            });
        }
コード例 #16
0
 public override bool Equals(object obj)
 {
     HashMode paramobj = HashMode.SHA1;
     if (obj is MMCTOTPHashModeItem)
         paramobj = ((MMCTOTPHashModeItem)obj).ID;
     else
         return false;
     if (paramobj == this.ID)
         return true;
     else
         return false;
 }
コード例 #17
0
        void SubmitInternal(HashMode hashMode, string name, string description, string descriptionUrl, IList <string> files)
        {
            logger.LogInformation("Signing SignTool job {0} with {1} files", name, files.Count());

            var descArgsList = new List <string>();

            if (!string.IsNullOrWhiteSpace(description))
            {
                if (description.Contains("\""))
                {
                    throw new ArgumentException(nameof(description));
                }

                descArgsList.Add($@"-d ""{description}""");
            }
            if (!string.IsNullOrWhiteSpace(descriptionUrl))
            {
                if (descriptionUrl.Contains("\""))
                {
                    throw new ArgumentException(nameof(descriptionUrl));
                }

                descArgsList.Add($@"-du ""{descriptionUrl}""");
            }

            var    descArgs            = string.Join(" ", descArgsList);
            string keyVaultAccessToken = null;

            var keyVaultService = contextAccessor.HttpContext.RequestServices.GetService <IKeyVaultService>();

            keyVaultAccessToken = keyVaultService.GetAccessTokenAsync().Result;

            Parallel.ForEach(files, options, (file, state) =>
            {
                // check to see if it's an appx and strip it first
                var ext = Path.GetExtension(file).ToLowerInvariant();
                if (".appx".Equals(ext, StringComparison.OrdinalIgnoreCase) || ".eappx".Equals(ext, StringComparison.OrdinalIgnoreCase))
                {
                    StripAppx(file);
                }

                string args;

                args = $@"sign ""{file}"" -tr {keyVaultService.CertificateInfo.TimestampUrl} -fd sha256 -td sha256 {descArgs} -kvu {keyVaultService.CertificateInfo.KeyVaultUrl} -kvc {keyVaultService.CertificateInfo.CertificateName} -kva {keyVaultAccessToken}";

                if (!Sign(args))
                {
                    throw new Exception($"Could not append sign {file}");
                }
            });
        }
コード例 #18
0
        /// <summary>
        /// Creates the hash.
        /// </summary>
        /// <param name="mode">The mode.</param>
        /// <param name="stringToHash">The string to hash.</param>
        /// <returns>
        /// String as Hash.
        /// </returns>
        public static string CreateHash(HashMode mode, string stringToHash)
        {
            var hashAlgorithm = CreateHashAlgorithm(mode);

            byte[]        data    = hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(stringToHash));
            StringBuilder builder = new StringBuilder();

            for (int i = 0; i < data.Length; i++)
            {
                builder.Append(data[i].ToString("x2"));
            }

            return(builder.ToString());
        }
コード例 #19
0
ファイル: HasherBase.cs プロジェクト: dansam100/ProgHasher
        /// <summary>
        /// Start hashing based on the given requirements
        /// </summary>
        public void BeginHash()
        {
            mode = HashMode.Hash;

            if (brain.HasOldValidCache("FoundList", Wildcard.Value))
            {
                this.results = SearchBrain.List.LoadPriorCachedList("FoundList", Wildcard.Value);
                this.results.ItemNotFound += new HashItemSearchHandler(OnItemNotFound);
                this.PerformCacheAnalysis  = true;
                this.Results.HasChanged    = true;
            }
            runner.RunWorkerAsync(this);
            hashTimer.BeginTimer();
        }
コード例 #20
0
        private static HashAlgorithm CreateHashAlgorithm(HashMode mode)
        {
            switch (mode)
            {
            case HashMode.MD5:
                return(new MD5CryptoServiceProvider());

            case HashMode.SHA256:
                return(new SHA256Managed());

            default:
                goto case HashMode.SHA256;
            }
        }
コード例 #21
0
        internal static ulong GetStableHash(this string str, HashMode hashMode)
        {
            switch (hashMode)
            {
            case HashMode.Hash16:
                return(GetStableHash16(str));

            case HashMode.Hash32:
                return(GetStableHash32(str));

            case HashMode.Hash64:
                return(GetStableHash64(str));
            }
            return(0);
        }
コード例 #22
0
        bool RunSignTool(string args, string inputFile, HashMode hashMode, RSA rsaPrivateKey, X509Certificate2 publicCertificate, string timestampUrl)
        {
            // Append a sha256 signature
            using (var signtool = new Process
            {
                StartInfo =
                {
                    FileName               = magetoolPath,
                    UseShellExecute        = false,
                    RedirectStandardError  = false,
                    RedirectStandardOutput = false,
                    Arguments              = args
                }
            })
            {
                logger.LogInformation("Signing {fileName}", signtool.StartInfo.FileName);
                signtool.Start();
                if (!signtool.WaitForExit(30 * 1000))
                {
                    logger.LogError("Error: Mage took too long to respond {exitCode}", signtool.ExitCode);
                    try
                    {
                        signtool.Kill();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Mage timed out and could not be killed", ex);
                    }

                    logger.LogError("Error: Mage took too long to respond {exitCode}", signtool.ExitCode);
                    throw new Exception($"Mage took too long to respond");
                }

                if (signtool.ExitCode == 0)
                {
                    // Now add the signature
                    ManifestSigner.SignFile(inputFile, hashMode, rsaPrivateKey, publicCertificate, timestampUrl);

                    return(true);
                }

                logger.LogError("Error: Signtool returned {exitCode}", signtool.ExitCode);

                return(false);
            }
        }
コード例 #23
0
        /// <summary>
        /// Creates the hash.
        /// </summary>
        /// <param name="mode">The mode.</param>
        /// <param name="inputBytes">The input in bytes.</param>
        /// <param name="saltBytes">The salt in bytes.</param>
        /// <returns>String as Hash.</returns>
        /// <remarks>LM ANWAR, 6/2/2013.</remarks>
        public static string CreateHash(HashMode mode, byte[] inputBytes, byte[] saltBytes)
        {
            byte[] allBytes = new byte[saltBytes.Length + inputBytes.Length];

            Buffer.BlockCopy(saltBytes, 0, allBytes, 0, saltBytes.Length);
            Buffer.BlockCopy(inputBytes, 0, allBytes, saltBytes.Length, inputBytes.Length);

            var hashAlgorithm = CreateHashAlgorithm(mode);

            byte[]        data    = hashAlgorithm.ComputeHash(allBytes);
            StringBuilder builder = new StringBuilder();

            for (int i = 0; i < data.Length; i++)
            {
                builder.Append(data[i].ToString("x2"));
            }

            return(builder.ToString());
        }
コード例 #24
0
        void SubmitInternal(HashMode hashMode, string name, string description, string descriptionUrl, IList <string> files)
        {
            logger.LogInformation("Signing NuGetKeyVaultSignTool job {0} with {1} files", name, files.Count());

            var keyVaultAccessToken = keyVaultService.GetAccessTokenAsync().Result;

            var args = $@"-f -tr {keyVaultService.CertificateInfo.TimestampUrl} -kvu {keyVaultService.CertificateInfo.KeyVaultUrl} -kvc {keyVaultService.CertificateInfo.CertificateName} -kva {keyVaultAccessToken}";

            Parallel.ForEach(files, options, (file, state) =>
            {
                telemetryLogger.OnSignFile(file, signToolName);
                var fileArgs = $@"sign ""{file}"" {args}";

                if (!Sign(fileArgs))
                {
                    throw new Exception($"Could not sign {file}");
                }
            });
        }
コード例 #25
0
        void SubmitInternal(HashMode hashMode, string name, string description, string descriptionUrl, IList <string> files)
        {
            logger.LogInformation("Signing SignTool job {0} with {1} files", name, files.Count());

            var certificate = keyVaultService.GetCertificateAsync().Result;

            using var rsa    = keyVaultService.ToRSA().Result;
            using var signer = new AuthenticodeKeyVaultSigner(rsa, certificate, HashAlgorithmName.SHA256, new TimeStampConfiguration(keyVaultService.CertificateInfo.TimestampUrl, HashAlgorithmName.SHA256, TimeStampType.RFC3161));
            // loop through all of the files here, looking for appx/eappx
            // mark each as being signed and strip appx
            Parallel.ForEach(files, (file, state) =>
            {
                telemetryLogger.OnSignFile(file, signToolName);

                if (!Sign(signer, file, description, descriptionUrl))
                {
                    throw new Exception($"Could not append sign {file}");
                }
            });
        }
コード例 #26
0
        public async Task <IActionResult> SignSingleFile(IFormFile source, HashMode hashMode, string name, string description, string descriptionUrl)
        {
            var dataDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            Directory.CreateDirectory(dataDir);
            var fileName = Path.Combine(dataDir, source.FileName);

            try
            {
                if (source.Length > 0)
                {
                    using (var fs = new FileStream(fileName, FileMode.Create))
                    {
                        await source.CopyToAsync(fs);
                    }
                }

                // Do work and then load the file into memory so we can delete it before the response is complete
                var fi = new FileInfo(fileName);

                await codeSignService.Submit(hashMode, name, description, descriptionUrl, new[] { fileName });


                byte[] buffer;
                using (var ms = new MemoryStream(new byte[fi.Length]))
                {
                    using (var fs = fi.OpenRead())
                    {
                        await fs.CopyToAsync(ms);
                    }

                    buffer = ms.ToArray();
                }

                return(File(buffer, "application/octet-stream", source.FileName));
            }
            finally
            {
                Directory.Delete(dataDir, true);
            }
        }
コード例 #27
0
        public override bool Equals(object obj)
        {
            HashMode paramobj = HashMode.SHA1;

            if (obj is MMCTOTPHashModeItem)
            {
                paramobj = ((MMCTOTPHashModeItem)obj).ID;
            }
            else
            {
                return(false);
            }
            if (paramobj == this.ID)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #28
0
        /// -------------------------------------------------------------------------------------------------
        /// <summary>
        /// Creates the hash.
        /// </summary>
        /// <remarks>
        /// LM ANWAR, 6/2/2013.
        /// </remarks>
        /// <param name="mode">
        /// The mode.
        /// </param>
        /// <param name="stringToHash">
        /// The string to hash.
        /// </param>
        /// <param name="salt">
        /// The salt.
        /// </param>
        /// <returns>
        /// String as Hash.
        /// </returns>
        /// -------------------------------------------------------------------------------------------------
        public static string CreateHash(HashMode mode, string stringToHash, string salt)
        {
            byte[] inputBytes = Encoding.UTF8.GetBytes(stringToHash);
            byte[] saltBytes  = Convert.FromBase64String(salt);
            byte[] allBytes   = new byte[saltBytes.Length + inputBytes.Length];

            Buffer.BlockCopy(saltBytes, 0, allBytes, 0, saltBytes.Length);
            Buffer.BlockCopy(inputBytes, 0, allBytes, saltBytes.Length, inputBytes.Length);

            var hashAlgorithm = CreateHashAlgorithm(mode);

            byte[]        data    = hashAlgorithm.ComputeHash(allBytes);
            StringBuilder builder = new StringBuilder();

            for (int i = 0; i < data.Length; i++)
            {
                builder.Append(data[i].ToString("x2"));
            }

            return(builder.ToString());
        }
コード例 #29
0
        void SubmitInternal(HashMode hashMode, string name, string description, string descriptionUrl, IList <string> files)
        {
            logger.LogInformation("Signing OpenVsixSignTool job {0} with {1} files", name, files.Count());

            // Dual isn't supported, use sha256
            var alg = hashMode == HashMode.Sha1 ? "sha1" : "sha256";

            var keyVaultService     = contextAccessor.HttpContext.RequestServices.GetService <IKeyVaultService>();
            var keyVaultAccessToken = keyVaultService.GetAccessTokenAsync().Result;

            var args = $@"sign --timestamp {keyVaultService.CertificateInfo.TimestampUrl} -ta {alg} -fd {alg} -kvu {keyVaultService.CertificateInfo.KeyVaultUrl} -kvc {keyVaultService.CertificateInfo.CertificateName} -kva {keyVaultAccessToken}";


            Parallel.ForEach(files, options, (file, state) =>
            {
                var fileArgs = $@"{args} ""{file}""";

                if (!Sign(fileArgs))
                {
                    throw new Exception($"Could not sign {file}");
                }
            });
        }
コード例 #30
0
ファイル: JEMMD5.cs プロジェクト: TylkoDemon/SMC
        /// <summary>
        /// Calculates MD5 hash.
        /// </summary>
        /// <param name="stream">File stream to hash.</param>
        /// <param name="mode">Mode of hash.</param>
        /// <param name="lowCase"></param>
        /// <returns>Generate string in low case?</returns>
        public static string Hash(FileStream stream, HashMode mode = HashMode.PerChar, bool lowCase = true)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }
            var format = lowCase ? "x2" : "X2";

            switch (mode)
            {
            case HashMode.PerChar:
            {
                var md5  = MD5.Create();
                var hash = md5.ComputeHash(stream);
                var sb   = new StringBuilder();
                foreach (var t in hash)
                {
                    sb.Append(t.ToString(format));
                }

                return(sb.ToString());
            }

            case HashMode.FromByte:
            {
                string hash;

                using (var md5 = MD5.Create())
                    hash = string.Concat(md5.ComputeHash(stream).Select(x => x.ToString(format)));

                return(hash);
            }

            default:
                throw new ArgumentOutOfRangeException(nameof(mode), mode, null);
            }
        }
コード例 #31
0
        public static String CalculateHash(String SourceString, String HashKey = null, HashMode encmode = HashMode.MD5)
        {
            Byte[] InputBytes = Encoding.UTF8.GetBytes(SourceString);
            switch (encmode)
            {
                case HashMode.MD5:
                    {
                        MD5CryptoServiceProvider s = new MD5CryptoServiceProvider();
                        byte[] ResultBytes = s.ComputeHash(InputBytes);
                        StringBuilder ret = new StringBuilder();
                        foreach (byte result in ResultBytes)
                            ret.Append(result.ToString("x2").ToLower());
                        return ret.ToString();
                    }
                case HashMode.SHA1:
                    {
                        SHA1CryptoServiceProvider s = new SHA1CryptoServiceProvider();
                        byte[] result = s.ComputeHash(InputBytes);
                        String ret = BitConverter.ToString(result);
                        ret = ret.Replace("-", "");
                        return ret;
                    }
                case HashMode.HAMC:
                    {
                        Byte[] SourceStringByte = Encoding.ASCII.GetBytes(SourceString);
                        Byte[] HashKeyByte = Encoding.ASCII.GetBytes(HashKey);

                        HMACMD5 hmacMD5 = new HMACMD5(HashKeyByte);
                        Byte[] computedHash = hmacMD5.ComputeHash(SourceStringByte);

                        StringBuilder s = new StringBuilder(2 * computedHash.Length);

                        foreach (byte t in computedHash)
                            s.AppendFormat("{0:x2}", t);

                        return s.ToString();
                    }
                default:
                    throw new NotSupportedException();
            }
        }
コード例 #32
0
        public static String CalculateHash(String SourceString, HashMode encmode)
        {
            Byte[] InputBytes = Encoding.UTF8.GetBytes(SourceString);
            switch (encmode)
            {
                case HashMode.MD5:
                    {
                        MD5CryptoServiceProvider s = new MD5CryptoServiceProvider();
                        byte[] ResultBytes = s.ComputeHash(InputBytes);
                        StringBuilder ret = new StringBuilder();
                        foreach (byte result in ResultBytes)
                            ret.Append(result.ToString("x2").ToLower());
                        return ret.ToString();
                    }
                case HashMode.SHA1:
                    {
                        SHA1CryptoServiceProvider s = new SHA1CryptoServiceProvider();
                        byte[] result = s.ComputeHash(InputBytes);
                        String ret = BitConverter.ToString(result);
                        ret = ret.Replace("-", "");
                        return ret;
                    }
            }

            return "";
        }