public string GetChecksum(string key) { var path = ComputePath(key); var stream = GetStream(path); return(ChecksumHelper.FromStream(stream)); }
public String GetChecksum(string path, string algorithm) { string fullPath = Project.GetFullPath(path); ChecksumHelper helper = new ChecksumHelper(algorithm); return(helper.CalculateChecksum(fullPath)); }
public ChecksumViewModel() { ChecksumHelper helper = new ChecksumHelper(); Result = helper.Checksum(); BonusResult = helper.ChecksumBonus(); }
public void CalculateHexChecksumTest() { // Arrange byte[] byteArray1 = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; byte[] byteArray2 = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; byte[] byteArray3 = new byte[] { }; // Act string hex1 = ChecksumHelper.CalculateHexChecksum(byteArray1); string hex2 = ChecksumHelper.CalculateHexChecksum(byteArray2); string hex3 = ChecksumHelper.CalculateHexChecksum(byteArray3); string hex4 = ChecksumHelper.CalculateHexChecksum(byteArray1, byteArray2); // Assert Assert.IsNotNull(hex1); Assert.IsNotNull(hex2); Assert.IsNotNull(hex3); Assert.IsNotNull(hex4); Assert.AreEqual(sha256LengthInBytes * 2, hex1.Length, "Every byte should convert to two Hex chars"); Assert.AreEqual(hex1, hex2); Assert.AreNotEqual(hex2, hex3); Assert.AreNotEqual(hex2, hex4); }
private Task <string> GetChecksumAsync(AdapterHolder adapterHolder, string key, CancellationToken cancellationToken) { if (key == null) { throw new ArgumentNullException(nameof(key)); } return(GetChecksumAsyncImpl()); async Task <string> GetChecksumAsyncImpl() { var adapter = await adapterHolder.GetAdapterAsync(); await ThrowIfNotExistsAsync(adapter, key, cancellationToken); if (adapter is IChecksumCalculator checksumCalculator) { return(await checksumCalculator.GetChecksumAsync(key, cancellationToken)); } var bytes = await ReadAllBytesAsync(adapter, key, cancellationToken); return(ChecksumHelper.FromContent(bytes)); } }
private Node ReadAsset(AssetInfo assetInfo, Dictionary <string, Node> containers) { Node asset = NodeFactory.CreateContainer(assetInfo.Id); foreach (Models.FileInfo fileInfo in assetInfo.Files) { if (!containers.TryGetValue(fileInfo.ContainerId, out Node container)) { throw new DirectoryNotFoundException($"Container not found: {fileInfo.ContainerId}"); } Node file = Navigator.SearchNode(container, fileInfo.Path); if (file == null) { throw new FileNotFoundException($"File not found: {fileInfo.Name}"); } if (!ChecksumHelper.Check(file.Stream, fileInfo.Checksum)) { throw new ChecksumMismatchException($"Checksum mismatch in {fileInfo.Name}"); } file.Transform(fileInfo.Readers, Parameters); asset.Add(file); } asset.Transform(assetInfo.Mergers, Parameters); return(asset); }
private string Update(IEnumerable <Guid> add = null, IEnumerable <Guid> remove = null) { lock (Subscriptions) { Subscriptions.UnionWith(add.EmptyIfNull()); Subscriptions.ExceptWith(remove.EmptyIfNull()); return(checksum = Subscriptions.Count + ":" + ChecksumHelper.ComputeHash(Subscriptions)); } }
public IntegTestDscHandlerProvider( ILogger <IntegTestDscHandlerProvider> pLogger, ILogger <IntegTestDscHandler> hLogger, ChecksumAlgorithmManager checksumManager, ChecksumHelper checksumHelper) : base(pLogger, hLogger, checksumManager, checksumHelper) { Console.WriteLine("CONSTRUCTING INTEG-TEST HANDLER PROVIDER"); }
public override void GetChecksum(ChecksumHelper checksum) { checksum.StartObject("LogicResourceProductionComponent"); checksum.WriteValue("resourceTimer", this.m_resourceTimer.GetRemainingSeconds(this.m_parent.GetLevel().GetLogicTime())); checksum.WriteValue("m_availableLoot", this.m_availableLoot); checksum.WriteValue("m_maxResources", this.m_maxResources); checksum.WriteValue("m_productionPer100Hour", this.m_productionPer100Hour); checksum.EndObject(); }
public Ps5DscHandlerProvider( ILogger <Ps5DscHandlerProvider> providerLogger, ILogger <Ps5DscHandler> handlerlogger, IConfiguration appSettings, ChecksumHelper checksumHelper) { _pLogger = providerLogger; _hLogger = handlerlogger; _appConfig = appSettings; _checksumHelper = checksumHelper; }
/// <summary> /// Gets the checksum of this instance. /// </summary> public void GetChecksum(ChecksumHelper checksumHelper) { checksumHelper.StartObject("LogicDataSlot"); if (this._data != null) { checksumHelper.WriteValue("globalID", this._data.GetGlobalID()); } checksumHelper.WriteValue("m_count", this._count); checksumHelper.EndObject(); }
public BasicDscHandlerProvider( ILogger <BasicDscHandlerProvider> pLogger, ILogger <BasicDscHandler> hLogger, ChecksumAlgorithmManager checksumManager, ChecksumHelper checksumHelper) { _pLogger = pLogger; _hLogger = hLogger; _checksumHelper = checksumHelper; _pLogger.LogInformation("Provider Created"); }
/// <summary> /// This is where the work is done /// </summary> protected override void ExecuteTask() { ChecksumHelper helper = new ChecksumHelper(Algorithm); foreach (String file in FileSet.FileNames) { string checksum = helper.CalculateChecksum(file); string outfile = file + "." + FileExtension; WriteChecksum(outfile, checksum); } }
/// <summary> /// Gets the checksum of this instance. /// </summary> public override void GetChecksum(ChecksumHelper checksum, bool includeGameObjects) { checksum.StartObject("LogicTrap"); base.GetChecksum(checksum, includeGameObjects); if (this._constructionTimer != null) { checksum.WriteValue("remainingMS", this._constructionTimer.GetRemainingMS(this._level.GetLogicTime())); } checksum.EndObject(); }
private object Fmt(INote d) { StringBuilder b = new StringBuilder(); b.AppendLine("Note"); b.AppendLine("{"); b.AppendLine($"\tTitle: '{d.Title}'"); b.AppendLine($"\tContentLength: {d.Text.Length}"); b.AppendLine($"\tContentHash: {ChecksumHelper.MD5(d.Text)}"); b.AppendLine($"\tChangeDate: {d.ModificationDate.ToString("yyyy-MM-dd HH:mm:ss")}"); b.AppendLine($"\tFolder: {d.Path.StrSerialize()}"); b.AppendLine("}"); return(b.ToString()); }
private object Fmt(PathEntry d) { StringBuilder b = new StringBuilder(); b.AppendLine("PathEntry"); b.AppendLine("{"); b.AppendLine($"\tTitle: '{d.Title}'"); b.AppendLine($"\tContentLength: {d.Content.Length}"); b.AppendLine($"\tContentHash: {ChecksumHelper.MD5(d.Content)}"); b.AppendLine($"\tChangeDate: {d.MDate.ToString("yyyy-MM-dd HH:mm:ss")}"); b.AppendLine($"\tPath: {d.FilesystemPath}"); b.AppendLine($"\tFolder: {d.NotePath.StrSerialize()}"); b.AppendLine("}"); return(b.ToString()); }
/// <summary> /// Gets the checksum of this instance. /// </summary> public void GetChecksum(ChecksumHelper checksum) { checksum.StartObject("LogicCalendar"); checksum.StartArray("m_pActiveCalendarEvents"); for (int i = 0; i < this._activeCalendarEvents.Count; i++) { checksum.StartObject("LogicCalendarEvent"); checksum.EndObject(); } checksum.EndArray(); checksum.WriteValue("m_activeTimestamp", this._activeTimestamp); checksum.EndObject(); }
private void CheckChecksum(int clientChecksum) { LogicJSONObject debugJSON = new LogicJSONObject(); ChecksumHelper checksum = this.m_logicGameMode.CalculateChecksum(debugJSON, EnvironmentSettings.Settings.ContentValidationModeEnabled); if (checksum.GetChecksum() != clientChecksum) { OutOfSyncMessage outOfSyncMessage = new OutOfSyncMessage(); outOfSyncMessage.SetSubTick(this.m_logicGameMode.GetLevel().GetLogicTime().GetTick()); outOfSyncMessage.SetClientChecksum(clientChecksum); outOfSyncMessage.SetServerChecksum(checksum.GetChecksum()); outOfSyncMessage.SetDebugJSON(debugJSON); this.m_session.SendPiranhaMessage(outOfSyncMessage, 1); this.m_shouldDestruct = true; } }
public void JoinByteArraysTest() { // Arrange byte[] byteArray1 = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; byte[] byteArray2 = new byte[] { 123, 255, 13, 3, 33 }; byte[] byteArray3 = new byte[0]; byte[] byteArray4 = new byte[] { 100, 100, 100, 100 }; // Act byte[] joined1 = ChecksumHelper.JoinByteArrays(byteArray1, byteArray2); // Assert Assert.IsNotNull(joined1); Assert.AreEqual(byteArray1.Length + byteArray2.Length, joined1.Length); Assert.IsTrue(CheckSequence(joined1, byteArray1)); Assert.IsTrue(CheckSequence(joined1, byteArray2)); Assert.IsFalse(CheckSequence(joined1, byteArray4)); }
public virtual FileContent GetModule(Guid?agentId, string moduleName, string moduleVersion) { var modulePath = Path.Combine(ModulePath, $"{moduleName}/{moduleVersion}.zip"); if (!File.Exists(modulePath)) { return(null); } // TODO: Clean this up for performance with caching and stuff using (var cs = ChecksumHelper.GetAlgorithm()) using (var fs = File.OpenRead(modulePath)) { return(new FileContent { ChecksumAlgorithm = cs.AlgorithmName, Checksum = cs.ComputeChecksum(fs), Content = (Stream)File.OpenRead(modulePath), }); } }
public virtual FileContent GetConfiguration(Guid agentId, string configName) { var configPath = Path.Combine(ConfigurationPath, $"SHARED/{configName}.mof"); if (!File.Exists(configPath)) { Logger.LogWarning($"unable to find ConfigurationName=[{configName}] for AgentId=[{agentId}]"); return(null); } // TODO: Clean this up for performance with caching and stuff using (var cs = ChecksumHelper.GetAlgorithm()) using (var fs = File.OpenRead(configPath)) { return(new FileContent { ChecksumAlgorithm = cs.AlgorithmName, Checksum = cs.ComputeChecksum(fs), Content = (Stream)File.OpenRead(configPath), }); } }
private void ReadContainers(IList <ContainerInfo> containers, Node parent, Dictionary <string, Node> dictionary) { foreach (ContainerInfo containerInfo in containers) { Node node = Navigator.SearchNode(parent, containerInfo.Path); if (node == null) { throw new DirectoryNotFoundException($"Parent: {parent.Path} - Node: {containerInfo.Path}"); } if (!ChecksumHelper.Check(node.Stream, containerInfo.Checksum)) { throw new ChecksumMismatchException($"Checksum mismatch in {containerInfo.Name}"); } node.Transform(containerInfo.Readers, Parameters); dictionary.Add(containerInfo.Id, node); ReadContainers(containerInfo.Containers, node, dictionary); } }
private string GetManifestFile(UrlHelper url, out string newChecksum) { string leadComment = $"App Version: {GetType().Assembly.GetName().Version}", cachePart = "", networkPart = "*", fallbackPart = ""; leadComment = $"{leadComment}, Timestamp: {DateTime.Now.ToString("MMMM dd, yyyy H:mm:ss")}"; var imgFolder = new DirectoryInfo(Server.MapPath("~/Content/Images")); var imgNames = GetFileNames(imgFolder); cachePart = string.Join(Environment.NewLine, imgNames.Select(img => url.Content($"~/Content/Images/{img}"))); //cachePart = $"{cachePart}\n" + "http://cdtssql353d:8000/t/Horizon/views/CopaycardSuite_NIAD/2_CopaysandCostImpact?&isdebug=true"; var manifestContent = $"CACHE:\n{cachePart}\n\nNETWORK:\n{networkPart}\n\nFALLBACK:\n{fallbackPart}"; var checksum = ChecksumHelper.GetMD5Checksum(manifestContent); newChecksum = checksum; var manifestFile = $"CACHE MANIFEST\n# {leadComment}, Checksum: {ChecksumHelper.GetMD5Checksum(manifestContent)}\n\n{manifestContent}"; return(manifestFile); }
/// <summary> /// Calculates the checksum of this instance. /// </summary> public ChecksumHelper CalculateChecksum(bool includeGameObjects) { ChecksumHelper checksum = new ChecksumHelper(); checksum.StartObject("LogicGameMode"); checksum.WriteValue("subTick", this._level.GetLogicTime()); checksum.WriteValue("m_currentTimestamp", this._currentTimestamp); if (this._level.GetHomeOwnerAvatar() != null) { checksum.StartObject("homeOwner"); this._level.GetHomeOwnerAvatar().GetChecksum(checksum); checksum.EndObject(); } if (this._level.GetVisitorAvatar() != null) { checksum.StartObject("visitor"); this._level.GetVisitorAvatar().GetChecksum(checksum); checksum.EndObject(); } this._level.GetGameObjectManager().GetChecksum(checksum, includeGameObjects); if (this._calendar != null) { checksum.StartObject("calendar"); this._calendar.GetChecksum(checksum); checksum.EndObject(); } checksum.WriteValue("checksum", checksum); checksum.EndObject(); return(checksum); }
public virtual void GetChecksum(ChecksumHelper checksum, bool includeGameObjects) { if (includeGameObjects) { checksum.StartObject("LogicGameObject"); checksum.WriteValue("type", (int)this.GetGameObjectType()); checksum.WriteValue("globalID", this.m_globalId); checksum.WriteValue("dataGlobalID", this.m_data.GetGlobalID()); checksum.WriteValue("x", this.GetX()); checksum.WriteValue("y", this.GetY()); checksum.WriteValue("seed", this.m_seed); LogicHitpointComponent hitpointComponent = this.GetHitpointComponent(); if (hitpointComponent != null) { checksum.WriteValue("m_hp", hitpointComponent.GetHitpoints()); checksum.WriteValue("m_maxHP", hitpointComponent.GetMaxHitpoints()); } LogicCombatComponent combatComponent = this.GetCombatComponent(); if (combatComponent != null) { LogicGameObject target = combatComponent.GetTarget(0); if (target != null) { checksum.WriteValue("target", target.GetGlobalID()); } } checksum.EndObject(); } }
/// <summary> /// Gets the checksum of this instance. /// </summary> public virtual void GetChecksum(ChecksumHelper checksum, bool includeGameObjects) { if (includeGameObjects) { checksum.StartObject("LogicGameObject"); checksum.WriteValue("type", this.GetGameObjectType()); checksum.WriteValue("globalID", this._globalId); checksum.WriteValue("dataGlobalID", this._data.GetGlobalID()); checksum.WriteValue("x", this.GetX()); checksum.WriteValue("y", this.GetY()); checksum.WriteValue("seed", this._seed); if (this.GetHitpointComponent() != null) { LogicHitpointComponent hitpointComponent = this.GetHitpointComponent(); checksum.WriteValue("m_hp", hitpointComponent.InternalGetHp()); checksum.WriteValue("m_maxHP", hitpointComponent.InternalGetMaxHp()); } checksum.EndObject(); } }
public override void Execute() { Logger.LogInformation("Calculate checksum for file : '{0}'", TargetCollection); var eventModel = CurrentActionProperties(TargetCollection, this.GetType().Name); OnTrigger(new PreingestEventArgs { Description = String.Format("Start calculate checksum for container '{0}'.", TargetCollection), Initiate = DateTimeOffset.Now, ActionType = PreingestActionStates.Started, PreingestAction = eventModel }); var anyMessages = new List <String>(); string currentCalculation = string.Empty; bool isSuccess = false; try { /** * checksum-sha224 * checksum-sha384 **/ switch (Checksum.ToUpperInvariant()) { case "MD5": { OnTrigger(new PreingestEventArgs { Description = String.Format("Calculate checksum for container '{0}' with MD5.", TargetCollection), Initiate = DateTimeOffset.Now, ActionType = PreingestActionStates.Executing, PreingestAction = eventModel }); string url = String.Format("http://{0}:{1}/hooks/{3}?file={2}", ApplicationSettings.ChecksumServerName, ApplicationSettings.ChecksumServerPort, TargetCollection, "checksum-md5"); currentCalculation = ChecksumHelper.CreateMD5Checksum(new FileInfo(TargetCollection), url); } break; case "SHA1": case "SHA-1": { OnTrigger(new PreingestEventArgs { Description = String.Format("Start calculate checksum for container '{0}' with SHA1.", TargetCollection), Initiate = DateTimeOffset.Now, ActionType = PreingestActionStates.Executing, PreingestAction = eventModel }); string url = String.Format("http://{0}:{1}/hooks/{3}?file={2}", ApplicationSettings.ChecksumServerName, ApplicationSettings.ChecksumServerPort, TargetCollection, "checksum-sha1"); currentCalculation = ChecksumHelper.CreateSHA1Checksum(new FileInfo(TargetCollection), url); } break; case "SHA224": case "SHA-224": { OnTrigger(new PreingestEventArgs { Description = String.Format("Start calculate checksum for container '{0}' with SHA224.", TargetCollection), Initiate = DateTimeOffset.Now, ActionType = PreingestActionStates.Executing, PreingestAction = eventModel }); string url = String.Format("http://{0}:{1}/hooks/{3}?file={2}", ApplicationSettings.ChecksumServerName, ApplicationSettings.ChecksumServerPort, TargetCollection, "checksum-sha224"); currentCalculation = ChecksumHelper.CreateSHA224Checksum(new FileInfo(TargetCollection), url); } break; case "SHA256": case "SHA-256": { OnTrigger(new PreingestEventArgs { Description = String.Format("Start calculate checksum for container '{0}' with SHA256.", TargetCollection), Initiate = DateTimeOffset.Now, ActionType = PreingestActionStates.Executing, PreingestAction = eventModel }); string url = String.Format("http://{0}:{1}/hooks/{3}?file={2}", ApplicationSettings.ChecksumServerName, ApplicationSettings.ChecksumServerPort, TargetCollection, "checksum-sha256"); currentCalculation = ChecksumHelper.CreateSHA256Checksum(new FileInfo(TargetCollection), url); } break; case "SHA384": case "SHA-384": { OnTrigger(new PreingestEventArgs { Description = String.Format("Start calculate checksum for container '{0}' with SHA384.", TargetCollection), Initiate = DateTimeOffset.Now, ActionType = PreingestActionStates.Executing, PreingestAction = eventModel }); string url = String.Format("http://{0}:{1}/hooks/{3}?file={2}", ApplicationSettings.ChecksumServerName, ApplicationSettings.ChecksumServerPort, TargetCollection, "checksum-sha384"); currentCalculation = ChecksumHelper.CreateSHA384Checksum(new FileInfo(TargetCollection), url); } break; case "SHA512": case "SHA-512": { OnTrigger(new PreingestEventArgs { Description = String.Format("Start calculate checksum for container '{0}' with SHA512.", TargetCollection), Initiate = DateTimeOffset.Now, ActionType = PreingestActionStates.Executing, PreingestAction = eventModel }); string url = String.Format("http://{0}:{1}/hooks/{3}?file={2}", ApplicationSettings.ChecksumServerName, ApplicationSettings.ChecksumServerPort, TargetCollection, "checksum-sha512"); currentCalculation = ChecksumHelper.CreateSHA512Checksum(new FileInfo(TargetCollection), url); } break; default: { anyMessages.Add(String.Format("Checksum {0} not defined. No calculation available.", Checksum)); Logger.LogWarning(String.Format("Checksum {0} not defined. No calculation available.", Checksum)); } break; } //failed, no value if (String.IsNullOrEmpty(currentCalculation)) { throw new ApplicationException("Calculation returned nothing or empty value!"); } var fileInformation = new FileInfo(TargetCollection); anyMessages.Add(String.Concat("Name : ", fileInformation.Name)); anyMessages.Add(String.Concat("Extension : ", fileInformation.Extension)); anyMessages.Add(String.Concat("Size : ", fileInformation.Length)); anyMessages.Add(String.Concat("CreationTime : ", fileInformation.CreationTimeUtc)); anyMessages.Add(String.Concat("LastAccessTime : ", fileInformation.LastAccessTimeUtc)); anyMessages.Add(String.Concat("LastWriteTime : ", fileInformation.LastWriteTimeUtc)); eventModel.Properties.Messages = anyMessages.ToArray(); var data = new List <String>(); data.Add(Checksum); data.Add(currentCalculation); isSuccess = !String.IsNullOrEmpty(currentCalculation); eventModel.ActionResult.ResultValue = PreingestActionResults.Success; eventModel.Summary.Processed = 1; eventModel.Summary.Accepted = 1; eventModel.Summary.Rejected = 0; if (!String.IsNullOrEmpty(DeliveredChecksumValue)) { bool isTheSame = DeliveredChecksumValue.Equals(currentCalculation, StringComparison.InvariantCultureIgnoreCase); data.Add(String.Format("{0} {1} {2}", DeliveredChecksumValue, isTheSame ? "=" : "≠", currentCalculation)); eventModel.Properties.Messages = anyMessages.ToArray(); if (!isTheSame) { eventModel.ActionResult.ResultValue = PreingestActionResults.Error; eventModel.Summary.Processed = 1; eventModel.Summary.Accepted = 0; eventModel.Summary.Rejected = 1; } } eventModel.ActionData = data.ToArray(); } catch (Exception e) { isSuccess = false; anyMessages.Clear(); anyMessages.Add(String.Format("Calculation checksum from file : '{0}' failed!", TargetCollection)); anyMessages.Add(e.Message); anyMessages.Add(e.StackTrace); Logger.LogError(e, "Calculation checksum from file : '{0}' failed!", TargetCollection); eventModel.Properties.Messages = anyMessages.ToArray(); eventModel.ActionResult.ResultValue = PreingestActionResults.Failed; eventModel.Summary.Processed = -1; eventModel.Summary.Accepted = -1; eventModel.Summary.Rejected = -1; OnTrigger(new PreingestEventArgs { Description = "An exception occured while calculating the checksum!", Initiate = DateTimeOffset.Now, ActionType = PreingestActionStates.Failed, PreingestAction = eventModel }); } finally { if (isSuccess) { OnTrigger(new PreingestEventArgs { Description = "Checksum calculation is done.", Initiate = DateTimeOffset.Now, ActionType = PreingestActionStates.Completed, PreingestAction = eventModel }); } } }
private List <ResultType> RunFixityCheck(FileInfo binaryFiles, AlgorithmTypes useAlgorithm, string valueToCompare = null) { List <ResultType> checkResult = new List <ResultType>(); string currentCalculation = string.Empty, url = string.Empty, urlPart = string.Empty; try { switch (useAlgorithm) { default: case AlgorithmTypes.MD5: { urlPart = "checksum-md5"; url = String.Format("http://{0}:{1}/hooks/{3}?file={2}", ApplicationSettings.ChecksumServerName, ApplicationSettings.ChecksumServerPort, binaryFiles.FullName, urlPart); currentCalculation = ChecksumHelper.CreateMD5Checksum(binaryFiles, url); } break; case AlgorithmTypes.SHA1: { urlPart = "checksum-sha1"; url = String.Format("http://{0}:{1}/hooks/{3}?file={2}", ApplicationSettings.ChecksumServerName, ApplicationSettings.ChecksumServerPort, binaryFiles.FullName, urlPart); currentCalculation = ChecksumHelper.CreateSHA1Checksum(binaryFiles, url); } break; case AlgorithmTypes.SHA224: { urlPart = "checksum-sha224"; url = String.Format("http://{0}:{1}/hooks/{3}?file={2}", ApplicationSettings.ChecksumServerName, ApplicationSettings.ChecksumServerPort, binaryFiles.FullName, urlPart); currentCalculation = ChecksumHelper.CreateSHA224Checksum(binaryFiles, url); } break; case AlgorithmTypes.SHA256: { urlPart = "checksum-sha256"; url = String.Format("http://{0}:{1}/hooks/{3}?file={2}", ApplicationSettings.ChecksumServerName, ApplicationSettings.ChecksumServerPort, binaryFiles.FullName, urlPart); currentCalculation = ChecksumHelper.CreateSHA256Checksum(binaryFiles, url); } break; case AlgorithmTypes.SHA384: { urlPart = "checksum-sha384"; url = String.Format("http://{0}:{1}/hooks/{3}?file={2}", ApplicationSettings.ChecksumServerName, ApplicationSettings.ChecksumServerPort, binaryFiles.FullName, urlPart); currentCalculation = ChecksumHelper.CreateSHA384Checksum(binaryFiles, url); } break; case AlgorithmTypes.SHA512: { urlPart = "checksum-sha512"; url = String.Format("http://{0}:{1}/hooks/{3}?file={2}", ApplicationSettings.ChecksumServerName, ApplicationSettings.ChecksumServerPort, binaryFiles.FullName, urlPart); currentCalculation = ChecksumHelper.CreateSHA512Checksum(binaryFiles, url); } break; } } catch (Exception e) { checkResult.Add(new ResultType { Type = ResultType.InfoType.Message, Data = new string[] { binaryFiles.FullName, "Failed to run fixity checksum!", e.Message, e.StackTrace } }); } finally { if (!String.IsNullOrEmpty(currentCalculation) && HashType.ProcessingMode == ExecutionMode.OnlyCalculate) { checkResult.Add(new ResultType { Type = ResultType.InfoType.Action, Data = new string[] { binaryFiles.FullName, currentCalculation } }); } if (!String.IsNullOrEmpty(currentCalculation) && HashType.ProcessingMode == ExecutionMode.CalculateAndCompare) { if (currentCalculation.Equals(valueToCompare, StringComparison.InvariantCultureIgnoreCase)) { checkResult.Add(new ResultType { Type = ResultType.InfoType.Action, Data = new string[] { binaryFiles.FullName, useAlgorithm.ToString(), string.Format("Our calculation : {0}", currentCalculation), string.Format("Provided value : {0}", valueToCompare), } }); } else { checkResult.Add(new ResultType { Type = ResultType.InfoType.Message, Data = new string[] { String.Format("Fixity comparison with file '{0}' using algorithm '{1}' failed!{2}Our calculation: {3}{2}Provided value:{4} ", binaryFiles.FullName, useAlgorithm, Environment.NewLine, currentCalculation, valueToCompare) } }); } } } return(checkResult); }
public Checksum CalculateChecksum() { return(new ChecksumString(ChecksumHelper.CalculateMD5(GetStateString()))); }
public virtual ActionStatus GetDscAction(Guid agentId, GetDscActionRequestBody detail) { var regPath = Path.Combine(RegistrationSavePath, $"{agentId}.json"); if (!File.Exists(regPath)) { throw new InvalidOperationException("unknown agent ID"); } var regDetail = JsonConvert.DeserializeObject <RegisterDscAgentRequestBody>( File.ReadAllText(regPath)); var configCount = (regDetail.ConfigurationNames?.Length).GetValueOrDefault(); Logger.LogDebug($"regDetail[{JsonConvert.SerializeObject(regDetail)}]"); DscActionStatus nodeStatus = DscActionStatus.OK; var list = new List <ActionDetailsItem>(); if (configCount == 0) { // Nothing to do since we don't know what config name to provide; // the xDscWebService-compatible behavior is to just return an OK nodeStatus = DscActionStatus.OK; Logger.LogWarning($"No configuration names specified during registration for AgentId=[{agentId}]"); } else if (configCount == 1) { var cn = regDetail.ConfigurationNames[0]; // This is the scenario of a single (default) // named configuration tied to the node if (detail.ClientStatus?.Length == 1 && (string.IsNullOrEmpty(detail.ClientStatus[0].ConfigurationName) || detail.ClientStatus[0].ConfigurationName == cn)) { var cs = detail.ClientStatus[0]; // Checksum is for the single default configuration of this node var configPath = Path.Combine(ConfigurationPath, $"SHARED/{cn}.mof"); if (!File.Exists(configPath)) { Logger.LogWarning($"unable to find ConfigurationName=[{cn}] for AgentId=[{agentId}]"); return(null); } // Assume we have to pull nodeStatus = DscActionStatus.GetConfiguration; var dtlItem = new ActionDetailsItem { ConfigurationName = cn, Status = nodeStatus, }; list.Add(dtlItem); if (!string.IsNullOrEmpty(cs.Checksum)) // Empty Checksum on the first pull { using (var csum = ChecksumHelper.GetAlgorithm()) { if (csum.AlgorithmName == cs.ChecksumAlgorithm && !string.IsNullOrEmpty(cs.Checksum)) // Make sure we're on the same algor { using (var fs = File.OpenRead(configPath)) { var csumCsum = csum.ComputeChecksum(fs); if (csumCsum == cs.Checksum) { // We've successfully passed all the checks, nothing to do nodeStatus = DscActionStatus.OK; dtlItem.Status = nodeStatus; } else { Logger.LogDebug($"Checksum mismatch " + "[{csumCsum}]!=[{cs.Checksum}]" + "for AgentId=[{agentId}]"); } } } else { Logger.LogWarning($"Checksum Algorithm mismatch " + "[{csum.AlgorithmName}]!=[{cs.ChecksumAlgorithm}] " + "for AgentId=[{agentId}]"); } } } else { Logger.LogDebug($"First time pull check for AgentId=[{agentId}]"); } } else { throw new NotImplementedException("only single/default configuration names are implemented"); } } else { Logger.LogWarning($"Found [{regDetail.ConfigurationNames.Length}] config names: {regDetail.ConfigurationNames}"); throw new NotImplementedException("multiple configuration names are not implemented"); // foreach (var cn in regDetail.ConfigurationNames) // { // var configPath = Path.Combine(ConfigurationPath, $"SHARED/{cn}.mof"); // if (!File.Exists(configPath)) // throw new InvalidOperationException($"missing configuration by name [{cn}]"); // using (var csum = ChecksumHelper.GetAlgorithm()) // { // if (csum.AlgorithmName != cs.ChecksumAlgorithm) // { // Logger.LogError("Checksum Algorithm mismatch!"); // } // else // { // using (var fs = File.OpenRead(configPath)) // { // if (csum.ComputeChecksum(fs) == cs.Checksum) // continue; // } // } // } // } } /* * foreach (var cs in detail.ClientStatus) * { * if (string.IsNullOrEmpty(cs.ConfigurationName)) * { * var configPath = Path.Combine(ConfigurationPath, $"{agentId}/{agentId}.mof"); * if (!File.Exists(configPath)) * { * nodeStatus = DscActionStatus.RETRY; * list.Add(new GetDscActionResponseBody.DetailsItem * { * Status = DscActionStatus.RETRY, * }); * } * else * { * using (var csum = ChecksumHelper.GetAlgorithm()) * { * if (csum.AlgorithmName != cs.ChecksumAlgorithm) * { * Logger.LogError("Checksum Algorithm mismatch!"); * } * else * { * using (var fs = File.OpenRead(configPath)) * { * if (csum.ComputeChecksum(fs) == cs.Checksum) * continue; * } * } * } * * nodeStatus = DscActionStatus.GetConfiguration; * list.Add(new GetDscActionResponseBody.DetailsItem * { * Status = DscActionStatus.GetConfiguration, * }); * } * } * } */ return(new ActionStatus { NodeStatus = nodeStatus, ConfigurationStatuses = list.ToArray(), }); }