private string CreatePasswordHash(string password, string salt) { var saltPepper = string.Concat(salt, this.pepper); var passwordHash = CryptoHashProvider.ComputeHash(password, saltPepper); return(passwordHash); }
/// <summary> /// We want to base the lock name off of the full path of the package, however, the Mutex looks for files on disk if a path is given. /// Additionally, it also fails if the string is longer than 256 characters. Therefore we obtain a base-64 encoded hash of the path. /// </summary> /// <seealso cref="http://social.msdn.microsoft.com/forums/en-us/clr/thread/D0B3BF82-4D23-47C8-8706-CC847157AC81"/> private static string GenerateUniqueToken(IPackageManager packageManager, string packageId, SemanticVersion version) { var packagePath = packageManager.FileSystem.GetFullPath(packageManager.PathResolver.GetPackageFileName(packageId, version)); var pathBytes = Encoding.UTF8.GetBytes(packagePath); var hashProvider = new CryptoHashProvider("SHA256"); return(Convert.ToBase64String(hashProvider.CalculateHash(pathBytes)).ToUpperInvariant()); }
public static string GenerateUniqueToken(string caseInsensitiveKey) { // SHA256 is case sensitive; given that our key is case insensitive, we upper case it var pathBytes = Encoding.UTF8.GetBytes(caseInsensitiveKey.ToUpperInvariant()); var hashProvider = new CryptoHashProvider("SHA256"); return(Convert.ToBase64String(hashProvider.CalculateHash(pathBytes)).ToUpperInvariant()); }
/// <summary> /// We want to base the lock name off of the full path of the package, however, the Mutex looks for files on disk if a path is given. /// Additionally, it also fails if the string is longer than 256 characters. Therefore we obtain a base-64 encoded hash of the path. /// </summary> /// <seealso cref="http://social.msdn.microsoft.com/forums/en-us/clr/thread/D0B3BF82-4D23-47C8-8706-CC847157AC81"/> private static string GenerateUniqueToken(IPackageManager packageManager, string packageId, SemanticVersion version) { var packagePath = packageManager.FileSystem.GetFullPath(packageManager.PathResolver.GetPackageFileName(packageId, version)); var pathBytes = Encoding.UTF8.GetBytes(packagePath); var hashProvider = new CryptoHashProvider("SHA256"); return Convert.ToBase64String(hashProvider.CalculateHash(pathBytes)).ToUpperInvariant(); }
public Task <string> GetPackageHashAsync(string hashAlgorithm, CancellationToken cancellationToken) { _sourceStream.Value.Seek(0, SeekOrigin.Begin); var bytes = new CryptoHashProvider(hashAlgorithm).CalculateHash(_sourceStream.Value); var packageHash = Convert.ToBase64String(bytes); return(Task.FromResult(packageHash)); }
public override void Context() { base.Context(); Provider = new CryptoHashProvider(FileSystem.Object, _hashAlgorithm.Object); FileSystem.Setup(x => x.file_exists(It.IsAny <string>())).Returns(true); FileSystem.Setup(x => x.read_file_bytes(filePath)).Returns(byteArray); _hashAlgorithm.Setup(x => x.ComputeHash(byteArray)).Throws <IOException>(); //IO.IO_FileTooLong2GB (over Int32.MaxValue) }
public DefaultServiceResolver(string packagePath, NameValueCollection settings) { _hashProvider = new CryptoHashProvider(Core.Constants.HashAlgorithm); _settingsProvider = new WebConfigSettingsProvider(settings); _packageRepository = new ServerPackageRepository(packagePath, _hashProvider, _settingsProvider, new TraceLogger()); _packageAuthenticationService = new PackageAuthenticationService(settings); }
private static void VerifyPackagesIntegrity(string folderRoot, string fileName) { var sb = new StringBuilder(); if (!Directory.Exists(folderRoot)) { Console.WriteLine($"Could not find folder: {folderRoot}"); return; } var packageInfos = LocalFolderUtility.GetPackagesV3(folderRoot, NullLogger.Instance); var numIncorrectHash = 0; foreach (var packageInfo in packageInfos) { if (File.Exists(packageInfo.Path)) { var packageHash = string.Empty; using (var stream = new FileStream( packageInfo.Path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true)) { var bytes = new CryptoHashProvider("SHA512").CalculateHash(stream); packageHash = Convert.ToBase64String(bytes); } var sha512File = packageInfo.Path + ".sha512"; if (File.Exists(sha512File)) { var existingHash = File.ReadAllText(sha512File); var flag = string.Equals(existingHash, packageHash); if (!flag) { numIncorrectHash++; } sb.AppendLine(string.Join(',', packageInfo.Identity.Id, packageInfo.Identity.Version.ToNormalizedString(), existingHash, packageHash, flag)); } } } Console.WriteLine($"Total number of incorrect hashed packages in {folderRoot}: {numIncorrectHash}"); File.WriteAllText(fileName, sb.ToString()); }
public void CryptoHashProviderAllowsSHA512orSHA256(string hashAlgorithm, string expectedHash) { // Arrange var testBytes = Encoding.UTF8.GetBytes("There is no butter knife"); var hashProvider = new CryptoHashProvider(hashAlgorithm); // Act var result = Convert.ToBase64String(hashProvider.CalculateHash(testBytes)); // Assert Assert.Equal(expectedHash, result); }
private static string CalculatePackageHash(string filePath, string hashAlgorithm) { string expectedPackageHash; using (var stream = File.OpenRead(filePath)) { var bytes = new CryptoHashProvider(hashAlgorithm).CalculateHash(stream); expectedPackageHash = Convert.ToBase64String(bytes); } return(expectedPackageHash); }
public void CryptoHashProviderReturnsTrueIfHashAreEqual() { // Arrange byte[] testBytes = Encoding.UTF8.GetBytes("There is no butter knife"); string expectedHash = "xy/brd+/mxheBbyBL7i8Oyy62P2ZRteaIkfc4yA8ncH1MYkbDo+XwBcZsOBY2YeaOucrdLJj5odPvozD430w2g=="; IHashProvider hashProvider = new CryptoHashProvider(); // Act bool result = hashProvider.VerifyHash(testBytes, Convert.FromBase64String(expectedHash)); // Assert Assert.True(result); }
public void DefaultCryptoHashProviderUsesSHA512() { // Arrange var testBytes = Encoding.UTF8.GetBytes("There is no butter knife"); var expectedHash = "xy/brd+/mxheBbyBL7i8Oyy62P2ZRteaIkfc4yA8ncH1MYkbDo+XwBcZsOBY2YeaOucrdLJj5odPvozD430w2g=="; CryptoHashProvider hashProvider = new CryptoHashProvider(); // Act byte[] actualHash = hashProvider.CalculateHash(testBytes); // Assert Assert.Equal(actualHash, Convert.FromBase64String(expectedHash)); }
public void CryptoHashProviderReturnsTrueIfHashAreEqual() { // Arrange var testBytes = Encoding.UTF8.GetBytes("There is no butter knife"); var expectedHash = "xy/brd+/mxheBbyBL7i8Oyy62P2ZRteaIkfc4yA8ncH1MYkbDo+XwBcZsOBY2YeaOucrdLJj5odPvozD430w2g=="; CryptoHashProvider hashProvider = new CryptoHashProvider(); // Act bool result = hashProvider.VerifyHash(testBytes, Convert.FromBase64String(expectedHash)); // Assert Assert.True(result); }
public void CryptoHashProviderReturnsFalseIfHashValuesAreUnequal() { // Arrange var testBytes = Encoding.UTF8.GetBytes("There is no butter knife"); var badBytes = Encoding.UTF8.GetBytes("this is a bad input"); CryptoHashProvider hashProvider = new CryptoHashProvider(); // Act byte[] testHash = hashProvider.CalculateHash(testBytes); byte[] badHash = hashProvider.CalculateHash(badBytes); bool result = hashProvider.VerifyHash(testHash, badHash); // Assert Assert.False(result); }
public void CryptoHashProviderIsThreadSafe() { // Arrange byte[] testBytes = Encoding.UTF8.GetBytes("There is no butter knife"); string expectedHash = "xy/brd+/mxheBbyBL7i8Oyy62P2ZRteaIkfc4yA8ncH1MYkbDo+XwBcZsOBY2YeaOucrdLJj5odPvozD430w2g=="; IHashProvider hashProvider = new CryptoHashProvider(); Parallel.For(0, 10000, ignored => { // Act byte[] actualHash = hashProvider.CalculateHash(testBytes); // Assert Assert.Equal(actualHash, Convert.FromBase64String(expectedHash)); }); }
public void CryptoHashProviderReturnsFalseIfHashValuesAreUnequal() { // Arrange byte[] testBytes = Encoding.UTF8.GetBytes("There is no butter knife"); byte[] badBytes = Encoding.UTF8.GetBytes("this is a bad input"); IHashProvider hashProvider = new CryptoHashProvider(); // Act byte[] testHash = hashProvider.CalculateHash(testBytes); byte[] badHash = hashProvider.CalculateHash(badBytes); bool result = hashProvider.VerifyHash(testHash, badHash); // Assert Assert.False(result); }
/// <summary> /// Asynchronously gets a package hash. /// </summary> /// <param name="hashAlgorithm">The hash algorithm.</param> /// <param name="cancellationToken">A cancellation token.</param> /// <returns>A task that represents the asynchronous operation. /// The task result (<see cref="Task{TResult}.Result" />) returns a <see cref="string" /> /// representing the package hash.</returns> /// <exception cref="ObjectDisposedException">Thrown if this object is disposed.</exception> /// <exception cref="ArgumentException">Thrown if <paramref name="hashAlgorithm" /> /// is either <c>null</c> or empty.</exception> /// <exception cref="OperationCanceledException">Thrown if <paramref name="cancellationToken" /> /// is cancelled.</exception> public Task <string> GetPackageHashAsync(string hashAlgorithm, CancellationToken cancellationToken) { ThrowIfDisposed(); if (string.IsNullOrEmpty(hashAlgorithm)) { throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(hashAlgorithm)); } cancellationToken.ThrowIfCancellationRequested(); using (var stream = GetDestinationStream()) { var bytes = new CryptoHashProvider(hashAlgorithm).CalculateHash(stream); var packageHash = Convert.ToBase64String(bytes); return(Task.FromResult(packageHash)); } }
public void Initialize() { var packagePathResolver = CreatePackagePathResolver(); var fileSystem = new PhysicalFileSystem(PackagePath) { Logger = new NuGetCommonLoggingAdapter() }; var hashProvider = new CryptoHashProvider(PackageHashAlgorithm); CreateDirectories(); InitializeLucene(); PackageIndexer = new PackageIndexer { FileSystem = fileSystem, Provider = Provider, Writer = Provider.IndexWriter }; var repository = new LucenePackageRepository(packagePathResolver, fileSystem) { HashProvider = hashProvider, HashAlgorithmName = PackageHashAlgorithm, DisablePackageHash = DisablePackageHash, IgnorePackageFiles = IgnorePackageFiles, PathResolver = packagePathResolver, Indexer = PackageIndexer, LuceneDataProvider = Provider, LucenePackages = Provider.AsQueryable(() => new LucenePackage(fileSystem)), LucenePackageSource = string.Format("{0} (with Lucene.Net index in {1})", PackagePath, LuceneIndexPath), PackageOverwriteMode = PackageOverwriteMode }; // TODO: circular reference PackageIndexer.PackageRepository = repository; PackageIndexer.Initialize(); repository.Initialize(); Repository = repository; InitializeFileSystemWatcher(fileSystem, repository); }
/// <summary> /// Asynchronously gets a package hash. /// </summary> /// <param name="hashAlgorithm">The hash algorithm.</param> /// <param name="cancellationToken">A cancellation token.</param> /// <returns>A task that represents the asynchronous operation. /// The task result (<see cref="Task{TResult}.Result" />) returns a <see cref="string" /> /// representing the package hash.</returns> /// <exception cref="ObjectDisposedException">Thrown if this object is disposed.</exception> /// <exception cref="ArgumentException">Thrown if <paramref name="hashAlgorithm" /> /// is either <c>null</c> or empty.</exception> /// <exception cref="OperationCanceledException">Thrown if <paramref name="cancellationToken" /> /// is cancelled.</exception> public Task <string> GetPackageHashAsync(string hashAlgorithm, CancellationToken cancellationToken) { ThrowIfDisposed(); if (string.IsNullOrEmpty(hashAlgorithm)) { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, Strings.StringCannotBeNullOrEmpty, nameof(hashAlgorithm)), nameof(hashAlgorithm)); } cancellationToken.ThrowIfCancellationRequested(); _sourceStream.Value.Seek(0, SeekOrigin.Begin); var bytes = new CryptoHashProvider(hashAlgorithm).CalculateHash(_sourceStream.Value); var packageHash = Convert.ToBase64String(bytes); return(Task.FromResult(packageHash)); }
public void Initialize() { var packagePathResolver = CreatePackagePathResolver(); var fileSystem = new PhysicalFileSystem(PackagePath); var hashProvider = new CryptoHashProvider(PackageHashAlgorithm); CreateDirectories(); InitializeLucene(); PackageIndexer = new PackageIndexer { FileSystem = fileSystem, Provider = Provider, Writer = Provider.IndexWriter }; var repository = new LucenePackageRepository(packagePathResolver, fileSystem) { HashProvider = hashProvider, HashAlgorithm = PackageHashAlgorithm, PathResolver = packagePathResolver, Indexer = PackageIndexer, LuceneDataProvider = Provider, LucenePackages = Provider.AsQueryable(() => new LucenePackage(fileSystem)), LucenePackageSource = string.Format("{0} (with Lucene.Net index in {1})", PackagePath, LuceneIndexPath) }; // TODO: circular reference PackageIndexer.PackageRepository = repository; PackageIndexer.Initialize(); repository.Initialize(); Repository = repository; InitializeFileSystemWatcher(fileSystem, repository); }
/// <summary> /// Writes the sha512 package hash file to the package output directory /// </summary> /// <param name="builder">The package builder</param> private void WriteSHA512PackageHash(PackageBuilder builder) { var outputPath = GetOutputPath(builder, false, builder.Version); Directory.CreateDirectory(Path.GetDirectoryName(outputPath)); var sha512OutputPath = Path.Combine(outputPath + ".sha512"); // We must use the Path.GetTempPath() which NuGetFolderPath.Temp uses as a root because writing temp files to the package directory with a guid would break some build tools caching var tempOutputPath = Path.Combine(NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp), Path.GetFileName(sha512OutputPath)); _packArgs.Logger.Log(PackagingLogMessage.CreateMessage(string.Format(CultureInfo.CurrentCulture, Strings.Log_PackageCommandInstallPackageToOutputPath, "SHA512", sha512OutputPath), LogLevel.Minimal)); byte[] sha512hash; var cryptoHashProvider = new CryptoHashProvider("SHA512"); using (var fileStream = new FileStream(outputPath, FileMode.Open, FileAccess.Read)) { sha512hash = cryptoHashProvider.CalculateHash(fileStream); } File.WriteAllText(tempOutputPath, Convert.ToBase64String(sha512hash)); FileUtility.Replace(tempOutputPath, sha512OutputPath); }
public static string GetHash(this IPackage package, CryptoHashProvider hashProvider) { using (Stream stream = package.GetStream()) return(Convert.ToBase64String(hashProvider.CalculateHash(stream))); }
public override void Context() { FileSystem = new DotNetFileSystem(); Provider = new CryptoHashProvider(FileSystem); ContextDirectory = FileSystem.combine_paths(FileSystem.get_directory_name(FileSystem.get_current_assembly_path()), "context"); }
public override void Context() { Provider = Provider = new CryptoHashProvider(FileSystem.Object); }
/// <summary> /// True if the given package matches hash /// </summary> private static bool MatchPackageHash(IPackage package, string hash) { var hashProvider = new CryptoHashProvider("SHA512"); return(package != null && package.GetHash(hashProvider).Equals(hash, StringComparison.OrdinalIgnoreCase)); }
public bool run_action(ChocolateyConfiguration configuration, PackageResult packageResult, CommandNameType command) { var installerRun = false; var packageDirectory = packageResult.InstallLocation; if (packageDirectory.is_equal_to(ApplicationParameters.InstallLocation) || packageDirectory.is_equal_to(ApplicationParameters.PackagesLocation)) { packageResult.Messages.Add( new ResultMessage( ResultType.Error, "Install location is not specific enough, cannot run PowerShell script:{0} Erroneous install location captured as '{1}'".format_with(Environment.NewLine, packageResult.InstallLocation) ) ); return(false); } if (!_fileSystem.directory_exists(packageDirectory)) { packageResult.Messages.Add(new ResultMessage(ResultType.Error, "Package install not found:'{0}'".format_with(packageDirectory))); return(installerRun); } var chocoPowerShellScript = get_script_for_action(packageResult, command); if (!string.IsNullOrEmpty(chocoPowerShellScript)) { var failure = false; ConfigurationBuilder.set_environment_variables(configuration); var package = packageResult.Package; Environment.SetEnvironmentVariable("chocolateyPackageName", package.Id); Environment.SetEnvironmentVariable("packageName", package.Id); Environment.SetEnvironmentVariable("chocolateyPackageVersion", package.Version.to_string()); Environment.SetEnvironmentVariable("packageVersion", package.Version.to_string()); Environment.SetEnvironmentVariable("chocolateyPackageFolder", packageDirectory); Environment.SetEnvironmentVariable("packageFolder", packageDirectory); Environment.SetEnvironmentVariable("installArguments", configuration.InstallArguments); Environment.SetEnvironmentVariable("installerArguments", configuration.InstallArguments); Environment.SetEnvironmentVariable("chocolateyInstallArguments", configuration.InstallArguments); Environment.SetEnvironmentVariable("packageParameters", configuration.PackageParameters); Environment.SetEnvironmentVariable("chocolateyPackageParameters", configuration.PackageParameters); if (configuration.ForceX86) { Environment.SetEnvironmentVariable("chocolateyForceX86", "true"); } if (configuration.OverrideArguments) { Environment.SetEnvironmentVariable("chocolateyInstallOverride", "true"); } if (configuration.NotSilent) { Environment.SetEnvironmentVariable("chocolateyInstallOverride", "true"); } //todo:if (configuration.NoOutput) //{ // Environment.SetEnvironmentVariable("ChocolateyEnvironmentQuiet","true"); //} if (package.IsDownloadCacheAvailable) { foreach (var downloadCache in package.DownloadCache.or_empty_list_if_null()) { var urlKey = CryptoHashProvider.hash_value(downloadCache.OriginalUrl, CryptoHashProviderType.Sha256).Replace("=", string.Empty); Environment.SetEnvironmentVariable("CacheFile_{0}".format_with(urlKey), downloadCache.FileName); Environment.SetEnvironmentVariable("CacheChecksum_{0}".format_with(urlKey), downloadCache.Checksum); Environment.SetEnvironmentVariable("CacheChecksumType_{0}".format_with(urlKey), "sha512"); } } this.Log().Debug(ChocolateyLoggers.Important, "Contents of '{0}':".format_with(chocoPowerShellScript)); string chocoPowerShellScriptContents = _fileSystem.read_file(chocoPowerShellScript); this.Log().Debug(chocoPowerShellScriptContents.escape_curly_braces()); bool shouldRun = !configuration.PromptForConfirmation; if (!shouldRun) { this.Log().Info(ChocolateyLoggers.Important, () => "The package {0} wants to run '{1}'.".format_with(package.Id, _fileSystem.get_file_name(chocoPowerShellScript))); this.Log().Info(ChocolateyLoggers.Important, () => "Note: If you don't run this script, the installation will fail."); this.Log().Info(ChocolateyLoggers.Important, () => @"Note: To confirm automatically next time, use '-y' or consider setting 'allowGlobalConfirmation'. Run 'choco feature -h' for more details."); var selection = InteractivePrompt.prompt_for_confirmation(@"Do you want to run the script?", new[] { "yes", "no", "print" }, defaultChoice: null, requireAnswer: true, allowShortAnswer: true, shortPrompt: true ); if (selection.is_equal_to("print")) { this.Log().Info(ChocolateyLoggers.Important, "------ BEGIN SCRIPT ------"); this.Log().Info(() => "{0}{1}{0}".format_with(Environment.NewLine, chocoPowerShellScriptContents.escape_curly_braces())); this.Log().Info(ChocolateyLoggers.Important, "------- END SCRIPT -------"); selection = InteractivePrompt.prompt_for_confirmation(@"Do you want to run this script?", new[] { "yes", "no" }, defaultChoice: null, requireAnswer: true, allowShortAnswer: true, shortPrompt: true ); } if (selection.is_equal_to("yes")) { shouldRun = true; } if (selection.is_equal_to("no")) { Environment.ExitCode = 1; packageResult.Messages.Add(new ResultMessage(ResultType.Error, "User cancelled powershell portion of installation for '{0}'.{1} Specify -n to skip automated script actions.".format_with(chocoPowerShellScript, Environment.NewLine))); } } if (shouldRun) { installerRun = true; if (configuration.Features.UsePowerShellHost) { add_assembly_resolver(); } var result = new PowerShellExecutionResults { ExitCode = -1 }; try { result = configuration.Features.UsePowerShellHost ? Execute.with_timeout(configuration.CommandExecutionTimeoutSeconds).command(() => run_host(configuration, chocoPowerShellScript), result) : run_external_powershell(configuration, chocoPowerShellScript); } catch (Exception ex) { this.Log().Error(ex.Message.escape_curly_braces()); result.ExitCode = -1; } if (configuration.Features.UsePowerShellHost) { remove_assembly_resolver(); } if (result.StandardErrorWritten && configuration.Features.FailOnStandardError) { failure = true; } else if (result.StandardErrorWritten && result.ExitCode == 0) { this.Log().Warn( () => @"Only an exit code of non-zero will fail the package by default. Set `--failonstderr` if you want error messages to also fail a script. See `choco -h` for details."); } if (result.ExitCode != 0) { Environment.ExitCode = result.ExitCode; packageResult.ExitCode = result.ExitCode; } // 0 - most widely used success exit code // MSI valid exit codes // 1605 - (uninstall) - the product is not found, could have already been uninstalled // 1614 (uninstall) - the product is uninstalled // 1641 - restart initiated // 3010 - restart required var validExitCodes = new List <int> { 0, 1605, 1614, 1641, 3010 }; if (!validExitCodes.Contains(result.ExitCode)) { failure = true; } if (failure) { packageResult.Messages.Add(new ResultMessage(ResultType.Error, "Error while running '{0}'.{1} See log for details.".format_with(chocoPowerShellScript, Environment.NewLine))); } packageResult.Messages.Add(new ResultMessage(ResultType.Note, "Ran '{0}'".format_with(chocoPowerShellScript))); } } return(installerRun); }
public static IServerPackageRepository CreatePackageRepository(string packagePath, ISettingsProvider settingsProvider = null, NuGet.Server.Core.Logging.ILogger logger = null) { var hashProvider = new CryptoHashProvider(Core.Constants.HashAlgorithm); return(new ServerPackageRepository(packagePath, hashProvider, settingsProvider, logger)); }