/// <summary> /// Converts sntp message into string object. /// </summary> public override string ToString() { string dateFormat = "MMM d, yyyy HH:mm:ss.fff 'GMT'"; StringBuilder sb = new StringBuilder(); sb.AppendLine(); sb.AppendLine(" SNTP PACKET"); sb.AppendLine(String.Concat(" Message Timestamp : ", this.Timestamp.ToString())); sb.AppendLine(String.Concat(" Leap Indicator (LI) : ", LeapIndicatorString.GetName(this.LeapIndicator))); sb.AppendLine(String.Concat(" Version Number (VI) : ", VersionNumberString.GetName(this.VersionNumber))); sb.AppendLine(String.Concat(" Mode : ", ModeString.GetName(this.Mode))); sb.AppendLine(String.Concat(" Stratum : ", StratumString.GetName(this.Stratum))); sb.AppendLine(String.Concat(" Poll Interval : ", this.PollInterval.ToString(), " second(s)")); sb.AppendLine(String.Concat(" Precision : ", this.Precision.ToString(), " second(s)")); sb.AppendLine(String.Concat(" Root Delay : ", this.RootDelay.ToString(), " second(s)")); sb.AppendLine(String.Concat(" Root Dispersion : ", this.RootDispersion.ToString(), " second(s)")); sb.AppendLine(String.Concat(" Reference Identifier : ", ReferenceIdentifierString.GetName(this.ReferenceIdentifier))); sb.AppendLine(String.Concat(" Reference IP Address : ", this.ReferenceIPAddress.ToString())); sb.AppendLine(String.Concat(" Reference DateTime : ", this.ReferenceDateTime.ToString(dateFormat))); sb.AppendLine(String.Concat(" Originate DateTime : ", this.OriginateDateTime.ToString(dateFormat))); sb.AppendLine(String.Concat(" Receive DateTime : ", this.ReceiveDateTime.ToString(dateFormat))); sb.AppendLine(String.Concat(" Transmit DateTime : ", this.TransmitDateTime.ToString(dateFormat))); sb.AppendLine(String.Concat(" Destination DateTime : ", this.DestinationDateTime.ToString(dateFormat))); sb.AppendLine(String.Concat(" Local DateTime : ", this.LocalDateTime.ToString(dateFormat), "(", TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).ToString(), ")")); sb.AppendLine(String.Concat(" Local Clock Offset : ", this.LocalClockOffset.ToString(), " second(s)")); sb.AppendLine(String.Concat(" Round Trip Delay : ", this.RoundTripDelay.ToString(), " second(s)")); sb.AppendLine(String.Concat(" Key Identifier : ", ByteUtility.PrintBytes(_keyIdentifier, false))); sb.AppendLine(String.Concat(" Message Digest : ", ByteUtility.PrintBytes(_messageDigest, false))); sb.AppendLine(); return(sb.ToString()); }
private void OnReceive(IAsyncResult ar) { if (!this.bool_0) { try { int num = 0; try { num = base.EndReceive(ar); } catch { this.method_1(); return; } if (num < 0) { this.method_1(); } else { byte[] array = ByteUtility.ChompBytes(this.Buffer, 0, num); this.method_8(ref array); this.BeginReceive(); } } catch { this.method_1(); } } }
private void DataReceived(IAsyncResult iasyncResult_0) { if (!this.bool_0) { try { int num = 0; try { num = base.EndReceive(iasyncResult_0); } catch { this.method_1(); return; } if (num > 0) { byte[] array = ByteUtility.ChompBytes(this.mDataBuffer, 0, num); this.method_8(ref array); this.WaitForData(); } else { this.method_1(); } } catch { this.method_1(); } } }
/// <summary> /// Removes the preamble information (if present) from the specified <see cref="Stream"/>, and <paramref name="source"/> is being closed and disposed. /// </summary> /// <param name="source">The input <see cref="Stream"/> to process.</param> /// <param name="encoding">The encoding to use when determining the preamble to remove.</param> /// <returns>A <see cref="Stream"/> without preamble information.</returns> public static Stream RemovePreamble(Stream source, Encoding encoding) { Validator.ThrowIfNull(source, nameof(source)); byte[] bytes = ByteConverter.FromStream(source); bytes = ByteUtility.RemovePreamble(bytes, encoding); MemoryStream output; MemoryStream tempOutput = null; try { tempOutput = new MemoryStream(bytes); tempOutput.Position = 0; output = tempOutput; tempOutput = null; } finally { if (tempOutput != null) { tempOutput.Dispose(); } using (source) // because we return a stream, close the source { } } output.Position = 0; return(output); }
private void parseBody() { packageNum = ByteUtility.GetSubByte(this.body, 0, 1); response = ByteUtility.GetSubByte(this.body, 1, 1); packageCheck = ByteUtility.GetSubByte(this.body, 2, 1); this.CheckValid(); }
private void parse() { this.start = ByteUtility.GetSubByte(this.source, 0, 4); this.body = ByteUtility.GetSubByte(this.source, 4, 25); this.end = ByteUtility.GetSubByte(this.source, 29, 3); this.parseBody(); }
private DataBlock CreateParsedDataBlock(byte[] replayBytes, int currIndex, out int movedIndex) { DataBlock dataBlock = new DataBlock(); if (currIndex >= replayBytes.Length) { movedIndex = currIndex; return null; } ushort compressedDataBlockSize = ByteUtility.ReadWord(replayBytes, currIndex); currIndex += 2; ushort decompressedDataBlockSize = ByteUtility.ReadWord(replayBytes, currIndex); currIndex += 2; uint checkSum = ByteUtility.ReadDoubleWord(replayBytes, currIndex); currIndex += 4; byte[] compressedDataBlockBytes = replayBytes.SubArray(currIndex, compressedDataBlockSize); byte[] decompressedDataBlockBytes = Ionic.Zlib.ZlibStream.UncompressBuffer(compressedDataBlockBytes); dataBlock.CompressedDataBlockSize = compressedDataBlockSize; dataBlock.DecompressedDataBlockSize = decompressedDataBlockSize; dataBlock.CheckSum = checkSum; dataBlock.CompressedDataBlockBytes = compressedDataBlockBytes; dataBlock.DecompressedDataBlockBytes = decompressedDataBlockBytes; currIndex += compressedDataBlockSize; movedIndex = currIndex; return dataBlock; }
public ulong BytesToInt(byte[] Data) { return(ByteUtility.getUInt64Segment( ByteUtility.ByteToUInt64(Data), (int)(BitOffset), (int)(BitOffset + BitSize) )); }
public void TestToHexDigit() { Assert.AreEqual((byte)0x68, ByteUtility.ToHexDigit(68)); Assert.AreEqual((byte)0x27, ByteUtility.ToHexDigit(27)); Assert.AreEqual((byte)0x93, ByteUtility.ToHexDigit(93)); Assert.AreEqual((byte)0x40, ByteUtility.ToHexDigit(40)); Assert.AreEqual((byte)0x08, ByteUtility.ToHexDigit(08)); }
private void parseBody() { packageNum = ByteUtility.GetSubByte(this.body, 0, 1); dataLength = ByteUtility.GetSubByte(this.body, 1, 2); data = ByteUtility.GetSubByte(this.body, 3, 512); packageCheck = ByteUtility.GetSubByte(this.body, 515, 1); this.CheckValid(); }
public void TestFromHexDigit() { Assert.AreEqual((byte)68, ByteUtility.FromHexDigit(0x68)); Assert.AreEqual((byte)27, ByteUtility.FromHexDigit(0x27)); Assert.AreEqual((byte)93, ByteUtility.FromHexDigit(0x93)); Assert.AreEqual((byte)40, ByteUtility.FromHexDigit(0x40)); Assert.AreEqual((byte)08, ByteUtility.FromHexDigit(0x08)); }
public void RoundTrip(string input, byte[] expected) { byte[] actual = ByteUtility.ToBytes(input); CollectionAssert.AreEqual(expected, actual); string output = ByteUtility.ToString(actual); Assert.AreEqual(input.ToUpperInvariant(), output); }
public void MakeReverse() { fileLength = ByteUtility.MakeReverse(fileLength); check1 = ByteUtility.MakeReverse(check1); check2 = ByteUtility.MakeReverse(check2); check3 = ByteUtility.MakeReverse(check3); nPackageNum = ByteUtility.MakeReverse(nPackageNum); newVersion = ByteUtility.MakeReverse(newVersion); reserve = ByteUtility.MakeReverse(reserve); }
/// <summary> /// Generate a HA1 hash /// </summary> /// <param name="realm">Realm that the user want to authenticate in</param> /// <param name="userName">User Name</param> /// <param name="password">Password</param> /// /// <para> /// A HA1 hash is simply a Md5 encoded string: "UserName:Realm:Password". The quotes should /// not be included. Realm is the currently requested Host (as in <c>Request.Headers["host"]</c>). /// </para> /// <returns></returns> private string Encode(string realm, string userName, string password) { string toHash = String.Concat(userName, ":", realm, ":", password); KeyedHashAlgorithm crypto = new KeyedHashAlgorithm(KeyedHashAlgorithmType.HMACMD5); byte[] value = crypto.ComputeHash(Encoding.UTF8.GetBytes(toHash)); return(ByteUtility.GetString(value)); }
private static void AssignAddress(byte[] dltData, long address) { for (var i = 1; i <= 6; ++i) { var twoDigit = (byte)(address % 100); var hexDigit = ByteUtility.ToHexDigit(twoDigit); dltData[i] = hexDigit; address /= 100; } }
public void ToHexAndFromHex() { Random rand = new Random((int)DateTime.Now.Ticks); var testData = new byte[1024]; rand.NextBytes(testData); Assert.Equal(testData, ByteUtility.FromHex(ByteUtility.ToHex(testData))); }
private void parseBody() { updataStatus = ByteUtility.GetSubByte(this.body, 0, 1); packageFlag = ByteUtility.GetSubByte(this.body, 1, 16); currentVersion = ByteUtility.GetSubByte(this.body, 17, 2); newVersion = ByteUtility.GetSubByte(this.body, 19, 2); updataResult = ByteUtility.GetSubByte(this.body, 21, 1); bootVersion = ByteUtility.GetSubByte(this.body, 22, 2); packageCheck = ByteUtility.GetSubByte(this.body, 24, 1); this.CheckValid(); }
/// <summary> /// Writes the XAML from specified EMF input stream. /// </summary> /// <param name="input">The input.</param> /// <param name="output">The output.</param> public override void ToXaml(Stream input, XmlWriter output) { if (input == null) { throw new ArgumentNullException("input"); } byte[] header; if (!ByteUtility.TryRead(input, 40, out header) || ReadUInt32(header, 0) != 0x9ac6cdd7) { throw new ConverterException(Resources.ExceptionNoEmfStream); } // EMF special header short handle = ReadInt16(header, 4); short left = ReadInt16(header, 6); short top = ReadInt16(header, 8); short right = ReadInt16(header, 10); short bottom = ReadInt16(header, 12); short twipsPerInch = ReadInt16(header, 14); int reserved = ReadInt32(header, 16); short checksum = ReadInt16(header, 20); // EMF meta header short fileType = ReadInt16(header, 22); short headerSize = ReadInt16(header, 24); short version = ReadInt16(header, 26); int fileSize = ReadInt32(header, 28); short numberOfObjects = ReadInt16(header, 32); int maxRecordSize = ReadInt32(header, 34); short noParameters = ReadInt16(header, 38); EmfContext context = new EmfContext(); double width = right - left; double height = bottom - top; context.ViewPortExt = new Point(width, height); context.Scale = 1D / 15D * 1440 / twipsPerInch; // converts twips to pixels WriteStartElement(output, "Canvas"); WriteAttribute(output, "Width", width * context.Scale); WriteAttribute(output, "Height", height * context.Scale); WriteAttribute(output, "HorizontalAlignment", "Left"); WriteAttribute(output, "VerticalAlignment", "Top"); while (ReadRecord(input, context, output)) { ; } WriteEndElement(output); }
private void DataReceived(IAsyncResult iAr) { // Connection not stopped yet? if (this.Alive == false) { return; } // Do an optional wait before processing the data if (RECEIVEDATA_MILLISECONDS_DELAY > 0) { Thread.Sleep(RECEIVEDATA_MILLISECONDS_DELAY); } // How many bytes has server received? int numReceivedBytes = 0; try { numReceivedBytes = mSocket.EndReceive(iAr); } catch (ObjectDisposedException) { ConnectionDead(); return; } catch (Exception ex) { AleedaEnvironment.GetLog().WriteUnhandledExceptionError("IonTcpConnection.DataReceived", ex); ConnectionDead(); return; } if (numReceivedBytes > 0) { // Copy received data buffer byte[] dataToProcess = ByteUtility.ChompBytes(mDataBuffer, 0, numReceivedBytes); // Decipher received data? if (mEncryptionStarted) { dataToProcess = mRc4.Decipher(dataToProcess, numReceivedBytes); } // Route data to GameClient to parse and process messages RouteData(ref dataToProcess); //Environment.GetHabboHotel().GetClients().GetClient(this.ID).HandleConnectionData(ref dataToProcess); } // Wait for new data WaitForData(); }
public override string ToString() { string response = "CID: " + this.ClientId.ToString() + " | SESID: " + this.SessionId.ToHexString("0x") + " | IP: " + this.Address.ToString() + " | OWNER: " + this.Owner.ToString() + " | NAME: " + ByteUtility.GetSafeString(_hostName) + " | EXPN: " + this.Expiration.ToLocalTime().ToString() + " | STATE: " + LeaseStateString.GetName(_state); return(response); }
/// <summary> /// Validates the value. /// </summary> /// <param name="value">The value.</param> /// <param name="nullAllowed">if set to <c>true</c> [null allowed].</param> /// <param name="encoding">The encoding.</param> /// <param name="minLength">The minimum number of bytes when encoded using specified encoding.</param> /// <param name="maxLength">The maximum number of bytes when encoded using specified encoding.</param> public static void ValidateValue(string value, bool nullAllowed, Encoding encoding, int minLength, int maxLength) { if (!nullAllowed || value != null) { int length = ByteUtility.GetByteCount(encoding, value); if (length < minLength || length > maxLength) { throw new ArgumentOutOfRangeException(StringUtility.Format(Resources.ExceptionStringLength, value, minLength, maxLength)); } } }
private void CheckValid() { if (!ByteUtility.Compares(start, System.Text.Encoding.Default.GetBytes("QSW:"))) { return; } if (!ByteUtility.Compares(end, System.Text.Encoding.Default.GetBytes("END"))) { return; } isValid = true; }
public TeamCharacterStatus(byte[] data) { var byteOffset = 0; var id = ByteUtility.GetInt(data, ref byteOffset); var name = ByteUtility.GetString(data, ref byteOffset); var rank = ByteUtility.GetShort(data, ref byteOffset); var lastOnline = ByteUtility.GetInt(data, ref byteOffset); this.Character = new TeamCharacter { Id = id, Name = name, Rank = rank, LastOnline = lastOnline }; }
private static byte[] CryptoTransformCore(byte[] value, byte[] key, byte[] initializationVector, AdvancedEncryptionStandardCommand command) { ValidateInput(value, key, initializationVector); byte[] output = null; using (Aes rijndael = Aes.Create()) { rijndael.BlockSize = BlockSize; rijndael.Key = key; rijndael.IV = initializationVector; rijndael.Padding = PaddingMode.PKCS7; rijndael.Mode = CipherMode.CBC; MemoryStream tempStream = null; CryptoStream cryptoStream = null; try { switch (command) { case AdvancedEncryptionStandardCommand.Decrypt: tempStream = new MemoryStream(value); cryptoStream = new CryptoStream(tempStream, rijndael.CreateDecryptor(), CryptoStreamMode.Read); output = new byte[value.Length]; cryptoStream.Read(output, 0, output.Length); tempStream = null; output = ByteUtility.RemoveTrailingZeros(output); break; case AdvancedEncryptionStandardCommand.Encrypt: tempStream = new MemoryStream(); cryptoStream = new CryptoStream(tempStream, rijndael.CreateEncryptor(), CryptoStreamMode.Write); cryptoStream.Write(value, 0, value.Length); cryptoStream.FlushFinalBlock(); output = tempStream.ToArray(); tempStream = null; break; } } finally { if (cryptoStream != null) { cryptoStream.Dispose(); } if (tempStream != null) { tempStream.Dispose(); } } } return(output); }
/// <summary> /// Authorize a request. /// </summary> /// <param name="request">Request being authenticated</param> /// <returns>Authenticated user if successful; otherwise null.</returns> public string Authenticate(IHttpContext context) { string authHeader = context.Request.Headers["Authorization"]; if (authHeader == null) { return(null); } authHeader = authHeader.Replace("Basic ", string.Empty); string decoded = ByteUtility.GetString(Convert.FromBase64String(authHeader)); int pos = decoded.IndexOf(':'); if (pos == -1) { Logger.WriteDebug(this, "Invalid basic authentication header, failed to find colon. Header: " + authHeader); return(null); } string password = decoded.Substring(pos + 1, decoded.Length - pos - 1); string userName = decoded.Substring(0, pos); var user = _userService.Lookup(userName, context.Request.Uri); if (user == null) { return(null); } if (user.Password == null) { string ha1 = Encode(context.Request.Uri.Host, userName, password); if (ha1 != user.HA1) { Logger.WriteInfo(this, "Incorrect user name or password. User Name: " + user.Username); return(null); } } else { if (userName != user.Username || password != user.Password) { Logger.WriteInfo(this, "Incorrect user name or password. User Name: " + user.Username); return(null); } } return(user.Username); }
private void parseBody() { fileType = ByteUtility.GetSubByte(body, 0, 1); fileLength = ByteUtility.GetSubByte(body, 1, 2); check1 = ByteUtility.GetSubByte(body, 3, 2); check2 = ByteUtility.GetSubByte(body, 5, 2); check3 = ByteUtility.GetSubByte(body, 7, 4); nPackageNum = ByteUtility.GetSubByte(body, 11, 2); newVersion = ByteUtility.GetSubByte(body, 13, 2); reserve = ByteUtility.GetSubByte(body, 15, 2); packageCheck = ByteUtility.GetSubByte(body, 17, 1); this.CheckValid(); }
private static long ParseAddress(byte[] dltData) { var address = 0L; for (var i = 6; i >= 1; --i) { var twoDigit = ByteUtility.FromHexDigit(dltData[i]); address *= 100; address += twoDigit; } return(address); }
/// <summary> /// 对比SSW数据包 /// </summary> private static void AnalyzeSSW(SSW_Send bin, List <SSW_Send> comList) { Console.ForegroundColor = ConsoleColor.Red; for (int i = 0; i < comList.Count; i++) { if (!ByteUtility.Compares(bin.body, comList[i].body)) { Console.WriteLine("SSW Package ERROR: [{0}]", i); } } Console.ResetColor(); Console.WriteLine("Analyzed SSW Packages Done! Totle count : {0}\n", comList.Count); }
public void ToHash() { var path = Guid.NewGuid().ToString() + ".txt"; using (var stream = File.CreateText(path)) { stream.Write("1234"); } Assert.Equal(ByteUtility.FromHex("81dc9bdb52d04dc20036dbd8313ed055"), new FileInfo(path).ToHash <MD5>()); System.IO.File.Delete(path); }
public CharacterList(byte[] data) { // TODO[CJ] Clean up var characters = new List <Character>(); var byteOffset = 0; var characterCount = BitConverter.ToInt16(data, byteOffset); byteOffset += sizeof(short); for (var i = 0; i < characterCount; ++i) { if (byteOffset < data.Length) { var id = ByteUtility.GetInt(data, ref byteOffset); var name = ByteUtility.GetString(data, ref byteOffset); var unknown1 = ByteUtility.GetInt(data, ref byteOffset); var unknown2 = ByteUtility.GetInt(data, ref byteOffset); var unknown3 = ByteUtility.GetInt(data, ref byteOffset); var className = ByteUtility.GetString(data, ref byteOffset); var unknown4 = ByteUtility.GetInt(data, ref byteOffset); if (byteOffset < data.Length) { var hasSkins = ByteUtility.GetBoolean(data, ref byteOffset); if (hasSkins) { var skinCount = ByteUtility.GetInt(data, ref byteOffset); for (var j = 0; j < skinCount; ++j) { var unknown5 = ByteUtility.GetByte(data, ref byteOffset); var skinName = ByteUtility.GetString(data, ref byteOffset); var skinName2 = ByteUtility.GetString(data, ref byteOffset); var unknown6 = ByteUtility.GetLong(data, ref byteOffset); var unknown7 = ByteUtility.GetByte(data, ref byteOffset); for (var k = 0; k < 6; ++k) { var skinFile = ByteUtility.GetString(data, ref byteOffset); } } } } characters.Add(new Character { Id = id, Name = name }); } } var test = ByteUtility.ByteArrayToHexString(data); this.Characters = characters.ToArray(); }