/* * Copyright (c) 2026 Winsider Seminars & Solutions, Inc. All rights reserved. * * This file is part of System Informer. * */ namespace CustomBuildTool { /// /// Provides methods to pack a setup package and source file. /// public static class BuildRotate { /// /// Rotates each bit within every byte of a setup package and writes the result to a separate file. /// /// The rotation count and whether the rotation was to the left. public static (int Count, bool Left) RotateSetupFile(string SourcePath, string TargetPath) { if (string.Equals(Path.GetFullPath(SourcePath), Path.GetFullPath(TargetPath), StringComparison.OrdinalIgnoreCase)) throw new ArgumentException("The output path must differ from the setup executable path.", nameof(TargetPath)); int count = Utils.GetRandomNumberOneToSeven(); bool left = RandomNumberGenerator.GetInt32(2) == 0; byte[] buffer = new byte[64 * 1024]; using FileStream source = File.OpenRead(SourcePath); using FileStream target = File.Create(TargetPath); int length; while ((length = source.Read(buffer)) != 0) { for (int index = 0; index < length; index++) { // Repeating the byte across a uint makes a 32-bit intrinsic rotate equivalent to a byte rotate. uint repeatedByte = (uint)buffer[index] * 0x01010101u; buffer[index] = (byte)(left ? BitOperations.RotateLeft(repeatedByte, count) : BitOperations.RotateRight(repeatedByte, count)); } target.Write(buffer, 0, length); } return (count, left); } /// /// The autogenerated file header written to generated source files. /// private const string FileHeader = @"/* * Copyright (c) 2026 Winsider Seminars & Solutions, Inc. All rights reserved. * * This file is part of System Informer. * * THIS IS AN AUTOGENERATED FILE, DO NOT MODIFY * */"; /// /// Writes an autogenerated C source file recording the rotation count and direction /// so the rotation applied to the target file can be reversed. /// /// The path of the generated C source file. /// The rotation count (1 through 7). /// Whether the rotation was to the left. public static void GenerateRotationSource(string SourcePath, int Count, bool Left) { byte[] data = [(byte)Count, (byte)(Left ? 1 : 0)]; Utils.WriteTextIfChanged(SourcePath, sb => { sb.WriteLine(FileHeader); sb.WriteLine(); sb.WriteLine("#include "); sb.WriteLine(); sb.WriteLine("CONST BYTE SetupRotationData[] ="); sb.WriteLine("{"); WriteBytes(sb, data); sb.WriteLine("};"); sb.WriteLine(); sb.WriteLine("CONST ULONG SetupRotationDataLength = ARRAYSIZE(SetupRotationData);"); }); } /// /// Writes a byte array as C source, formatted eight bytes per line. /// /// The writer receiving the formatted bytes. /// The bytes to write. private static void WriteBytes(TextWriter sb, byte[] Buffer) { if (Buffer == null || Buffer.Length == 0) return; for (var i = 0; i < Buffer.Length; i++) { if (i % 8 == 0) { sb.Write(" "); } sb.Write($"0x{Buffer[i]:x2},"); if (i % 8 == 7 || i == Buffer.Length - 1) sb.WriteLine(); else sb.Write(' '); } } } }