void SaveUserSettings() { if (!Directory.Exists(UserDataFolder)) { Directory.CreateDirectory(UserDataFolder); } using (FileStream fs = File.Create(UserSettingsFilePath)) using (var xs = new XorStream(fs)) using (var gzs = new GZipStream(xs, CompressionMode.Compress)) { var writer = new RawDataWriter(xs, Encoding.UTF8); writer.Write(Encoding.UTF8.GetBytes(USER_SETTINGS_SIGNATURE)); writer.Write(IsMaximized); writer.Write(FrameRectangle.Left); writer.Write(FrameRectangle.Top); writer.Write(FrameRectangle.Width); writer.Write(FrameRectangle.Height); writer.Write(UseCountryCode); writer.Write(MRUSubHeadingSize); writer.Write(MRUSubHeading.Count); foreach (SubHeading sh in MRUSubHeading) { writer.Write(sh.Value); } writer.Write(AutoDetectProxy); writer.Write(EnableProxy); writer.Write(ProxyHost ?? ""); writer.Write(ProxyPort); } }
private static void Encode(Stream input, Stream output) { using (PaddedStream paddedInput = new PaddedStream(input, 32, PaddedStreamMode.Read)) { using (XorStream xorPaddedInput = new XorStream(paddedInput)) { using (MemoryStream normalOutput = new MemoryStream()) { using (MemoryStream xorOutput = new MemoryStream()) { long initialPosition = input.Position; long inputLength = input.Length - initialPosition; // Compress using normal encoding EncodeInternal(paddedInput, normalOutput, false, inputLength); // Reset the input stream and compress using XOR encoding input.Position = initialPosition; EncodeInternal(xorPaddedInput, xorOutput, true, inputLength); long normalOutputLength = normalOutput.Length; long xorOutputLength = xorOutput.Length; using (PaddedStream paddedOutput = new PaddedStream(output, 2, PaddedStreamMode.Write)) { byte[] outputBytes = (normalOutputLength <= xorOutputLength ? normalOutput : xorOutput).ToArray(); paddedOutput.Write(outputBytes, 0, outputBytes.Length); } } } } } }
public void Save(Stream output, IList <IArchiveFileInfo> files) { // Wrap encryption output = new XorStream(output, _selectedKey); using var bw = new BinaryWriterX(output, ByteOrder.BigEndian); // Calculate offsets var sizeOffset = 2 + files.Sum(x => Encoding.UTF8.GetByteCount(x.FilePath.ToRelative().FullName)) + files.Count * 2; var dataOffset = sizeOffset + 2 + files.Count * 4; // Write files output.Position = dataOffset; foreach (var file in files.Cast <ArchiveFileInfo>()) { file.SaveFileData(output); } // Write sizes output.Position = sizeOffset; bw.Write((short)files.Count); bw.WriteMultiple(files.Select(x => (int)x.FileSize)); // Write names output.Position = 0; bw.Write((short)files.Count); foreach (var file in files) { var name = file.FilePath.ToRelative().FullName; bw.Write((short)Encoding.UTF8.GetByteCount(name)); bw.WriteString(name, Encoding.UTF8, false, false); } }
void LoadAppSettings() { if (!File.Exists(AppSettingsFilePath)) { return; } using (FileStream fs = File.OpenRead(AppSettingsFilePath)) using (var xs = new XorStream(fs)) using (var gzs = new GZipStream(xs, CompressionMode.Decompress)) { var reader = new RawDataReader(xs, Encoding.UTF8); byte[] sign = Encoding.UTF8.GetBytes(APP_SETTINGS_SIGNATURE); for (int i = 0; i < sign.Length; ++i) { if (sign[i] != reader.ReadByte()) { throw new CorruptedFileException(AppSettingsFilePath); } } m_dataGeneration = reader.ReadUInt(); m_updateKey = reader.ReadUInt(); } }
public TcpClientEntry(Stream stm, string endpoint, bool buffered) { _xor_stream = new XorStream(stm); _buffered = buffered; UserName = String.Format("User_{0}", endpoint); HostName = endpoint; }
static string DecodeString(byte[] data) { var ms = new MemoryStream(data); var xs = new XorStream(ms); byte[] buff = new byte[data.Length]; xs.Read(buff, 0, buff.Length); return(Encoding.UTF8.GetString(buff)); }
private Task <bool> DoCipher(Stream input, Stream output, IProgress <ProgressReport> progress, bool decrypt) { var requestId = Guid.NewGuid().ToString("N"); var key = OnRequestKey("XOR Key", -1, requestId, out var error); if (key == null) { return(Task.Factory.StartNew(() => { progress.Report(new ProgressReport { Percentage = 0, Message = error }); return false; })); } return(Task.Factory.StartNew(() => { progress.Report(new ProgressReport { Percentage = 0, Message = decrypt ? "Decryption..." : "Encryption..." }); using (var xor = new XorStream(decrypt ? input : output, key)) { var buffer = new byte[0x10000]; var totalLength = decrypt ? xor.Length : input.Length; while (xor.Position < totalLength) { var length = (int)Math.Min(0x10000, totalLength - xor.Position); if (decrypt) { xor.Read(buffer, 0, length); output.Write(buffer, 0, length); } else { input.Read(buffer, 0, length); xor.Write(buffer, 0, length); } progress.Report(new ProgressReport { Percentage = (double)xor.Position / totalLength * 100, Message = decrypt ? "Decryption..." : "Encryption...", }); } } progress.Report(new ProgressReport { Percentage = 100, Message = decrypt ? "Decryption finished." : "Encryption finished." }); return true; })); }
// ---- CONSTRUCTORS & DESTRUCTOR ------------------------------------------------------------------------------ internal VehicleInfo(Stream stream) { XorStream xorStream = new XorStream(stream, _key); DisplayName = xorStream.ReadFixedString(_maxDisplayNameLength); Name = xorStream.ReadFixedString(_maxNameLength); ImageFile1 = xorStream.ReadFixedString(_maxImageFile1Length); ImageFile2 = xorStream.ReadFixedString(_maxImageFile2Length); ImageFile3 = xorStream.ReadFixedString(_maxImageFile3Length); uint runtime = xorStream.ReadUInt32(); }
public ConnectionEntry(TcpClient client, Stream stm, bool secure) { Stream = new XorStream(stm); Client = client; Writer = new BinaryWriter(Stream); Reader = new BinaryReader(Stream); Secure = secure; }
string DecodeFile(string filePath) { string tmpFile = Path.GetTempFileName(); using (FileStream ifs = File.OpenRead(filePath)) using (var xs = new XorStream(ifs)) using (var gzs = new GZipStream(xs, CompressionMode.Decompress)) using (FileStream ofs = File.OpenWrite(tmpFile)) gzs.CopyTo(ofs); return(tmpFile); }
public IList <IArchiveFileInfo> Load(Stream input) { // Determine key _selectedKey = DetermineKey(input); if (_selectedKey == null) { throw new InvalidOperationException("Key could not be determined automatically."); } // Wrap decryption input = new XorStream(input, _selectedKey); using var br = new BinaryReaderX(input, true, ByteOrder.BigEndian); // Read names var count = br.ReadInt16(); var names = new List <string>(); for (var i = 0; i < count; i++) { var length = br.ReadInt16(); names.Add(Encoding.UTF8.GetString(br.ReadBytes(length))); } // Read sizes count = br.ReadInt16(); var sizes = br.ReadMultiple <int>(count); // Add files var result = new List <IArchiveFileInfo>(); var offset = input.Position; for (var i = 0; i < count; i++) { var name = names[i]; var size = sizes[i]; if (result.Any(x => x.FilePath.ToRelative().FullName == name)) { continue; } result.Add(new ArchiveFileInfo(new SubStream(input, offset, size), name)); offset += size; } return(result); }
public static SCUMM1File OpenDirectory(string path) { string directoryPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(path), "00.LFL"); if (!File.Exists(directoryPath)) { return(null); } // FIXME: Bit error-prone to create the file this way... XorStream stream = new XorStream(directoryPath); SCUMM1File directoryFile = new SCUMM1File(directoryPath, stream); return(directoryFile); }
string EncodeFile(string filePath) { string tmpFile = Path.GetTempFileName(); using (FileStream ofs = File.OpenWrite(tmpFile)) using (var xs = new XorStream(ofs)) using (var gzs = new GZipStream(xs, CompressionMode.Compress)) { using (FileLocker.Lock(filePath)) using (FileStream ifs = File.OpenRead(filePath)) ifs.CopyTo(gzs); } return(tmpFile); }
public void ReadBytes() { var data = Enumerable.Range(0, 256).Select(d => (byte)d).ToArray(); byte encByte = 0x73; var dataExpected = data.Select(d => d ^ encByte).Select(d => (byte)d).ToArray(); using (var ms = new MemoryStream(data)) { var stream = new XorStream(ms, encByte); var output = new byte[256]; stream.Read(output, 0, 256); Check.That(output).ContainsExactly(dataExpected); } }
private async Task DoConnect(TcpClient client, string hostname, bool text, bool tls, bool verify_tls, bool buffered) { Stream stm; _client = client; _client.NoDelay = true; if (tls) { RemoteCertificateValidationCallback validation = verify_tls ? new RemoteCertificateValidationCallback(ValidateRemoteConnection) : new RemoteCertificateValidationCallback(ValidateRemoteConnectionBypass); SslStream sslStream = new SslStream(_client.GetStream(), false, validation); int lastTimeout = sslStream.ReadTimeout; sslStream.ReadTimeout = 3000; await sslStream.AuthenticateAsClientAsync(hostname); Console.WriteLine("TLS Protocol: {0}", SslProtocolToString(sslStream.SslProtocol)); Console.WriteLine("TLS KeyEx : {0}", KeyExToString(sslStream.KeyExchangeAlgorithm)); Console.WriteLine("TLS Cipher: {0}", sslStream.CipherAlgorithm); Console.WriteLine("TLS Hash: {0}", sslStream.HashAlgorithm); Console.WriteLine("Cert Subject: {0}", sslStream.RemoteCertificate.Subject); Console.WriteLine("Cert Issuer : {0}", sslStream.RemoteCertificate.Issuer); sslStream.ReadTimeout = lastTimeout; stm = sslStream; } else { stm = _client.GetStream(); } _base_stream = new XorStream(stm); if (text) { NetworkUtils.WriteNetworkOrderInt32(_base_stream, NetworkUtils.TEXT_MAGIC); _transport = new TextNetworkTransport(_base_stream); } else { NetworkUtils.WriteNetworkOrderInt32(_base_stream, NetworkUtils.BINARY_MAGIC); _transport = new BinaryNetworkTransport(_base_stream, buffered); } }
public void Load() { string appFilePath = AppPaths.AppSettingsFilePath; #if DEBUG System.Diagnostics.Debug.Print($"Lecture du ficher {appFilePath}...\n"); #endif try { using (FileStream fs = File.OpenRead(appFilePath)) using (var xs = new XorStream(fs)) using (var gzs = new GZipStream(xs, CompressionMode.Decompress)) { var br = new BinaryReader(gzs); AppSettings.Load(br); } } catch (Exception ex) { AppContext.LogManager.LogSysError("Erreur lors du chargement des paramètrs de l'application: " + ex.Message); } string userFilePath = AppPaths.UserSettingsFilePath; #if DEBUG System.Diagnostics.Debug.Print($"Lecture du ficher {userFilePath}...\n"); #endif try { using (FileStream fs = File.OpenRead(userFilePath)) using (var xs = new XorStream(fs)) using (var gzs = new GZipStream(xs, CompressionMode.Decompress)) { var br = new BinaryReader(gzs); UserSettings.Load(br); } } catch (Exception ex) { AppContext.LogManager.LogSysError("Erreur lors du chargement des paramètrs de l'utilisateur: " + ex.Message); } }
void LoadUserSettings() { //if (!File.Exists(UserSettingsFilePath)) // return; using (FileStream fs = File.OpenRead(UserSettingsFilePath)) using (var xs = new XorStream(fs)) using (var gzs = new GZipStream(xs, CompressionMode.Decompress)) { var reader = new RawDataReader(xs, Encoding.UTF8); byte[] sign = Encoding.UTF8.GetBytes(USER_SETTINGS_SIGNATURE); for (int i = 0; i < sign.Length; ++i) { if (sign[i] != reader.ReadByte()) { throw new CorruptedFileException(UserSettingsFilePath); } } IsMaximized = reader.ReadBoolean(); int x = reader.ReadInt(); int y = reader.ReadInt(); int w = reader.ReadInt(); int h = reader.ReadInt(); FrameRectangle = new Rectangle(x, y, w, h); UseCountryCode = reader.ReadBoolean(); int mruSize = reader.ReadInt(); int mruCount = reader.ReadInt(); MRUSubHeading = new MRUList <SubHeading>(mruSize); for (int i = 0; i < mruCount; ++i) { MRUSubHeading.Add(new SubHeading(reader.ReadULong())); } AutoDetectProxy = reader.ReadBoolean(); EnableProxy = reader.ReadBoolean(); ProxyHost = reader.ReadString(); ProxyPort = reader.ReadUShort(); } }
private byte[] DetermineKey(Stream input) { foreach (var key in Keys) { using var xorStream = new XorStream(input, key) { Position = 2 }; var value = xorStream.ReadByte(); if (value == 0) { return(key); } } return(null); }
void SaveAppSettings() { if (!Directory.Exists(AppDataFolder)) { Directory.CreateDirectory(AppDataFolder); } using (FileStream fs = File.Create(AppSettingsFilePath)) using (var xs = new XorStream(fs)) using (var gzs = new GZipStream(xs, CompressionMode.Compress)) { var writer = new RawDataWriter(xs, Encoding.UTF8); writer.Write(Encoding.UTF8.GetBytes(APP_SETTINGS_SIGNATURE)); writer.Write(m_dataGeneration); writer.Write(m_updateKey); } }
public static CpkTable Create(Stream input, long offset) { input.Position = offset; using var br = new BinaryReaderX(input, true); // Read table header var header = br.ReadType <CpkTableHeader>(); // Create UTF stream Stream utfStream = new SubStream(input, offset + 0x10, header.packetSize); if (header.IsEncrypted) { utfStream = new XorStream(utfStream, XorKey); } return(Create(utfStream, header.magic)); }
// ---- CONSTRUCTORS & DESTRUCTOR ------------------------------------------------------------------------------ internal CircuitInfo(Stream stream) { XorStream xorStream = new XorStream(stream, _key); Name = xorStream.ReadFixedString(_maxNameLength); DisplayName = xorStream.ReadFixedString(_maxDisplayNameLength); ImageFile1 = xorStream.ReadFixedString(_maxImageFile1Length); ImageFile2 = xorStream.ReadFixedString(_maxImageFile2Length); ImageFile3 = xorStream.ReadFixedString(_maxImageFile3Length); Flags = (CircuitFlags)xorStream.ReadByte(); Version = (byte)xorStream.ReadByte(); ID = (byte)xorStream.ReadByte(); byte alignment1 = (byte)xorStream.ReadByte(); Length = xorStream.ReadInt32(); Laps = (byte)xorStream.ReadByte(); Level = (byte)xorStream.ReadByte(); ushort alignment2 = xorStream.ReadUInt16(); uint runtime = xorStream.ReadUInt32(); }
public void Save() { string appFilePath = AppPaths.AppSettingsFilePath; using (FileStream fs = File.Create(appFilePath)) using (var xs = new XorStream(fs)) using (var gzs = new GZipStream(xs, CompressionMode.Compress)) { var bw = new BinaryWriter(gzs); AppSettings.Save(bw); } string userFilePath = AppPaths.UserSettingsFilePath; using (FileStream fs = File.Create(userFilePath)) using (var xs = new XorStream(fs)) using (var gzs = new GZipStream(xs, CompressionMode.Compress)) { var bw = new BinaryWriter(gzs); UserSettings.Save(bw); } }
public SCUMM3File(string path, XorStream stream) : base(path, stream) { }
protected SRXORFile(string path, XorStream stream) : base(path, stream) { this.xorStream = stream; }
private static void DecodeInternal(Stream input, Stream output, DecodingCodeTreeNode codeTree, ushort numberOfTiles, bool xorOutput) { UInt8_E_L_InputBitStream inputBits = new UInt8_E_L_InputBitStream(input); UInt8_E_L_OutputBitStream outputBits; XorStream xorStream = null; try { if (xorOutput) { xorStream = new XorStream(output); outputBits = new UInt8_E_L_OutputBitStream(xorStream); } else { outputBits = new UInt8_E_L_OutputBitStream(output); } // The output is: number of tiles * 0x20 (1 << 5) bytes per tile * 8 (1 << 3) bits per byte int outputSize = numberOfTiles << 8; // in bits int bitsWritten = 0; DecodingCodeTreeNode currentNode = codeTree; while (bitsWritten < outputSize) { NibbleRun nibbleRun = currentNode.NibbleRun; if (nibbleRun.Count == 0xFF) { // Bit pattern 0b111111; inline RLE. // First 3 bits are repetition count, followed by the inlined nibble. byte count = (byte)(inputBits.Read(3) + 1); byte nibble = inputBits.Read(4); DecodeNibbleRun(inputBits, outputBits, count, nibble, ref bitsWritten); currentNode = codeTree; } else if (nibbleRun.Count != 0) { // Output the encoded nibble run DecodeNibbleRun(inputBits, outputBits, nibbleRun.Count, nibbleRun.Nibble, ref bitsWritten); currentNode = codeTree; } else { // Read the next bit and go down one level in the tree currentNode = currentNode[inputBits.Get()]; if (currentNode == null) { throw new CompressionException(Properties.Resources.InvalidCode); } } } outputBits.Flush(false); } finally { if (xorStream != null) { xorStream.Dispose(); } } }