public IActionResult Index(HashCalculator model) { SetViewBagValues(); if (!ModelState.IsValid) { return(View()); } String selectedValue = model.SelectedAlgorithm; switch (selectedValue) { case "SHA1": model.Result = model.ComputeSHA1Hash(); break; case "SHA256": model.Result = model.ComputeSHA256Hash(); break; case "SHA384": model.Result = model.ComputeSHA384Hash(); break; case "SHA512": model.Result = model.ComputeSHA512Hash(); break; case "MD5": model.Result = model.ComputeMD5Hash(); break; } return(View(model)); }
public async Task <IActionResult> Login([FromBody] TokenRequest request) { var usuarioModel = await _context.UsuarioModel .SingleOrDefaultAsync(m => m.UserName == request.Username); if (usuarioModel == null) { return(BadRequest("Usuario nao encontrado.")); } string senha = HashCalculator.GenerateMD5(request.Password); if (senha == usuarioModel.Senha) { var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("SECRET"))); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: "yourdomain.com", audience: "yourdomain.com", expires: DateTime.Now.AddMinutes(30), signingCredentials: creds); return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) })); } return(BadRequest("Usuario e senha incorretos.")); }
private string GetCacheFileName(string path) { string cacheDir = GetCachePath(); string hashFileName = HashCalculator.CalculateSHA1(path); return(Path.Combine(cacheDir, hashFileName + "." + context.Settings.LanguageId.ToLower() + ".bin")); }
public void IndepedentByRelativePathTest() { var hash1 = HashCalculator.CalculateCheckSum(path); var hash2 = HashCalculator.CalculateCheckSum("../../../../HelpDir1/TestDirectory"); Assert.AreEqual(hash1, hash2); }
public void DependsOnDirNameTest() { var hash1 = HashCalculator.CalculateCheckSum(path); var hash2 = HashCalculator.CalculateCheckSum("../../../../HelpDir4/TestDirectory1"); Assert.AreNotEqual(hash1, hash2); }
public void ParralelingTest() { var hash1 = HashCalculator.CalculateCheckSum(path); var hash2 = HashCalculator.CalculateCheckSumParralel(path); Assert.AreEqual(hash1, hash2); }
internal void LoadModule(string moduleId) { XmlDocument model = new XmlDocument(); string modelDir = moduleId; model.LoadXml(Resources.Load <TextAsset>(modelDir).text); //getting rid of comments string pattern = "(<!--.*?--\\>)"; model.InnerXml = Regex.Replace(model.InnerXml, pattern, string.Empty, RegexOptions.Singleline); string gameHash = HashCalculator.Md5Sum(model.InnerXml); List <Parameter> parameters = XmlLoader.LoadParameters(model); List <Situation> situations = XmlLoader.LoadSituations(model, parameters); Schedule schedule = XmlLoader.LoadSchedule(model.GetElementsByTagName("schedule")[0], situations, true); XElement xElement = XElement.Parse(Resources.Load <TextAsset>(modelDir).text); int pointsEvery = int.Parse(xElement.Elements().FirstOrDefault(t => t.Name == "gainPoints").Attribute("afterEveryHour").Value); List <Plot.Element> plotElements = XmlLoader.LoadPlot(xElement.Elements().FirstOrDefault(t => t.Name == "plot"), parameters, situations); GameState = new GameState(parameters, situations, schedule, new Model(moduleId, XmlLoader.LoadTime(model, parameters)), new Plot(plotElements), gameHash, pointsEvery); GameState.GameTimeChangeListeners.Add(PanelCenter); GameState.ActualPointsChangeLisnters.Add(PanelCenter.gameObject.FindByName <PanelAvailablePoints>("PanelAvailablePoints")); PanelCenter.Init(GameState); ChangePanel(typeof(PanelCenter)); }
ImageEx IDrawingCanvas.CreateImage(ImageInfo image) { var cacheId = Convert.ToBase64String(HashCalculator.ComputeSimpleHash(image.Stream)); image.Stream.Position = 0; return(new Image(_images.GetPdfImage(cacheId, image.Stream))); }
public override int CalculateHash(HashCalculator calc) { return(HashCalculator.Combine( GetType().GetHashCode(), _preventCombatOnly.GetHashCode(), calc.Calculate(_source))); }
public void TestMaxLenNotAffectsHash() { var h20 = new HashCalculator(GroBufHelpers.Seed, 20); var h10 = new HashCalculator(GroBufHelpers.Seed, 10); Assert.AreEqual(h20.CalcHash("qxx"), h10.CalcHash("qxx")); }
StoredPackage ReadPackageFile(string filePath) { try { var metadata = new ZipPackage(filePath); using (var hashStream = metadata.GetStream()) { var hash = HashCalculator.Hash(hashStream); var packageMetadata = new PackageMetadata { Id = metadata.Id, Version = metadata.Version.ToString(), Hash = hash }; return(new StoredPackage(packageMetadata, filePath)); } } catch (FileNotFoundException) { return(null); } catch (IOException) { return(null); } catch (FileFormatException) { return(null); } }
/// <summary> /// Calculates hash for the specified value /// </summary> private static string ComputeHash(object value) { string key = string.Empty; if (value == null) { return(key); } if (value is string) { key = value as string; } else { if (!(value is byte[])) { return(key); } byte[] rawBytes = HashCalculator.ComputeMD5((byte[])value); StringBuilder sb = new StringBuilder(rawBytes.Length); for (int i = 0; i < rawBytes.Length; i++) { sb.Append(rawBytes[i].ToString("X2")); } key = sb.ToString(); } return(key); }
public int CalculateHash(HashCalculator calc) { var hashcodes = Value.Select(item => item.GetHashCode()) .ToList(); return(HashCalculator.CombineCommutative(hashcodes)); }
private string GetCacheFileName(string path) { string pluginDir = Path.Combine(PathHelper.DataDir, "ASCompletion"); string cacheDir = Path.Combine(pluginDir, "FileCache"); string hashFileName = HashCalculator.CalculateSHA1(path); return Path.Combine(cacheDir, hashFileName + "." + context.Settings.LanguageId.ToLower()); }
public int CalculateHash(HashCalculator calc) { return(HashCalculator.Combine( calc.Calculate(_isBlocked), calc.Calculate(_card), calc.Calculate(_blockers))); }
static void Main(string[] args) { string secret = " jp7SjOOr4czRTifCo30qx0sZAIw9PW+vVpsbP09pQaY="; string scheme = "Onnistuu"; string clientIdentifier = "ddf58116-6082-4bfc-a775-0c0bb2f945ce"; IEnvironment environment = new EnvironmentStaging(); IHashCalculator hashCalculator = new HashCalculator(secret, environment.Root); IAuthentication authentication = new CompanyAuthentication(scheme, clientIdentifier, DateTime.Now, hashCalculator); IResponseParser responseParser = new ResponseParser(); VismaSignClient client = new VismaSignClient(authentication, environment, responseParser); var documentUri = client.DocumentCreate(new Document() { document = new Document.DocumentData() { name = "Test doc" } }); WebClient webClient = new WebClient(); byte[] fileContent = webClient.DownloadData("https://sign.visma.net/empty.pdf"); client.DocumentAddFile(documentUri, fileContent, "test.pdf"); }
public void DownloadPackage(string packageId, NuGetVersion version, string feedId, Uri feedUri, ICredentials feedCredentials, bool forcePackageDownload, out string downloadedTo, out string hash, out long size) { var cacheDirectory = GetPackageRoot(feedId); LocalNuGetPackage downloaded = null; downloadedTo = null; if (!forcePackageDownload) { AttemptToGetPackageFromCache(packageId, version, feedId, cacheDirectory, out downloaded, out downloadedTo); } if (downloaded == null) { DownloadPackage(packageId, version, feedUri, feedCredentials, cacheDirectory, out downloaded, out downloadedTo); } else { Log.VerboseFormat("Package was found in cache. No need to download. Using file: '{0}'", downloadedTo); } size = fileSystem.GetFileSize(downloadedTo); string packageHash = null; downloaded.GetStream(stream => packageHash = HashCalculator.Hash(stream)); hash = packageHash; }
string Hash(string packageFilePath) { using (var stream = fileSystem.OpenFile(packageFilePath, FileMode.Open)) { return(HashCalculator.Hash(stream)); } }
public void Install(RunningDeployment deployment) { var package = deployment.Variables.Get(SpecialVariables.Action.Azure.CloudServicePackagePath); Log.Info("Uploading package to Azure blob storage: '{0}'", package); var packageHash = HashCalculator.Hash(package); var nugetPackageVersion = deployment.Variables.Get(SpecialVariables.Package.NuGetPackageVersion); var uploadedFileName = Path.ChangeExtension(Path.GetFileName(package), "." + nugetPackageVersion + "_" + packageHash + ".cspkg"); var credentials = credentialsFactory.GetCredentials( deployment.Variables.Get(SpecialVariables.Action.Azure.SubscriptionId), deployment.Variables.Get(SpecialVariables.Action.Azure.CertificateThumbprint), deployment.Variables.Get(SpecialVariables.Action.Azure.CertificateBytes) ); var storageAccountName = deployment.Variables.Get(SpecialVariables.Action.Azure.StorageAccountName); var storageEndpointSuffix = deployment.Variables.Get(SpecialVariables.Action.Azure.StorageEndPointSuffix, DefaultVariables.StorageEndpointSuffix); var defaultServiceManagementEndpoint = deployment.Variables.Get(SpecialVariables.Action.Azure.ServiceManagementEndPoint, DefaultVariables.ServiceManagementEndpoint); var uploadedUri = azurePackageUploader.Upload(credentials, storageAccountName, package, uploadedFileName, storageEndpointSuffix, defaultServiceManagementEndpoint); Log.SetOutputVariable(SpecialVariables.Action.Azure.UploadedPackageUri, uploadedUri.ToString(), deployment.Variables); Log.Info("Package uploaded to " + uploadedUri.ToString()); }
protected override bool Verify(string fileName, CancellationToken cancellationToken = default) { FileHelper.WaitFileRelease(fileName, cancellationToken); var file = new FileInfo(fileName); string actualHash; switch (HashType) { case "sha1": actualHash = HashCalculator.GetSha1Hash(file); break; case "sha256": actualHash = HashCalculator.GetSha256Hash(file); break; case "sha384": actualHash = HashCalculator.GetSha384Hash(file); break; case "sha512": actualHash = HashCalculator.GetSha512Hash(file); break; default: EventLog.WriteEntry("prng", $"Invalid hash rule: invalid hash type ({HashType})", EventLogEntryType.Warning); return(false); } return(actualHash.ToLowerInvariant() == Hash.ToLowerInvariant()); }
private Dictionary <string, List <string> > FindDuplicateFilesIterative(string rootDirectory) { Dictionary <string, List <string> > duplicatesFiles = new Dictionary <string, List <string> >(); Console.WriteLine($"Start iterative operation for finding duplicate files from {rootDirectory}"); Queue <string> directoriesToSearch = new Queue <string>(); directoriesToSearch.Enqueue(rootDirectory); while (directoriesToSearch.Count > 0) { string currentSearchDirectory = directoriesToSearch.Dequeue(); Console.WriteLine($"Collecting from {currentSearchDirectory}"); // Adding subdirectories to search. foreach (string directory in Directory.EnumerateDirectories(currentSearchDirectory)) { directoriesToSearch.Enqueue(directory); } // Search files. foreach (string filePath in Directory.EnumerateFiles(currentSearchDirectory)) { AddFileHashToGivenDict(duplicatesFiles, HashCalculator.CalculateHash(filePath), filePath); } } Console.WriteLine($"Finished iterative operation for finding duplicate files from {rootDirectory}"); return(duplicatesFiles); }
public override int CalculateHash(HashCalculator calc) { return(HashCalculator.Combine( base.CalculateHash(calc), calc.Calculate(_source), calc.Calculate(_creatureOrPlayer))); }
public int CalculateHash(HashCalculator calc) { return(HashCalculator.Combine( calc.Calculate(Card), DamageAssignmentOrder, calc.Calculate(_assignedDamage))); }
public override int CalculateHash(HashCalculator calc) { return HashCalculator.Combine( base.CalculateHash(calc), _p.ActivateAsSorcery.GetHashCode(), calc.Calculate(_p.Cost)); }
public override int CalculateHash(HashCalculator calc) { return(HashCalculator.Combine( base.CalculateHash(calc), _p.ActivateAsSorcery.GetHashCode(), calc.Calculate(_p.Cost))); }
private FileIntegrity CheckFile(AppContentSummaryFile file) { if (!File.Exists(_localDirectory.Path.PathCombine(file.Path))) { return(new FileIntegrity(file.Path, FileIntegrityStatus.MissingData)); } if (!_localMetaData.IsEntryRegistered(file.Path)) { return(new FileIntegrity(file.Path, FileIntegrityStatus.MissingMetaData)); } if (_localMetaData.GetEntryVersionId(file.Path) != _versionId) { return(new FileIntegrity(file.Path, FileIntegrityStatus.InvalidVersion)); } string hash = HashCalculator.ComputeFileHash(_localDirectory.Path.PathCombine(file.Path)); if (hash != file.Hash) { return(new FileIntegrity(file.Path, FileIntegrityStatus.InvalidHash)); } // TODO: Check file size (always). return(new FileIntegrity(file.Path, FileIntegrityStatus.Ok)); }
public override int CalculateHash(HashCalculator calc) { return(HashCalculator.Combine( GetType().GetHashCode(), _maxAmount, calc.Calculate((IHashable)_creatureOrPlayer))); }
public override int CalculateHash(HashCalculator calc) { return(HashCalculator.Combine( GetType().GetHashCode(), calc.Calculate(_from), calc.Calculate(_to))); }
public override int CalculateHash(HashCalculator calc) { var hashcodes = _p.Triggers.Select(calc.Calculate).ToList(); return HashCalculator.Combine( base.CalculateHash(calc), HashCalculator.Combine(hashcodes)); }
public async Task ComputeFromStreamAsync() { var(bytes, expectedHash) = GenerateTestData(); var stream = new MemoryStream(bytes); Assert.Equal(expectedHash, await HashCalculator.ComputeAsync(stream)); }
public void ComputeFromStream() { var(bytes, expectedHash) = GenerateTestData(); var stream = new MemoryStream(bytes); Assert.Equal(expectedHash, HashCalculator.Compute(stream)); }
public int CalculateHash(HashCalculator calc) { return(HashCalculator.Combine( Step.GetHashCode(), TurnCount, State.GetHashCode() )); }
public int CalculateHash(HashCalculator calc) { if (Ai.IsSearchInProgress && IsVisibleToSearchingPlayer == false) { return Zone.GetHashCode(); } if (_hash.Value.HasValue == false) { // this value can be same for different cards with same NAME, // sometimes this is good sometimes not, currently we favor // smaller tree sizes and less accurate results. // if tree size is no longer a problem we will replace NAME with // a guid. _hash.Value = HashCalculator.Combine( Name.GetHashCode(), _hasSummoningSickness.Value.GetHashCode(), UsageScore.GetHashCode(), IsTapped.GetHashCode(), Damage, HasRegenerationShield.GetHashCode(), HasLeathalDamage.GetHashCode(), Power.GetHashCode(), Toughness.GetHashCode(), Level.GetHashCode(), Counters.GetHashCode(), Type.GetHashCode(), Zone.GetHashCode(), _isRevealed.Value.GetHashCode(), _isPeeked.Value.GetHashCode(), _isHidden.Value.GetHashCode(), calc.Calculate(_simpleAbilities), calc.Calculate(_triggeredAbilities), calc.Calculate(_activatedAbilities), calc.Calculate(_protections), calc.Calculate(_attachments), calc.Calculate(_colors) ); } return _hash.Value.GetValueOrDefault(); }
public int CalculateHash(HashCalculator calc) { return calc.Calculate(_abilities); }
public int CalculateHash(HashCalculator calc) { return calc.Calculate(_assigned); }
public int CalculateHash(HashCalculator calc) { return HashCalculator.Combine( calc.Calculate(_attackers), calc.Calculate(_blockers)); }
public override int CalculateHash(HashCalculator calc) { return GetType().GetHashCode(); }
public int CalculateHash(HashCalculator calc) { return calc.Calculate(_all); }
public int CalculateHash(HashCalculator calc) { return HashCalculator.Combine( Life, HasPriority.GetHashCode(), IsActive.GetHashCode(), calc.Calculate(_assignedDamage), calc.Calculate(_battlefield), calc.Calculate(_graveyard), calc.Calculate(_library), calc.Calculate(_hand), _landLimit.Value.GetValueOrDefault(), _landsPlayedCount.Value ); }