System.Text.Encoding.GetString(byte[], int, int)

Here are the examples of the csharp api System.Text.Encoding.GetString(byte[], int, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

6116 Examples 7

19 View Source File : QQUser.cs
License : MIT License
Project Creator : 499116344

public GroupMembers Search_Group_Members(long externalId)
        {
            try
            {
                using (var httpWebClient = new HttpWebClient())
                {
                    var address = "https://qun.qq.com/cgi-bin/qun_mgr/search_group_members";
                    var s = $"gc={externalId}&st=0&end=10000&sort=0&bkn={Bkn}";
                    httpWebClient.Headers["Accept"] = "application/json, text/javascript, */*; q=0.01";
                    httpWebClient.Headers["Referer"] = "http://qun.qq.com/member.html";
                    httpWebClient.Headers["X-Requested-With"] = "XMLHttpRequest";
                    httpWebClient.Headers.Add("Cache-Control: no-cache");
                    httpWebClient.Headers["User-Agent"] = _ua;
                    httpWebClient.Cookies = QunCookies;
                    var text = Encoding.UTF8.GetString(httpWebClient.UploadData(address, "POST",
                        Encoding.UTF8.GetBytes(s)));

                    var r = new Regex("\"[0-9]+\":\"[^\"]+\"");
                    if (r.IsMatch(text))
                    {
                        foreach (var match in r.Matches(text))
                        {
                            var str = ((Capture) match).Value.Split(':');
                            var r2 = new Regex("\"[0-9]+\"");
                            var level = r2.Matches(str[0])[0].Value;
                            var r3 = new Regex("\"[^\"]+\"");
                            var name = r3.Matches(str[1])[0].Value;
                            var dataItem = "{\"level\":" + level + ",\"name\":" + name + "}";

                            text = text.Replace(((Capture) match).Value, dataItem);
                        }

                        text = text.Replace("\"levelname\":{", "\"levelname\":[")
                            .Replace("},\"max_count\"", "],\"max_count\"");
                    }

                    MessageLog($"获取群{externalId}成员列表成功:{(text.Length > 200 ? text.Substring(0, 200) : text)}");
                    return JsonConvert.DeserializeObject<GroupMembers>(text);
                }
            }
            catch (Exception ex)
            {
                MessageLog($"获取群{externalId}成员列表失败:{ex.Message}");
            }

            return null;
        }

19 View Source File : Amf3Reader.cs
License : MIT License
Project Creator : a1q123456

private bool TryGetStringImpl<T>(Span<byte> objectBuffer, List<T> referenceTable, out string value, out int consumed) where T : clreplaced
        {
            value = default;
            consumed = default;
            if (!TryGetU29Impl(objectBuffer, out var header, out int headerLen))
            {
                return false;
            }
            if (!TryGetReference(header, _stringReferenceTable, out var headerData, out string refValue, out var isRef))
            {
                return false;
            }
            if (isRef)
            {
                value = refValue;
                consumed = headerLen;
                return true;
            }

            var strLen = (int)headerData;
            if (objectBuffer.Length - headerLen < strLen)
            {
                return false;
            }

            value = Encoding.UTF8.GetString(objectBuffer.Slice(headerLen, strLen));
            consumed = headerLen + strLen;
            if (value.Any())
            {
                referenceTable.Add(value as T);
            }
            
            return true;
        }

19 View Source File : HttpUtil.cs
License : Apache License 2.0
Project Creator : 214175590

public string GetString(Encoding coding)
        {
            StringBuilder str = new StringBuilder();
            Stream sr = ResponseContent;
            sr.Seek(0, SeekOrigin.Begin);
            byte[] data = new byte[1024 * 1024];
            int readcount = sr.Read(data, 0, data.Length);
            while (readcount > 0)
            {
                str.Append(coding.GetString(data, 0, readcount));
                readcount = sr.Read(data, 0, data.Length);
            }
            return str.ToString();
        }

19 View Source File : NTLM.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 3gstudent

public void Parse(RdpPacket packet)
            {
                NTLM.AV_ID av_id;
                byte[] buffer = null;
                do
                {
                    av_id = (NTLM.AV_ID) packet.ReadLittleEndian16();
                    int count = packet.ReadLittleEndian16();
                    if (count > 0)
                    {
                        if (av_id != NTLM.AV_ID.MsvAvFlags)
                        {
                            buffer = new byte[count];
                            packet.Read(buffer, 0, count);
                        }
                        else
                        {
                            this.Flags = packet.ReadLittleEndian32();
                        }
                    }
                    switch (av_id)
                    {
                        case NTLM.AV_ID.MsvAvNbComputerName:
                            this.NbComputerName.length = count;
                            this.NbComputerName.value = buffer;
                            this.sNbComputerName = Encoding.Unicode.GetString(this.NbComputerName.value, 0, this.NbComputerName.value.Length);
                            break;

                        case NTLM.AV_ID.MsvAvNbDomainName:
                            this.NbDomainName.length = count;
                            this.NbDomainName.value = buffer;
                            this.sNbDomainName = Encoding.Unicode.GetString(this.NbDomainName.value, 0, this.NbDomainName.value.Length);
                            break;

                        case NTLM.AV_ID.MsvAvDnsComputerName:
                            this.DnsComputerName.length = count;
                            this.DnsComputerName.value = buffer;
                            this.sDnsComputerName = Encoding.Unicode.GetString(this.DnsComputerName.value, 0, this.DnsComputerName.value.Length);
                            break;

                        case NTLM.AV_ID.MsvAvDnsDomainName:
                            this.DnsDomainName.length = count;
                            this.DnsDomainName.value = buffer;
                            this.sDnsDomainName = Encoding.Unicode.GetString(this.DnsDomainName.value, 0, this.DnsDomainName.value.Length);
                            break;

                        case NTLM.AV_ID.MsvAvDnsTreeName:
                            this.DnsTreeName.length = count;
                            this.DnsTreeName.value = buffer;
                            break;

                        case NTLM.AV_ID.MsvAvTimestamp:
                            this.Timestamp.length = count;
                            this.Timestamp.value = buffer;
                            break;

                        case NTLM.AV_ID.MsvAvRestrictions:
                            this.Restrictions.length = count;
                            this.Restrictions.value = buffer;
                            break;

                        case NTLM.AV_ID.MsvAvTargetName:
                            this.TargetName.length = count;
                            this.TargetName.value = buffer;
                            break;

                        case NTLM.AV_ID.MsvChannelBindings:
                            this.ChannelBindings.length = count;
                            this.ChannelBindings.value = buffer;
                            break;
                    }
                }
                while (av_id != NTLM.AV_ID.MsvAvEOL);
            }

19 View Source File : CSRedisClientHashTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
		public void HMSet() {
			replacedert.True(rds.HMSet("TestHMSet", "string1", base.String, "bytes1", base.Bytes, "clreplaced1", base.Clreplaced, "clreplaced1array", new[] { base.Clreplaced, base.Clreplaced }));
			replacedert.Equal(4, rds.HMGet("TestHMSet", "string1", "bytes1", "clreplaced1", "clreplaced1array").Length);
			replacedert.Contains(base.String, rds.HMGet("TestHMSet", "string1", "bytes1", "clreplaced1", "clreplaced1array"));
			replacedert.Contains(Encoding.UTF8.GetString(base.Bytes), rds.HMGet("TestHMSet", "string1", "bytes1", "clreplaced1", "clreplaced1array"));
			replacedert.Contains(base.Clreplaced.ToString(), rds.HMGet("TestHMSet", "string1", "bytes1", "clreplaced1", "clreplaced1array"));

		}

19 View Source File : TripleDesEncrypt.cs
License : MIT License
Project Creator : 17MKH

private string Decrypt(string decryptString, string key, bool hex)
    {
        if (decryptString.IsNull())
            return null;
        if (key.IsNull())
            key = KEY;

        var keyBytes = Encoding.UTF8.GetBytes(key);
        var encryptBytes = hex ? decryptString.Hex2Bytes() : Convert.FromBase64String(decryptString);
        var provider = new DESCryptoServiceProvider
        {
            Key = keyBytes,
            Mode = CipherMode.ECB,
            Padding = PaddingMode.PKCS7
        };

        using var mStream = new MemoryStream();
        using var cStream = new CryptoStream(mStream, provider.CreateDecryptor(), CryptoStreamMode.Write);
        cStream.Write(encryptBytes, 0, encryptBytes.Length);
        cStream.FlushFinalBlock();
        return Encoding.UTF8.GetString(mStream.ToArray());
    }

19 View Source File : QQUser.cs
License : MIT License
Project Creator : 499116344

public FriendList Get_Friend_List()
        {
            try
            {
                using (var httpWebClient = new HttpWebClient())
                {
                    var address = "https://qun.qq.com/cgi-bin/qun_mgr/get_friend_list";
                    var s = $"bkn={Bkn}";
                    httpWebClient.Headers["Accept"] = "application/json, text/javascript, */*; q=0.01";
                    httpWebClient.Headers["Referer"] = "http://qun.qq.com/member.html";
                    httpWebClient.Headers["X-Requested-With"] = "XMLHttpRequest";
                    httpWebClient.Headers["User-Agent"] = _ua;
                    httpWebClient.Headers.Add("Cache-Control: no-cache");
                    httpWebClient.Cookies = QunCookies;
                    var text = Encoding.UTF8.GetString(httpWebClient.UploadData(address, "POST",
                        Encoding.UTF8.GetBytes(s)));
                    var r = new Regex("\"[0-9]+\":");
                    if (r.IsMatch(text))
                    {
                        foreach (var match in r.Matches(text))
                        {
                            var str = ((Capture) match).Value;
                            text = text.Replace(str, "");
                        }

                        text = text.Replace("\"result\":{{", "\"result\":[{").Replace("\"}}}", "\"}]}");
                    }

                    MessageLog("获取好友列表成功:" + text);
                    return JsonConvert.DeserializeObject<FriendList>(text);
                }
            }
            catch (Exception ex)
            {
                MessageLog("获取好友列表失败:" + ex.Message);
            }

            return null;
        }

19 View Source File : EndianBinaryReader.cs
License : MIT License
Project Creator : 0xC0000054

public AvifContainer.BoxString ReadBoxString(long endOffset)
        {
            if (endOffset < 0)
            {
                ExceptionUtil.ThrowArgumentOutOfRangeException(nameof(endOffset));
            }

            VerifyNotDisposed();

            AvifContainer.BoxString result;

            int length = GetStringLength(endOffset, out bool hasNullTerminator);

            if (length == 0)
            {
                result = AvifContainer.BoxString.Empty;
            }
            else
            {
                if (length < this.bufferSize)
                {
                    EnsureBuffer(length);

                    result = System.Text.Encoding.UTF8.GetString(this.buffer, this.readOffset, length);

                    this.readOffset += length;
                }
                else
                {
                    using (IArrayPoolBuffer<byte> bytes = this.arrayPool.Rent<byte>(length))
                    {
                        ProperRead(bytes.Array, 0, bytes.RequestedLength);

                        result = System.Text.Encoding.UTF8.GetString(bytes.Array, 0, bytes.RequestedLength);
                    }
                }
            }

            if (hasNullTerminator)
            {
                this.Position++; // Skip the null-terminator if one was found at the end of the string.
            }

            return result;
        }

19 View Source File : Amf0Reader.cs
License : MIT License
Project Creator : a1q123456

internal bool TryGetStringImpl(Span<byte> buffer, int lengthOfLengthField, out string value, out int consumedLength)
        {
            value = default;
            consumedLength = default;
            var stringLength = 0;
            if (lengthOfLengthField == Amf0CommonValues.STRING_HEADER_LENGTH)
            {
                stringLength = (int)NetworkBitConverter.ToUInt16(buffer);
            }
            else
            {
                stringLength = (int)NetworkBitConverter.ToUInt32(buffer);
            }

            if (buffer.Length - lengthOfLengthField < stringLength)
            {
                return false;
            }

            value = Encoding.UTF8.GetString(buffer.Slice(lengthOfLengthField, stringLength));
            consumedLength = lengthOfLengthField + stringLength;
            return true;
        }

19 View Source File : EndianBinaryReader.cs
License : MIT License
Project Creator : 0xC0000054

public string ReadAsciiString(int length)
        {
            if (length < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(length));
            }
            VerifyNotDisposed();

            if (length == 0)
            {
                return string.Empty;
            }

            EnsureBuffer(length);

            string value = System.Text.Encoding.ASCII.GetString(buffer, readOffset, length);

            readOffset += length;

            return value;
        }

19 View Source File : HashesTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
        public void HMSet()
        {
            cli.Del("TestHMSet");
            cli.HMSet("TestHMSet", "string1", base.String, "bytes1", base.Bytes, "clreplaced1", base.Clreplaced, "clreplaced1array", new[] { base.Clreplaced, base.Clreplaced });
            replacedert.Equal(4, cli.HMGet("TestHMSet", "string1", "bytes1", "clreplaced1", "clreplaced1array").Length);
            replacedert.Contains(base.String, cli.HMGet("TestHMSet", "string1", "bytes1", "clreplaced1", "clreplaced1array"));
            replacedert.Contains(Encoding.UTF8.GetString(base.Bytes), cli.HMGet("TestHMSet", "string1", "bytes1", "clreplaced1", "clreplaced1array"));
            replacedert.Contains(JsonConvert.SerializeObject(base.Clreplaced), cli.HMGet("TestHMSet", "string1", "bytes1", "clreplaced1", "clreplaced1array"));
        }

19 View Source File : CSRedisCache.cs
License : MIT License
Project Creator : 2881099

private byte[] GetAndRefresh(string key, bool getData) {
			if (key == null) {
				throw new ArgumentNullException(nameof(key));
			}

			// This also resets the LRU status as desired.
			// TODO: Can this be done in one operation on the server side? Probably, the trick would just be the DateTimeOffset math.
			object[] results;
			byte[] value = null;
			if (getData) {
				var ret = _redisClient.HMGet<byte[]>(key, AbsoluteExpirationKey, SlidingExpirationKey, DataKey);
				results = new object[] { ret[0] == null ? null : Encoding.UTF8.GetString(ret[0]), ret[1] == null ? null : Encoding.UTF8.GetString(ret[1]), value = ret[2] };
			} else {
				results = _redisClient.HMGet(key, AbsoluteExpirationKey, SlidingExpirationKey);
			}

			// TODO: Error handling
			if (results.Length >= 2) {
				MapMetadata(results, out DateTimeOffset? absExpr, out TimeSpan? sldExpr);
				Refresh(key, absExpr, sldExpr);
			}

			if (results.Length >= 3) {
				return value;
			}

			return null;
		}

19 View Source File : RedumpProvider.cs
License : MIT License
Project Creator : 13xforever

public async Task<HashSet<DiscKeyInfo>> EnumerateAsync(string discKeyCachePath, string ProductCode, CancellationToken cancellationToken)
        {
            var result = new HashSet<DiscKeyInfo>();
            try
            {
                var replacedembly = replacedembly.GetExecutingreplacedembly();
                var embeddedResources = replacedembly.GetManifestResourceNames().Where(n => n.Contains("Disc_Keys") || n.Contains("Disc Keys")).ToList();
                if (embeddedResources.Any())
                    Log.Trace("Loading embedded redump keys");
                else
                    Log.Warn("No embedded redump keys found");
                foreach (var res in embeddedResources)
                {
                    using var resStream = replacedembly.GetManifestResourceStream(res);
                    using var zip = new ZipArchive(resStream, ZipArchiveMode.Read);
                    foreach (var zipEntry in zip.Entries.Where(e => e.Name.EndsWith(".dkey", StringComparison.InvariantCultureIgnoreCase)
                                                                    || e.Name.EndsWith(".key", StringComparison.InvariantCultureIgnoreCase)))
                    {
                        using var keyStream = zipEntry.Open();
                        using var memStream = new MemoryStream();
                        await keyStream.CopyToAsync(memStream, cancellationToken).ConfigureAwait(false);
                        var discKey = memStream.ToArray();
                        if (zipEntry.Length > 256/8*2)
                        {
                            Log.Warn($"Disc key size is too big: {discKey} ({res}/{zipEntry.FullName})");
                            continue;
                        }
                        if (discKey.Length > 16)
                        {
                            discKey = Encoding.UTF8.GetString(discKey).TrimEnd().ToByteArray();
                        }

                        try
                        {
                            result.Add(new DiscKeyInfo(null, discKey, zipEntry.FullName, KeyType.Redump, discKey.ToHexString()));
                        }
                        catch (Exception e)
                        {
                            Log.Warn(e, $"Invalid disc key format: {discKey}");
                        }
                    }
                }
                if (result.Any())
                    Log.Info($"Found {result.Count} embedded redump keys");
                else
                    Log.Warn($"Failed to load any embedded redump keys");
            }
            catch (Exception e)
            {
                Log.Error(e, "Failed to load embedded redump keys");
            }

            Log.Trace("Loading cached redump keys");
            var diff = result.Count;
            try
            {
                if (Directory.Exists(discKeyCachePath))
                {
                    var matchingDiskKeys = Directory.GetFiles(discKeyCachePath, "*.dkey", SearchOption.TopDirectoryOnly)
                        .Concat(Directory.GetFiles(discKeyCachePath, "*.key", SearchOption.TopDirectoryOnly));
                    foreach (var dkeyFile in matchingDiskKeys)
                    {
                        try
                        {
                            try
                            {
                                var discKey = File.ReadAllBytes(dkeyFile);
                                if (discKey.Length > 16)
                                {
                                    try
                                    {
                                        discKey = Encoding.UTF8.GetString(discKey).TrimEnd().ToByteArray();
                                    }
                                    catch (Exception e)
                                    {
                                        Log.Warn(e, $"Failed to convert {discKey.ToHexString()} from hex to binary");
                                    }
                                }
                                result.Add(new DiscKeyInfo(null, discKey, dkeyFile, KeyType.Redump, discKey.ToString()));
                            }
                            catch (InvalidDataException)
                            {
                                File.Delete(dkeyFile);
                                continue;
                            }
                            catch (Exception e)
                            {
                                Log.Warn(e);
                                continue;
                            }
                        }
                        catch (Exception e)
                        {
                            Log.Warn(e, e.Message);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Warn(ex, "Failed to load redump keys from local cache");
            }
            diff = result.Count - diff;
            Log.Info($"Found {diff} cached disc keys");
            return result;
        }

19 View Source File : QQUser.cs
License : MIT License
Project Creator : 499116344

public bool GetCookies()
        {
            try
            {
                using (var httpWebClient = new HttpWebClient())
                {
                    //string address = string.Format("http://ptlogin2.qq.com/jump?ptlang=2052&clientuin={0}&clientkey={1}&u1=http%3A%2F%2Fqzone.qq.com&ADUIN={0}&ADSESSION={2}&ADTAG=CLIENT.QQ.5365_.0&ADPUBNO=26405",
                    //    QQ, Util.ToHex(TXProtocol.ClientKey, "", "{0}"), Util.GetTimeMillis(DateTime.Now));
                    var address =
                        $"https://ssl.ptlogin2.qq.com/jump?pt_clientver=5593&pt_src=1&keyindex=9&ptlang=2052&clientuin={QQ}&clientkey={Util.ToHex(TXProtocol.BufServiceTicketHttp, "", "{0}")}&u1=https:%2F%2Fuser.qzone.qq.com%2F417085811%3FADUIN=417085811%26ADSESSION={Util.GetTimeMillis(DateTime.Now)}%26ADTAG=CLIENT.QQ.5593_MyTip.0%26ADPUBNO=26841&source=namecardhoverstar";
                    httpWebClient.Headers["User-Agent"] = _ua;
                    var text = Encoding.UTF8.GetString(httpWebClient.DownloadData(address));
                    QQCookies = httpWebClient.Cookies;
                    var cookies = QQCookies.GetCookies(new Uri("http://qq.com"));
                    if (cookies["skey"] != null)
                    {
                        var value = cookies["skey"].Value;
                        if (!string.IsNullOrWhiteSpace(value))
                        {
                            QQSkey = value;
                            Bkn = Util.GetBkn(value);
                            QQGtk = Util.GET_GTK(value);
                            return true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageLog("获取skey失败:" + ex.Message);
            }

            return false;
        }

19 View Source File : Chromium.cs
License : GNU General Public License v3.0
Project Creator : 0xfd3

public static string DecryptWithKey(byte[] encryptedData, byte[] MasterKey)
        {
            byte[] iv = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // IV 12 bytes

            //trim first 3 bytes(signature "v10") and take 12 bytes after signature.
            Array.Copy(encryptedData, 3, iv, 0, 12);

            try
            {
                //encryptedData without IV
                byte[] Buffer = new byte[encryptedData.Length - 15];
                Array.Copy(encryptedData, 15, Buffer, 0, encryptedData.Length - 15);

                byte[] tag = new byte[16]; //AuthTag
                byte[] data = new byte[Buffer.Length - tag.Length]; //Encrypted Data

                //Last 16 bytes for tag
                Array.Copy(Buffer, Buffer.Length - 16, tag, 0, 16);

                //encrypted preplacedword
                Array.Copy(Buffer, 0, data, 0, Buffer.Length - tag.Length);

                AesGcm aesDecryptor = new AesGcm();
                var result = Encoding.UTF8.GetString(aesDecryptor.Decrypt(MasterKey, iv, null, data, tag));

                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return null;
            }
        }

19 View Source File : GZipByteArray.cs
License : MIT License
Project Creator : 499116344

public static string DecompressString(byte[] input)
        {
            return Encoding.UTF8.GetString(ZlibStream.UncompressBuffer(input));
        }

19 View Source File : MainPage.xaml.cs
License : MIT License
Project Creator : 1iveowl

private void Button_OnClick(object sender, RoutedEventArgs e)
        {
            _mqttService = new MQTTService();

            var mqttClientOptions = new Options
            {
                Server = "test.mosquitto.org",
                //Server = "192.168.0.41",
                Port = 1883,
                ConnectionType = ConnectionType.Tcp,
                CleanSession = true,
                ClientId = Guid.NewGuid().ToString().Replace("-", string.Empty),
                UseTls = false
            };

            var topic1 = new TopicFilter
            {
                QualityOfServiceLevel = QoSLevel.AtLeastOnce,
                //Topic = "PP/#"
                Topic = "/#"
            };

            ITopicFilter[] topicFilters = {

                topic1,
            };

            var MQTTService = _mqttService.CreateObservableMQTTService(mqttClientOptions, topicFilters);
            _disposable = MQTTService
                .observableMessage
                .SubscribeOnDispatcher()
                //.Throttle(TimeSpan.FromMilliseconds(100), Scheduler.Default)
                .ObserveOnDispatcher().Subscribe(
                    msg =>
                    {
                        textBlock.Text = Encoding.UTF8.GetString(msg.Payload);
                    },
                    ex =>
                    {
                        textBlock.Text = "Exception";
                    },
                    () => { });

            //var MQTTService = await mqttService.CreateObservableMQTTServiceAsync(mqttClientOptions, topicFilters);


        }

19 View Source File : AssetsFile.cs
License : MIT License
Project Creator : 91Act

private void readBase5()
        {
            int clreplacedID = a_Stream.ReadInt32();
            if (fileGen > 15)//5.5.0 and up
            {
                a_Stream.ReadByte();
                int type1;
                if ((type1 = a_Stream.ReadInt16()) >= 0)
                {
                    type1 = -1 - type1;
                }
                else
                {
                    type1 = clreplacedID;
                }
                clreplacedIDs.Add(new[] { type1, clreplacedID });
                clreplacedID = type1;
                /*TODO 用来替换下方的代码
                if(clreplacedID == 114)
                {
                    a_Stream.Position += 16;
                }*/
                var temp = a_Stream.ReadInt32();
                if (temp == 0)
                {
                    a_Stream.Position += 16;
                }
                a_Stream.Position -= 4;
                if (type1 < 0)
                {
                    a_Stream.Position += 16;
                }
            }
            else if (clreplacedID < 0)
            {
                a_Stream.Position += 16;
            }
            a_Stream.Position += 16;

            if (baseDefinitions)
            {
                int varCount = a_Stream.ReadInt32();
                int stringSize = a_Stream.ReadInt32();

                a_Stream.Position += varCount * 24;
                string varStrings = Encoding.UTF8.GetString(a_Stream.ReadBytes(stringSize));
                string clreplacedName = "";
                var clreplacedVar = new List<ClreplacedMember>();
                //build Clreplaced Structures
                a_Stream.Position -= varCount * 24 + stringSize;
                for (int i = 0; i < varCount; i++)
                {
                    ushort num0 = a_Stream.ReadUInt16();
                    byte level = a_Stream.ReadByte();
                    bool isArray = a_Stream.ReadBoolean();

                    ushort varTypeIndex = a_Stream.ReadUInt16();
                    ushort test = a_Stream.ReadUInt16();
                    string varTypeStr;
                    if (test == 0) //varType is an offset in the string block
                    { varTypeStr = varStrings.Substring(varTypeIndex, varStrings.IndexOf('\0', varTypeIndex) - varTypeIndex); }//substringToNull
                    else //varType is an index in an internal strig array
                    { varTypeStr = baseStrings.ContainsKey(varTypeIndex) ? baseStrings[varTypeIndex] : varTypeIndex.ToString(); }

                    ushort varNameIndex = a_Stream.ReadUInt16();
                    test = a_Stream.ReadUInt16();
                    string varNameStr;
                    if (test == 0) { varNameStr = varStrings.Substring(varNameIndex, varStrings.IndexOf('\0', varNameIndex) - varNameIndex); }
                    else { varNameStr = baseStrings.ContainsKey(varNameIndex) ? baseStrings[varNameIndex] : varNameIndex.ToString(); }

                    int size = a_Stream.ReadInt32();
                    int index = a_Stream.ReadInt32();
                    int flag = a_Stream.ReadInt32();

                    if (index == 0) { clreplacedName = varTypeStr + " " + varNameStr; }
                    else
                    {
                        clreplacedVar.Add(new ClreplacedMember()
                        {
                            Level = level - 1,
                            Type = varTypeStr,
                            Name = varNameStr,
                            Size = size,
                            Flag = flag
                        });
                    }
                }
                a_Stream.Position += stringSize;

                var aClreplaced = new ClreplacedStruct() { ID = clreplacedID, Text = clreplacedName, members = clreplacedVar };
                aClreplaced.SubItems.Add(clreplacedID.ToString());
                ClreplacedStructures[clreplacedID] = aClreplaced;
            }
        }

19 View Source File : SharpSteam.cs
License : MIT License
Project Creator : 0x0ade

public unsafe string FileRead(string managedname) {
        int size = SteamRemoteStorage.GetFileSize(managedname);
        byte[] data = new byte[size];
        int rv = SteamRemoteStorage.FileRead(managedname, data, size);
        return Encoding.ASCII.GetString(data, 0, size);
    }

19 View Source File : ExternalCommunicator.cs
License : Apache License 2.0
Project Creator : A7ocin

public ExternalCommand GetCommand()
    {
        int location = sender.Receive(messageHolder);
        string message = Encoding.ASCII.GetString(messageHolder, 0, location);
        switch (message)
        {
            case "STEP":
                return ExternalCommand.STEP;
            case "RESET":
                return ExternalCommand.RESET;
            case "QUIT":
                return ExternalCommand.QUIT;
            default:
                return ExternalCommand.QUIT;
        }
    }

19 View Source File : CSRedisClientStringTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
		public void MGet() {
			rds.Set("TestMGet_null1", base.Null);
			rds.Set("TestMGet_string1", base.String);
			rds.Set("TestMGet_bytes1", base.Bytes);
			rds.Set("TestMGet_clreplaced1", base.Clreplaced);
			rds.Set("TestMGet_null2", base.Null);
			rds.Set("TestMGet_string2", base.String);
			rds.Set("TestMGet_bytes2", base.Bytes);
			rds.Set("TestMGet_clreplaced2", base.Clreplaced);
			rds.Set("TestMGet_null3", base.Null);
			rds.Set("TestMGet_string3", base.String);
			rds.Set("TestMGet_bytes3", base.Bytes);
			rds.Set("TestMGet_clreplaced3", base.Clreplaced);

			replacedert.Equal(4, rds.MGet("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1").Length);
			replacedert.Equal("", rds.MGet("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[0]);
			replacedert.Equal(base.String, rds.MGet("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[1]);
			replacedert.Equal(Encoding.UTF8.GetString(base.Bytes), rds.MGet("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[2]);
			replacedert.Equal(base.Clreplaced.ToString(), rds.MGet("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[3]);

			replacedert.Equal(4, rds.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1").Length);
			replacedert.Equal(new byte[0], rds.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[0]);
			replacedert.Equal(Encoding.UTF8.GetBytes(base.String), rds.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[1]);
			replacedert.Equal(base.Bytes, rds.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[2]);
			replacedert.Equal(Encoding.UTF8.GetBytes(base.Clreplaced.ToString()), rds.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[3]);

			replacedert.Equal(3, rds.MGet<TestClreplaced>("TestMGet_clreplaced1", "TestMGet_clreplaced2", "TestMGet_clreplaced3").Length);
			replacedert.Equal(base.Clreplaced.ToString(), rds.MGet<TestClreplaced>("TestMGet_clreplaced1", "TestMGet_clreplaced2", "TestMGet_clreplaced3")[0]?.ToString());
			replacedert.Equal(base.Clreplaced.ToString(), rds.MGet<TestClreplaced>("TestMGet_clreplaced1", "TestMGet_clreplaced2", "TestMGet_clreplaced3")[1]?.ToString());
			replacedert.Equal(base.Clreplaced.ToString(), rds.MGet<TestClreplaced>("TestMGet_clreplaced1", "TestMGet_clreplaced2", "TestMGet_clreplaced3")[2]?.ToString());
		}

19 View Source File : CSRedisClientHashTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
		public void HGetAll()
		{
			replacedert.True(rds.HMSet("TestHGetAll", "string1", base.String, "bytes1", base.Bytes, "clreplaced1", base.Clreplaced, "clreplaced1array", new[] { base.Clreplaced, base.Clreplaced }));
			replacedert.Equal(4, rds.HGetAll("TestHGetAll").Count);
			replacedert.Equal(base.String, rds.HGetAll("TestHGetAll")["string1"]);
			replacedert.Equal(Encoding.UTF8.GetString(base.Bytes), rds.HGetAll("TestHGetAll")["bytes1"]);
			replacedert.Equal(base.Clreplaced.ToString(), rds.HGetAll("TestHGetAll")["clreplaced1"]);

			Task.Run(async () =>
			{
				var test = await rds.HGetAllAsync("TestHGetAll");

				rds.Set("TestHGetAll2", "1");
				try
				{
					var test2 = await rds.HGetAllAsync("TestHGetAll2");
				}
				catch
				{

				}

				for (var a = 0; a < 1000; a++)
					test = await rds.HGetAllAsync("TestHGetAll");
			}).Wait();
		}

19 View Source File : Program.cs
License : MIT License
Project Creator : 0x1000000

private static async Task Step21ExportDataToJson(ISqDatabase database)
        {
            var tables = CreateTableList();

            //To JSON
            var jsonString = await ToJsonString(database, tables);

            //Remove everything
            foreach (var table in tables.Reverse())
            {
                await Delete(table).All().Exec(database);
            }

            //From JSON
            await FromJsonString(sqDatabase: database, s: jsonString, tableBases: tables);

            //Again to JSON
            var jsonString2 = await ToJsonString(database, tables);

            if (jsonString != jsonString2)
            {
                throw new Exception("Export'n'Import was not correct");
            }

            static async Task<string> ToJsonString(ISqDatabase database, TableBase[] tableBases)
            {
                using var ms = new MemoryStream();
                using Utf8JsonWriter writer = new Utf8JsonWriter(ms);

                writer.WriteStartObject();
                foreach (var table in tableBases)
                {
                    await ReadTableDataIntoJson(writer, database, table);
                }

                writer.WriteEndObject();
                writer.Flush();

                var s = Encoding.UTF8.GetString(ms.ToArray());
                return s;
            }

            static async Task ReadTableDataIntoJson(Utf8JsonWriter writer, ISqDatabase database, TableBase table)
            {
                writer.WriteStartArray(table.FullName.AsExprTableFullName().TableName.Name);

                writer.WriteStartArray();
                foreach (var column in table.Columns)
                {
                    writer.WriteStringValue(column.ColumnName.Name);
                }

                writer.WriteEndArray();

                await Select(table.Columns)
                    .From(table)
                    .Query(database,
                        r =>
                        {
                            writer.WriteStartArray();
                            foreach (var column in table.Columns)
                            {
                                var readreplacedtring = column.Readreplacedtring(r);
                                writer.WriteStringValue(readreplacedtring);
                            }

                            writer.WriteEndArray();
                        });

                writer.WriteEndArray();
            }

            static async Task FromJsonString(ISqDatabase sqDatabase, string s, TableBase[] tableBases)
            {
                var doreplacedent = JsonDoreplacedent.Parse(s);
                var pending = new Dictionary<string, JsonElement>();

                using var enumerator = doreplacedent.RootElement.EnumerateObject();
                if (!enumerator.MoveNext())
                {
                    throw new Exception("Enumerator is empty");
                }

                foreach (var table in tableBases)
                {
                    var tableName = table.FullName.AsExprTableFullName().TableName.Name;
                    JsonElement element;

                    if (enumerator.Current.Name != tableName && pending.TryGetValue(tableName, out var e))
                    {
                        element = e;
                    }
                    else
                    {
                        while (enumerator.Current.Name != tableName)
                        {
                            pending.Add(enumerator.Current.Name, enumerator.Current.Value);
                            if (!enumerator.MoveNext())
                            {
                                throw new Exception("Enumerator is empty");
                            }
                        }

                        element = enumerator.Current.Value;
                    }

                    await InsertTableData(sqDatabase, table, element);
                }
            }

            static async Task InsertTableData(ISqDatabase database, TableBase table, JsonElement element)
            {
                var columnsDict = table.Columns.ToDictionary(i => i.ColumnName.Name, i => i);
                var colIndexes = element.EnumerateArray().First().EnumerateArray().Select(c => c.GetString()).ToList();

                var rowsEnumerable = element
                    .EnumerateArray()
                    .Skip(1)
                    .Select(e =>
                        e.EnumerateArray()
                            .Select((c, i) =>
                                columnsDict[colIndexes[i]]
                                    .FromString(c.ValueKind == JsonValueKind.Null ? null : c.GetString()))
                            .ToList());

                var insertExpr = IdenreplacedyInsertInto(table, table.Columns).Values(rowsEnumerable);
                if (!insertExpr.Insert.Source.IsEmpty)
                {
                    await insertExpr.Exec(database);
                }

            }
        }

19 View Source File : RedisReader.cs
License : MIT License
Project Creator : 2881099

public void ExpectType(RedisMessage expectedType)
        {
            RedisMessage type = ReadType();
            if ((int)type == -1)
            {
                var alldata = _io.ReadAll();
                try { _io.Dispose(); } catch { }
                throw new EndOfStreamException($"Unexpected end of stream; expected type '{expectedType}'; data = '{Encoding.UTF8.GetString(alldata)}'");
            }
            if (type != expectedType)
                throw new RedisProtocolException($"Unexpected response type: {type} (expecting {expectedType})");
        }

19 View Source File : SQLite.cs
License : GNU General Public License v3.0
Project Creator : 0xfd3

private bool ReadTableFromOffset(ulong Offset)
        {
            if (this.db_bytes[(int)Offset] == 13)
            {
                int num2 = Convert.ToInt32(decimal.Subtract(new decimal(this.ConvertToInteger(Convert.ToInt32(decimal.Add(new decimal(Offset), 3M)), 2)), decimal.One));
                int length = 0;
                if (this.table_entries != null)
                {
                    length = this.table_entries.Length;
                    this.table_entries = (table_entry[])Utils.CopyArray((Array)this.table_entries, new table_entry[(this.table_entries.Length + num2) + 1]);
                }
                else
                {
                    this.table_entries = new table_entry[num2 + 1];
                }
                int num16 = num2;
                for (int i = 0; i <= num16; i++)
                {
                    record_header_field[] _fieldArray = null;
                    ulong num = this.ConvertToInteger(Convert.ToInt32(decimal.Add(decimal.Add(new decimal(Offset), 8M), new decimal(i * 2))), 2);
                    if (decimal.Compare(new decimal(Offset), 100M) != 0)
                    {
                        num += Offset;
                    }
                    int endIndex = this.GVL((int)num);
                    long num9 = this.CVL((int)num, endIndex);
                    int num8 = this.GVL(Convert.ToInt32(decimal.Add(decimal.Add(new decimal(num), decimal.Subtract(new decimal(endIndex), new decimal(num))), decimal.One)));
                    this.table_entries[length + i].row_id = this.CVL(Convert.ToInt32(decimal.Add(decimal.Add(new decimal(num), decimal.Subtract(new decimal(endIndex), new decimal(num))), decimal.One)), num8);
                    num = Convert.ToUInt64(decimal.Add(decimal.Add(new decimal(num), decimal.Subtract(new decimal(num8), new decimal(num))), decimal.One));
                    endIndex = this.GVL((int)num);
                    num8 = endIndex;
                    long num7 = this.CVL((int)num, endIndex);
                    long num10 = Convert.ToInt64(decimal.Add(decimal.Subtract(new decimal(num), new decimal(endIndex)), decimal.One));
                    for (int j = 0; num10 < num7; j++)
                    {
                        _fieldArray = (record_header_field[])Utils.CopyArray((Array)_fieldArray, new record_header_field[j + 1]);
                        endIndex = num8 + 1;
                        num8 = this.GVL(endIndex);
                        _fieldArray[j].type = this.CVL(endIndex, num8);
                        if (_fieldArray[j].type > 9L)
                        {
                            if (this.IsOdd(_fieldArray[j].type))
                            {
                                _fieldArray[j].size = (long)Math.Round((double)(((double)(_fieldArray[j].type - 13L)) / 2.0));
                            }
                            else
                            {
                                _fieldArray[j].size = (long)Math.Round((double)(((double)(_fieldArray[j].type - 12L)) / 2.0));
                            }
                        }
                        else
                        {
                            _fieldArray[j].size = this.SQLDataTypeSize[(int)_fieldArray[j].type];
                        }
                        num10 = (num10 + (num8 - endIndex)) + 1L;
                    }
                    this.table_entries[length + i].content = new string[(_fieldArray.Length - 1) + 1];
                    int num4 = 0;
                    int num17 = _fieldArray.Length - 1;
                    for (int k = 0; k <= num17; k++)
                    {
                        if (_fieldArray[k].type > 9L)
                        {
                            if (!this.IsOdd(_fieldArray[k].type))
                            {
                                if (decimal.Compare(new decimal(this.encoding), decimal.One) == 0)
                                {
                                    this.table_entries[length + i].content[k] = Encoding.Default.GetString(this.db_bytes, Convert.ToInt32(decimal.Add(decimal.Add(new decimal(num), new decimal(num7)), new decimal(num4))), (int)_fieldArray[k].size);
                                }
                                else if (decimal.Compare(new decimal(this.encoding), 2M) == 0)
                                {
                                    this.table_entries[length + i].content[k] = Encoding.Unicode.GetString(this.db_bytes, Convert.ToInt32(decimal.Add(decimal.Add(new decimal(num), new decimal(num7)), new decimal(num4))), (int)_fieldArray[k].size);
                                }
                                else if (decimal.Compare(new decimal(this.encoding), 3M) == 0)
                                {
                                    this.table_entries[length + i].content[k] = Encoding.BigEndianUnicode.GetString(this.db_bytes, Convert.ToInt32(decimal.Add(decimal.Add(new decimal(num), new decimal(num7)), new decimal(num4))), (int)_fieldArray[k].size);
                                }
                            }
                            else
                            {
                                this.table_entries[length + i].content[k] = Encoding.Default.GetString(this.db_bytes, Convert.ToInt32(decimal.Add(decimal.Add(new decimal(num), new decimal(num7)), new decimal(num4))), (int)_fieldArray[k].size);
                            }
                        }
                        else
                        {
                            this.table_entries[length + i].content[k] = Conversions.ToString(this.ConvertToInteger(Convert.ToInt32(decimal.Add(decimal.Add(new decimal(num), new decimal(num7)), new decimal(num4))), (int)_fieldArray[k].size));
                        }
                        num4 += (int)_fieldArray[k].size;
                    }
                }
            }
            else if (this.db_bytes[(int)Offset] == 5)
            {
                ushort num14 = Convert.ToUInt16(decimal.Subtract(new decimal(this.ConvertToInteger(Convert.ToInt32(decimal.Add(new decimal(Offset), 3M)), 2)), decimal.One));
                int num18 = num14;
                for (int m = 0; m <= num18; m++)
                {
                    ushort num13 = (ushort)this.ConvertToInteger(Convert.ToInt32(decimal.Add(decimal.Add(new decimal(Offset), 12M), new decimal(m * 2))), 2);
                    this.ReadTableFromOffset(Convert.ToUInt64(decimal.Multiply(decimal.Subtract(new decimal(this.ConvertToInteger((int)(Offset + num13), 4)), decimal.One), new decimal(this.page_size))));
                }
                this.ReadTableFromOffset(Convert.ToUInt64(decimal.Multiply(decimal.Subtract(new decimal(this.ConvertToInteger(Convert.ToInt32(decimal.Add(new decimal(Offset), 8M)), 4)), decimal.One), new decimal(this.page_size))));
            }
            return true;
        }

19 View Source File : HashesTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
        public void HGetAll()
        {
            cli.Del("TestHGetAll");
            cli.HMSet("TestHGetAll", "string1", base.String, "bytes1", base.Bytes, "clreplaced1", base.Clreplaced, "clreplaced1array", new[] { base.Clreplaced, base.Clreplaced });
            replacedert.Equal(4, cli.HGetAll("TestHGetAll").Count);
            replacedert.Equal(base.String, cli.HGetAll("TestHGetAll")["string1"]);
            replacedert.Equal(Encoding.UTF8.GetString(base.Bytes), cli.HGetAll("TestHGetAll")["bytes1"]);
            replacedert.Equal(JsonConvert.SerializeObject(base.Clreplaced), cli.HGetAll("TestHGetAll")["clreplaced1"]);
        }

19 View Source File : CSRedisCache.cs
License : MIT License
Project Creator : 2881099

private async Task<byte[]> GetAndRefreshAsync(string key, bool getData, CancellationToken token = default(CancellationToken)) {
			if (key == null) {
				throw new ArgumentNullException(nameof(key));
			}

			token.ThrowIfCancellationRequested();

			// This also resets the LRU status as desired.
			// TODO: Can this be done in one operation on the server side? Probably, the trick would just be the DateTimeOffset math.
			object[] results;
			byte[] value = null;
			if (getData) {
				var ret = await _redisClient.HMGetAsync<byte[]>(key, AbsoluteExpirationKey, SlidingExpirationKey, DataKey);
				results = new object[] { ret[0] == null ? null : Encoding.UTF8.GetString(ret[0]), ret[1] == null ? null : Encoding.UTF8.GetString(ret[1]), value = ret[2] };
			} else {
				results = await _redisClient.HMGetAsync(key, AbsoluteExpirationKey, SlidingExpirationKey);
			}

			// TODO: Error handling
			if (results.Length >= 2) {
				MapMetadata(results, out DateTimeOffset? absExpr, out TimeSpan? sldExpr);
				await RefreshAsync(key, absExpr, sldExpr, token);
			}

			if (results.Length >= 3) {
				return value;
			}

			return null;
		}

19 View Source File : BinaryReaderEx.cs
License : MIT License
Project Creator : 13xforever

public static string ReadUEString(this BinaryReader reader)
        {
            if (reader.PeekChar() < 0)
                return null;

            var length = reader.ReadInt32();
            if (length == 0)
                return null;

            if (length == 1)
                return "";

            var valueBytes = reader.ReadBytes(length);
            return Utf8.GetString(valueBytes, 0, valueBytes.Length - 1);
        }

19 View Source File : NTLM.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 3gstudent

public byte[] ProcessChallenge(byte[] Challenge)
        {
            byte[] bytes;
            RdpPacket packet = new RdpPacket();
            this.m_ChallengeMsg = Challenge;
            packet.Write(Challenge, 0, Challenge.Length);
            packet.Position = 0L;
            long position = packet.Position;

            if (packet.ReadString(8) != "NTLMSSP\0")
            {
                throw new Exception("Invalid negotiation token!");
            }

            if (packet.ReadLittleEndian32() != 2)
            {
                throw new Exception("Expected challenge!");
            }

            int count = packet.ReadLittleEndian16();
            packet.ReadLittleEndian16();
            int num4 = packet.ReadLittleEndian32();
            uint flags = (uint) packet.ReadLittleEndian32();
            DumpFlags(flags);
            byte[] buffer = new byte[8];
            packet.Read(buffer, 0, 8);
            DumpHex(buffer, buffer.Length, "Server Challenge");
            byte[] buffer2 = new byte[8];
            packet.Read(buffer2, 0, 8);
            int num5 = packet.ReadLittleEndian16();
            packet.ReadLittleEndian16();
            int num6 = packet.ReadLittleEndian32();

            if ((flags & 0x2000000) != 0)
            {
                byte[] buffer3 = new byte[8];
                packet.Read(buffer3, 0, 8);
            }

            if ((flags & 0x20000000) == 0)
            {
                throw new Exception("Strong Encryption not supported by server");
            }

            byte[] buffer4 = null;

            if (count > 0)
            {
                buffer4 = new byte[count];
                packet.Position = position + num4;
                packet.Read(buffer4, 0, count);
                Encoding.Unicode.GetString(buffer4, 0, buffer4.Length);
            }

            AV_PAIRS av_pairs = new AV_PAIRS();
            byte[] buffer5 = null;

            if (num5 <= 0)
            {
                throw new Exception("No TargetInfo!");
            }

            packet.Position = position + num6;
            buffer5 = new byte[num5];
            packet.Read(buffer5, 0, num5);
            packet = new RdpPacket();
            packet.Write(buffer5, 0, buffer5.Length);
            packet.Position = 0L;
            av_pairs.Parse(packet);

            buffer5 = av_pairs.Serialise();

            byte[] data = nTOWFv2(this.m_sDomain, this.m_sUsername, this.m_sPreplacedword);

            if (Network.Logger != null)
            {
                if (Network.Logger.Reading)
                {
                    data = this.m_Socket.GetBlob(PacketLogger.PacketType.NTLM_ResponseKeyNT);
                }
                else
                {
                    this.m_Socket.AddBlob(PacketLogger.PacketType.NTLM_ResponseKeyNT, data);
                }
            }

            byte[] blob = new byte[8];
            RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
            provider.GetBytes(blob);

            if (Network.Logger != null)
            {
                if (Network.Logger.Reading)
                {
                    blob = this.m_Socket.GetBlob(PacketLogger.PacketType.NTLM_ClientChallenge);
                }
                else
                {
                    this.m_Socket.AddBlob(PacketLogger.PacketType.NTLM_ClientChallenge, blob);
                }
            }

            DumpHex(blob, blob.Length, "Client Challenge");
            byte[] buffer8 = getLMv2Response(data, buffer, blob);
            DumpHex(buffer8, buffer8.Length, "LM Response");

            if (this.m_bNTLMv2)
            {
                Array.Clear(buffer8, 0, buffer8.Length);
            }

            bool bGenerateMIC = false;

            if ((av_pairs.Timestamp.length <= 0) || !this.m_bNTLMv2)
            {
                bytes = BitConverter.GetBytes(DateTime.UtcNow.ToFileTimeUtc());
            }
            else
            {
                bytes = av_pairs.Timestamp.value;
                bGenerateMIC = true;
                av_pairs.ProcessForNTLMv2();
                buffer5 = av_pairs.Serialise();
            }

            DumpHex(buffer5, buffer5.Length, "targetinfo");
            byte[] keyExchangeKey = null;
            byte[] buffer11 = getNTLMv2Response(data, buffer, blob, bytes, buffer5, out keyExchangeKey);
            DumpHex(buffer11, buffer11.Length, "NTLMv2 Response");

            if (Network.Logger != null)
            {
                if (Network.Logger.Reading)
                {
                    keyExchangeKey = this.m_Socket.GetBlob(PacketLogger.PacketType.NTLM_KeyExchangeKey);
                }
                else
                {
                    this.m_Socket.AddBlob(PacketLogger.PacketType.NTLM_KeyExchangeKey, keyExchangeKey);
                }
            }

            byte[] encryptedRandomSessionKey = null;
            byte[] buffer13 = null;
            buffer13 = new byte[0x10];
            provider.GetBytes(buffer13);

            if (Network.Logger != null)
            {
                if (Network.Logger.Reading)
                {
                    buffer13 = this.m_Socket.GetBlob(PacketLogger.PacketType.NTLM_ExportedSessionKey);
                }
                else
                {
                    this.m_Socket.AddBlob(PacketLogger.PacketType.NTLM_ExportedSessionKey, buffer13);
                }
            }

            encryptedRandomSessionKey = new byte[0x10];
            RC4 rc = new RC4();
            rc.engineInitEncrypt(keyExchangeKey);
            encryptedRandomSessionKey = rc.crypt(buffer13);

            if ((flags & 0x40000000) == 0)
            {
                encryptedRandomSessionKey = new byte[0];
                buffer13 = keyExchangeKey;
            }

            this.InitSignKeys(buffer13);

            return this.Authenticate(buffer8, buffer11, this.m_sDomain, this.m_sUsername, this.m_sWorkstation, encryptedRandomSessionKey, buffer13, bGenerateMIC);
        }

19 View Source File : GmicPipeServer.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054

private static List<string> DecodeMessageBuffer(byte[] bytes)
        {
            const byte Separator = (byte)'\n';

            int startOffset = 0;
            int count = 0;

            List<string> messageParameters = new List<string>();

            if (bytes[bytes.Length - 1] == Separator)
            {
                // A message with multiple values uses \n as the separator and terminator.
                for (int i = 0; i < bytes.Length; i++)
                {
                    if (bytes[i] == Separator)
                    {
                        // Empty strings are skipped.
                        if (count > 0)
                        {
                            messageParameters.Add(Encoding.UTF8.GetString(bytes, startOffset, count));
                        }
                        startOffset = i + 1;
                        count = 0;
                    }
                    else
                    {
                        count++;
                    }
                }
            }
            else
            {
                messageParameters.Add(Encoding.UTF8.GetString(bytes));
            }

            return messageParameters;
        }

19 View Source File : ASCIIEncoding.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 3gstudent

public static string GetString(byte[] bytes, int index, int count)
        {
            return Encoding.UTF8.GetString(bytes, index, count);
        }

19 View Source File : AesEncrypt.cs
License : MIT License
Project Creator : 17MKH

private string Decrypt(string decryptString, string key, bool hex)
    {
        if (decryptString.IsNull())
            return null;
        if (key.IsNull())
            key = KEY;

        var keyBytes = Encoding.UTF8.GetBytes(key);
        var encryptBytes = hex ? decryptString.Hex2Bytes() : Convert.FromBase64String(decryptString);
        var provider = new RijndaelManaged
        {
            Key = keyBytes,
            Mode = CipherMode.ECB,
            Padding = PaddingMode.PKCS7
        };

        using var mStream = new MemoryStream();
        using var cStream = new CryptoStream(mStream, provider.CreateDecryptor(), CryptoStreamMode.Write);
        cStream.Write(encryptBytes, 0, encryptBytes.Length);
        cStream.FlushFinalBlock();
        return Encoding.UTF8.GetString(mStream.ToArray());
    }

19 View Source File : QQUser.cs
License : MIT License
Project Creator : 499116344

public bool GetQunCookies()
        {
            try
            {
                using (var httpWebClient = new HttpWebClient())
                {
                    var address = string.Format(
                        "https://ssl.ptlogin2.qq.com/jump?pt_clientver=5509&pt_src=1&keyindex=9&clientuin={0}&clientkey={1}&u1=http%3A%2F%2Fqun.qq.com%2Fmember.html%23gid%3D168209441",
                        QQ, Util.ToHex(TXProtocol.BufServiceTicketHttp /*QunKey*/, "", "{0}"),
                        Util.GetTimeMillis(DateTime.Now));
                    httpWebClient.Headers["User-Agent"] = _ua;
                    var result = Encoding.UTF8.GetString(httpWebClient.DownloadData(address));
                    QunCookies = httpWebClient.Cookies;
                    var cookies = QunCookies.GetCookies(new Uri("http://qun.qq.com"));
                    if (cookies["skey"] != null && !string.IsNullOrWhiteSpace(cookies["skey"].Value))
                    {
                        QQSkey = cookies["skey"].Value;
                        Bkn = Util.GetBkn(cookies["skey"].Value);
                    }

                    var value2 = cookies["p_skey"].Value;
                    if (!string.IsNullOrWhiteSpace(value2))
                    {
                        QunPSkey = cookies["p_skey"].Value;
                        QunGtk = Util.GET_GTK(value2);
                    }

                    return true;
                }
            }
            catch (Exception ex)
            {
                MessageLog("获取skey失败:" + ex.Message);
            }

            return false;
        }

19 View Source File : InternalTalk.cs
License : MIT License
Project Creator : 0ffffffffh

public Dictionary<string, string> Parse(byte[] data, int length)
        {
            Dictionary<string, string> talkInfo = new Dictionary<string, string>();

            string s = Encoding.ASCII.GetString(data,0,length);

            var items = s.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            Log.Verbose(s);
            foreach (var item in items)
            {
                var kv = item.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);

                if (!talkInfo.ContainsKey(kv[0].ToLower()))
                    talkInfo.Add(kv[0].ToLower(), kv[1]);

            }

            return talkInfo;
        }

19 View Source File : Receive_0x001D.cs
License : MIT License
Project Creator : 499116344

protected override void ParseBody()
        {
            Decrypt(User.TXProtocol.SessionKey);
            Reader.ReadBytes(4);
            User.QQSkey = Encoding.UTF8.GetString(Reader.ReadBytes(10));
            if (string.IsNullOrEmpty(User.QQSkey))
            {
                throw new Exception("skey获取失败");
            }

            new Task(() =>
            {
                User.GetQunCookies();
                User.Friends = User.Get_Friend_List();
                User.Groups = User.Get_Group_List();
            }).Start();
            //User.QQCookies = "uin=o" + User.QQ + ";skey=" + User.QQSkey + ";";
            //User.QQGtk = Util.GET_GTK(User.QQSkey);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 1iveowl

static async Task Start()
        {
            var mqttService = new MQTTService();

            var mqttClientOptions = new Options
            {
                Uri = new Uri("mqtt://test.mosquitto.org:8883"),
                UseTls = true,
                //IgnoreCertificateChainErrors = true,
                //IgnoreCertificateRevocationErrors = true,
                AllowUntrustedCertificates = true,

                //Uri = new Uri("ws://broker.mqttdashboard.com:8000/mqtt"),
                //Server = "broker.mqttdashboard.com",
                ////Port = 1883,
                //Port = 8000,
                //Url = "broker.mqttdashboard.com",
                //Path = "mqtt",
                ConnectionType = ConnectionType.Tcp,
                //ConnectionType = ConnectionType.WebSocket
            };

            var topic1 = new TopicFilter
            {
                QualityOfServiceLevel = QoSLevel.ExactlyOnce,
                //Topic = "PP/#"
                Topic = "/#"
            };

            var topic2 = new TopicFilter
            {
                QualityOfServiceLevel = QoSLevel.AtLeastOnce,
                Topic = "EFM/#"
                //Topic = "MQTTClientRx/Test"
            };

            var topic3 = new TopicFilter
            {
                QualityOfServiceLevel = QoSLevel.AtLeastOnce,
                Topic = "MQTTClientRx"
            };


            ITopicFilter[] topicFilters = 
            {

                topic1,
                topic2,
                topic3,
            };

            var MQTTService = mqttService.CreateObservableMQTTClient(mqttClientOptions, willMessage:null, topicFilters:topicFilters);

            var disposableMessage = MQTTService.observableMessage.Subscribe(
                msg =>
                {
                    if (msg.Topic.Contains("EFM"))
                    {
                        Console.ForegroundColor = ConsoleColor.Yellow;
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.Blue;
                    }

                    Console.WriteLine($"{Encoding.UTF8.GetString(msg.Payload)}, " +
                                      $"{msg.QualityOfServiceLevel.ToString()}, " +
                                      $"Retain: {msg.Retain}, " +
                                      $"Topic: {msg.Topic}");
                },
                ex =>
                {
                    Console.WriteLine($"{ex?.Message} : inner {ex?.InnerException?.Message}");
                },
                () =>
                {
                    Console.WriteLine("Completed...");
                });

            await MQTTService.client.ConnectAsync();


            //await Task.Delay(TimeSpan.FromSeconds(2));

            //Console.ForegroundColor = ConsoleColor.Yellow;
            //Console.WriteLine($"Unsubscribe: {topic1.Topic}");
            //await MQTTService.client.UnsubscribeAsync(topic2);

            //Console.ForegroundColor = ConsoleColor.Blue;

            //await Task.Delay(TimeSpan.FromSeconds(2));

            //Console.ForegroundColor = ConsoleColor.Yellow;
            //Console.WriteLine($"Unsubscribe: {topic1.Topic}");
            //await MQTTService.client.UnsubscribeAsync(topic1);
            //Console.ForegroundColor = ConsoleColor.Blue;

            //await Task.Delay(TimeSpan.FromSeconds(2));

            //Console.ForegroundColor = ConsoleColor.Yellow;
            //Console.WriteLine($"Unsubscribe: {topic1.Topic}");
            //await MQTTService.client.SubscribeAsync(topic3);
            //Console.ForegroundColor = ConsoleColor.Blue;

            //var newMessage = new MQTTMessage
            //{
            //    Payload = Encoding.UTF8.GetBytes("Hello MQTT EO"),
            //    QualityOfServiceLevel = QoSLevel.AtLeastOnce,
            //    Retain = false,
            //    Topic = "MQTTClientRx"
            //};

            //await Task.Delay(TimeSpan.FromSeconds(2));

            //await MQTTService.client.PublishAsync(newMessage);

            //await Task.Delay(TimeSpan.FromSeconds(2));

            //await MQTTService.client.DisconnectAsync();

            //disposableMessage?.Dispose();
        }

19 View Source File : QQUser.cs
License : MIT License
Project Creator : 499116344

public GroupList Get_Group_List()
        {
            try
            {
                using (var httpWebClient = new HttpWebClient())
                {
                    var address = "https://qun.qq.com/cgi-bin/qun_mgr/get_group_list";
                    var s = $"bkn={Bkn}";
                    httpWebClient.Headers["Accept"] = "application/json, text/javascript, */*; q=0.01";
                    httpWebClient.Headers["Referer"] = "http://qun.qq.com/member.html";
                    httpWebClient.Headers["X-Requested-With"] = "XMLHttpRequest";
                    httpWebClient.Headers.Add("Cache-Control: no-cache");
                    httpWebClient.Headers["User-Agent"] = _ua;
                    httpWebClient.Cookies = QunCookies;
                    var text = Encoding.UTF8.GetString(httpWebClient.UploadData(address, "POST",
                        Encoding.UTF8.GetBytes(s)));

                    MessageLog("获取群列表成功:" + text);

                    var groups = JsonConvert.DeserializeObject<GroupList>(text);
                    if (groups.Create != null)
                    {
                        foreach (var item in groups.Create)
                        {
                            item.Members = Search_Group_Members((long) item.Gc);
                        }
                    }

                    if (groups.Join != null)
                    {
                        foreach (var item in groups.Join)
                        {
                            item.Members = Search_Group_Members((long) item.Gc);
                        }
                    }

                    if (groups.Manage != null)
                    {
                        foreach (var item in groups.Manage)
                        {
                            item.Members = Search_Group_Members((long) item.Gc);
                        }
                    }

                    return groups;
                }
            }
            catch (Exception ex)
            {
                MessageLog("获取群列表失败:" + ex.Message);
            }

            return null;
        }

19 View Source File : SQLite.cs
License : GNU General Public License v3.0
Project Creator : 0xfd3

private void ReadMasterTable(ulong Offset)
        {
            if (this.db_bytes[(int)Offset] == 13)
            {
                ushort num2 = Convert.ToUInt16(decimal.Subtract(new decimal(this.ConvertToInteger(Convert.ToInt32(decimal.Add(new decimal(Offset), 3M)), 2)), decimal.One));
                int length = 0;
                if (this.master_table_entries != null)
                {
                    length = this.master_table_entries.Length;
                    this.master_table_entries = (sqlite_master_entry[])Utils.CopyArray((Array)this.master_table_entries, new sqlite_master_entry[(this.master_table_entries.Length + num2) + 1]);
                }
                else
                {
                    this.master_table_entries = new sqlite_master_entry[num2 + 1];
                }
                int num13 = num2;
                for (int i = 0; i <= num13; i++)
                {
                    ulong num = this.ConvertToInteger(Convert.ToInt32(decimal.Add(decimal.Add(new decimal(Offset), 8M), new decimal(i * 2))), 2);
                    if (decimal.Compare(new decimal(Offset), 100M) != 0)
                    {
                        num += Offset;
                    }
                    int endIndex = this.GVL((int)num);
                    long num7 = this.CVL((int)num, endIndex);
                    int num6 = this.GVL(Convert.ToInt32(decimal.Add(decimal.Add(new decimal(num), decimal.Subtract(new decimal(endIndex), new decimal(num))), decimal.One)));
                    this.master_table_entries[length + i].row_id = this.CVL(Convert.ToInt32(decimal.Add(decimal.Add(new decimal(num), decimal.Subtract(new decimal(endIndex), new decimal(num))), decimal.One)), num6);
                    num = Convert.ToUInt64(decimal.Add(decimal.Add(new decimal(num), decimal.Subtract(new decimal(num6), new decimal(num))), decimal.One));
                    endIndex = this.GVL((int)num);
                    num6 = endIndex;
                    long num5 = this.CVL((int)num, endIndex);
                    long[] numArray = new long[5];
                    int index = 0;
                    do
                    {
                        endIndex = num6 + 1;
                        num6 = this.GVL(endIndex);
                        numArray[index] = this.CVL(endIndex, num6);
                        if (numArray[index] > 9L)
                        {
                            if (this.IsOdd(numArray[index]))
                            {
                                numArray[index] = (long)Math.Round((double)(((double)(numArray[index] - 13L)) / 2.0));
                            }
                            else
                            {
                                numArray[index] = (long)Math.Round((double)(((double)(numArray[index] - 12L)) / 2.0));
                            }
                        }
                        else
                        {
                            numArray[index] = this.SQLDataTypeSize[(int)numArray[index]];
                        }
                        index++;
                    }
                    while (index <= 4);
                    if (decimal.Compare(new decimal(this.encoding), decimal.One) == 0)
                    {
                        this.master_table_entries[length + i].item_type = Encoding.Default.GetString(this.db_bytes, Convert.ToInt32(decimal.Add(new decimal(num), new decimal(num5))), (int)numArray[0]);
                    }
                    else if (decimal.Compare(new decimal(this.encoding), 2M) == 0)
                    {
                        this.master_table_entries[length + i].item_type = Encoding.Unicode.GetString(this.db_bytes, Convert.ToInt32(decimal.Add(new decimal(num), new decimal(num5))), (int)numArray[0]);
                    }
                    else if (decimal.Compare(new decimal(this.encoding), 3M) == 0)
                    {
                        this.master_table_entries[length + i].item_type = Encoding.BigEndianUnicode.GetString(this.db_bytes, Convert.ToInt32(decimal.Add(new decimal(num), new decimal(num5))), (int)numArray[0]);
                    }
                    if (decimal.Compare(new decimal(this.encoding), decimal.One) == 0)
                    {
                        this.master_table_entries[length + i].item_name = Encoding.Default.GetString(this.db_bytes, Convert.ToInt32(decimal.Add(decimal.Add(new decimal(num), new decimal(num5)), new decimal(numArray[0]))), (int)numArray[1]);
                    }
                    else if (decimal.Compare(new decimal(this.encoding), 2M) == 0)
                    {
                        this.master_table_entries[length + i].item_name = Encoding.Unicode.GetString(this.db_bytes, Convert.ToInt32(decimal.Add(decimal.Add(new decimal(num), new decimal(num5)), new decimal(numArray[0]))), (int)numArray[1]);
                    }
                    else if (decimal.Compare(new decimal(this.encoding), 3M) == 0)
                    {
                        this.master_table_entries[length + i].item_name = Encoding.BigEndianUnicode.GetString(this.db_bytes, Convert.ToInt32(decimal.Add(decimal.Add(new decimal(num), new decimal(num5)), new decimal(numArray[0]))), (int)numArray[1]);
                    }
                    this.master_table_entries[length + i].root_num = (long)this.ConvertToInteger(Convert.ToInt32(decimal.Add(decimal.Add(decimal.Add(decimal.Add(new decimal(num), new decimal(num5)), new decimal(numArray[0])), new decimal(numArray[1])), new decimal(numArray[2]))), (int)numArray[3]);
                    if (decimal.Compare(new decimal(this.encoding), decimal.One) == 0)
                    {
                        this.master_table_entries[length + i].sql_statement = Encoding.Default.GetString(this.db_bytes, Convert.ToInt32(decimal.Add(decimal.Add(decimal.Add(decimal.Add(decimal.Add(new decimal(num), new decimal(num5)), new decimal(numArray[0])), new decimal(numArray[1])), new decimal(numArray[2])), new decimal(numArray[3]))), (int)numArray[4]);
                    }
                    else if (decimal.Compare(new decimal(this.encoding), 2M) == 0)
                    {
                        this.master_table_entries[length + i].sql_statement = Encoding.Unicode.GetString(this.db_bytes, Convert.ToInt32(decimal.Add(decimal.Add(decimal.Add(decimal.Add(decimal.Add(new decimal(num), new decimal(num5)), new decimal(numArray[0])), new decimal(numArray[1])), new decimal(numArray[2])), new decimal(numArray[3]))), (int)numArray[4]);
                    }
                    else if (decimal.Compare(new decimal(this.encoding), 3M) == 0)
                    {
                        this.master_table_entries[length + i].sql_statement = Encoding.BigEndianUnicode.GetString(this.db_bytes, Convert.ToInt32(decimal.Add(decimal.Add(decimal.Add(decimal.Add(decimal.Add(new decimal(num), new decimal(num5)), new decimal(numArray[0])), new decimal(numArray[1])), new decimal(numArray[2])), new decimal(numArray[3]))), (int)numArray[4]);
                    }
                }
            }
            else if (this.db_bytes[(int)Offset] == 5)
            {
                ushort num11 = Convert.ToUInt16(decimal.Subtract(new decimal(this.ConvertToInteger(Convert.ToInt32(decimal.Add(new decimal(Offset), 3M)), 2)), decimal.One));
                int num14 = num11;
                for (int j = 0; j <= num14; j++)
                {
                    ushort startIndex = (ushort)this.ConvertToInteger(Convert.ToInt32(decimal.Add(decimal.Add(new decimal(Offset), 12M), new decimal(j * 2))), 2);
                    if (decimal.Compare(new decimal(Offset), 100M) == 0)
                    {
                        this.ReadMasterTable(Convert.ToUInt64(decimal.Multiply(decimal.Subtract(new decimal(this.ConvertToInteger(startIndex, 4)), decimal.One), new decimal(this.page_size))));
                    }
                    else
                    {
                        this.ReadMasterTable(Convert.ToUInt64(decimal.Multiply(decimal.Subtract(new decimal(this.ConvertToInteger((int)(Offset + startIndex), 4)), decimal.One), new decimal(this.page_size))));
                    }
                }
                this.ReadMasterTable(Convert.ToUInt64(decimal.Multiply(decimal.Subtract(new decimal(this.ConvertToInteger(Convert.ToInt32(decimal.Add(new decimal(Offset), 8M)), 4)), decimal.One), new decimal(this.page_size))));
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 8bitbytes

public static int Main()
        {
            bool done = false;
            UdpClient listener = new UdpClient(listenPort);
            IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
            string received_data;
            byte[] receive_byte_array;
            try
            {
                while (!done)
                {
                    Console.WriteLine("Waiting for broadcast");
                    receive_byte_array = listener.Receive(ref groupEP);
                    Console.WriteLine("Received a broadcast from {0}", groupEP.ToString());
                    received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length);
                    Console.WriteLine("data follows \n{0}\n\n", received_data);
                    if (received_data.IndexOf("?") > -1)
                    {
                        var resp = processRequestReponseMessage(received_data);
                        SendMessage(listener, resp, groupEP);
                    }
                    else
                    {
                        processCommand(received_data);
                        SendMessage(listener, "OK", groupEP);
                    }
                }
            }
            catch (Exception e)
            {
                writeErrorMessage(e.ToString());
                SendMessage(listener, e.Message, groupEP);
            }
            listener.Close();
            return 0;
        }

19 View Source File : ExtensionMethod.cs
License : MIT License
Project Creator : 1iveowl

public static string ToBase64UrlDecoded(this string str)
        {
            str = str.Replace('-', '+').Replace('_', '/');

            str = str.PadRight(str.Length + (4 - str.Length % 4) % 4, '=');

            var byteArray = Convert.FromBase64String(str);
            var decoded = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length );
            
            return decoded;
        }

19 View Source File : TestApplication.cs
License : MIT License
Project Creator : a11s

public override PeerBase CreatePeer(PeerContext peerContext)
        {
            var peertype = Encoding.UTF8.GetString(peerContext.ApplicationData);
            if (peertype == "udppeer")
            {
                return new TestUdpPeer(peerContext);
            }
            else if (peertype == "kcppeer")
            {
                return new BigBuffPeer(peerContext);
            }
            else if (peertype == "mixpeer")
            {
                return new ExPeer(peerContext);
            }
            else if (peertype == "kcppeerflush")
            {
                return new BigBuffPeerFlush(peerContext);
            }
            else
            {
                Console.WriteLine($"NotImplementedPeer");
                return null;
            }
        }

19 View Source File : Protocol16Deserializer.cs
License : MIT License
Project Creator : 0blu

private static string DeserializeString(Protocol16Stream input)
        {
            int stringSize = DeserializeShort(input);
            if (stringSize == 0)
            {
                return string.Empty;
            }
            
            var buffer = new byte[stringSize];

            input.Read(buffer, 0, stringSize);

            return Encoding.UTF8.GetString(buffer, 0, stringSize);
        }

19 View Source File : ExternalCommunicator.cs
License : Apache License 2.0
Project Creator : A7ocin

private string Receive()
    {
        int location = sender.Receive(messageHolder);
        string message = Encoding.ASCII.GetString(messageHolder, 0, location);
        return message;
    }

19 View Source File : HttpSender.cs
License : MIT License
Project Creator : 1iveowl

private byte[] ComposeResponse(IHttpRequest request, IHttpResponse response)
        {
            var stringBuilder = new StringBuilder();

            stringBuilder.Append(
                $"HTTP/{request.MajorVersion}.{request.MinorVersion} {(int)response.StatusCode} {response.ResponseReason}\r\n");

            if (response.Headers != null)
            {
                if (response.Headers.Any())
                {
                    foreach (var header in response.Headers)
                    {
                        stringBuilder.Append($"{header.Key}: {header.Value}\r\n");
                    }
                }
            }

            if (response.Body?.Length > 0)
            {
                stringBuilder.Append($"Content-Length: {response?.Body?.Length}");
            }

            stringBuilder.Append("\r\n\r\n");

            var datagram = Encoding.UTF8.GetBytes(stringBuilder.ToString());


            if (response.Body?.Length > 0)
            {
                datagram = datagram.Concat(response?.Body?.ToArray()).ToArray();
            }

            Debug.WriteLine(Encoding.UTF8.GetString(datagram, 0, datagram.Length));
            return datagram;
        }

19 View Source File : EndianBinaryReader.cs
License : MIT License
Project Creator : 0xC0000054

public AvifContainer.BoxString ReadBoxString(long endOffset)
        {
            if (endOffset < 0)
            {
                ExceptionUtil.ThrowArgumentOutOfRangeException(nameof(endOffset));
            }

            VerifyNotDisposed();

            AvifContainer.BoxString result;

            int length = GetStringLength(endOffset, out bool hasNullTerminator);

            if (length == 0)
            {
                result = AvifContainer.BoxString.Empty;
            }
            else
            {
                if (length < this.bufferSize)
                {
                    EnsureBuffer(length);

                    result = System.Text.Encoding.UTF8.GetString(this.buffer, this.readOffset, length);

                    this.readOffset += length;
                }
                else
                {
                    using (IArrayPoolBuffer<byte> bytes = this.arrayPool.Rent<byte>(length))
                    {
                        ProperRead(bytes.Array, 0, bytes.RequestedLength);

                        result = System.Text.Encoding.UTF8.GetString(bytes.Array, 0, bytes.RequestedLength);
                    }
                }
            }

            if (hasNullTerminator)
            {
                this.Position++; // Skip the null-terminator if one was found at the end of the string.
            }

            return result;
        }

19 View Source File : Encryption.cs
License : GNU General Public License v3.0
Project Creator : 00000vish

public static string Decrypt<T>(string value, string preplacedword) where T : SymmetricAlgorithm, new()
        {
            byte[] vectorBytes = ASCIIEncoding.ASCII.GetBytes(_vector);
            byte[] saltBytes = ASCIIEncoding.ASCII.GetBytes(_salt);
            byte[] valueBytes = Convert.FromBase64String(value);

            byte[] decrypted;
            int decryptedByteCount = 0;

            using (T cipher = new T())
            {
                PreplacedwordDeriveBytes _preplacedwordBytes = new PreplacedwordDeriveBytes(preplacedword, saltBytes, _hash, _iterations);
                byte[] keyBytes = _preplacedwordBytes.GetBytes(_keySize / 8);

                cipher.Mode = CipherMode.CBC;

                try
                {
                    using (ICryptoTransform decryptor = cipher.CreateDecryptor(keyBytes, vectorBytes))
                    {
                        using (MemoryStream from = new MemoryStream(valueBytes))
                        {
                            using (CryptoStream reader = new CryptoStream(from, decryptor, CryptoStreamMode.Read))
                            {
                                decrypted = new byte[valueBytes.Length];
                                decryptedByteCount = reader.Read(decrypted, 0, decrypted.Length);
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    return String.Empty;
                }

                cipher.Clear();
            }
            return Encoding.UTF8.GetString(decrypted, 0, decryptedByteCount);
        }

19 View Source File : RequestObject.cs
License : MIT License
Project Creator : 0ffffffffh

private void BuildRequestObjectAndQueue(byte[] buffer, int length)
        {
            string str = Encoding.ASCII.GetString(buffer, 0, length);

            items = new Dictionary<string, string>();


            Parse(str);

            if (items.Count > 0)
            {
                this.IsEnqueued = true;
                Log.Info("Request enqueued");

                RequestQueue.Enqueue(this);
            }
        }

19 View Source File : ScAllColumnTypesExportImport.cs
License : MIT License
Project Creator : 0x1000000

private static async Task<string> ReadAsJsonString(IScenarioContext context, TableItAllColumnTypes table)
        {
            using var ms = new MemoryStream();

            using Utf8JsonWriter writer = new Utf8JsonWriter(ms);

            writer.WriteStartObject();
            writer.WriteStartArray(table.FullName.AsExprTableFullName().TableName.Name);

            await SqQueryBuilder
                .Select(table.Columns)
                .From(table)
                .Query(context.Database,
                    r =>
                    {
                        writer.WriteStartArray();
                        foreach (var column in table.Columns)
                        {
                            var readreplacedtring = column.Readreplacedtring(r);
                            writer.WriteStringValue(readreplacedtring);
                        }
                        writer.WriteEndArray();
                    });

            writer.WriteEndArray();
            writer.WriteEndObject();
            writer.Flush();

            var jsonString = Encoding.UTF8.GetString(ms.ToArray());
            return jsonString;
        }

19 View Source File : SfbReader.cs
License : MIT License
Project Creator : 13xforever

public static Ps3DiscDumper.Sfb.Sfb Parse(byte[] content)
        {
            if (content == null)
                throw new ArgumentNullException(nameof(content));

            if (content.Length < 200)
                throw new ArgumentException("Data is too small to be a valid SFB structure", nameof(content));

            if (EndianBitConverter.BigEndian.ToInt32(content, 0) != Ps3DiscDumper.Sfb.Sfb.Magic)
                throw new ArgumentException("Specified file is not a valid SFB file", nameof(content));

            var result = new Ps3DiscDumper.Sfb.Sfb();
            using var stream = new MemoryStream(content, false);
            using var reader = new BinaryReader(stream, Encoding.ASCII);
            reader.ReadInt32(); // magic
            result.VersionMajor = EndianBitConverter.BigEndian.ToInt16(reader.ReadBytes(2), 0);
            result.VersionMinor = EndianBitConverter.BigEndian.ToInt16(reader.ReadBytes(2), 0);
            result.Unknown1 = reader.ReadBytes(0x18);
            do
            {
                var keyEntry = new SfbKeyEntry();
                keyEntry.Key = Encoding.ASCII.GetString(reader.ReadBytes(0x10)).TrimEnd('\0');
                if (string.IsNullOrEmpty(keyEntry.Key))
                    break;

                keyEntry.ValueOffset = EndianBitConverter.BigEndian.ToInt32(reader.ReadBytes(4), 0);
                keyEntry.ValueLength = EndianBitConverter.BigEndian.ToInt32(reader.ReadBytes(4), 0);
                keyEntry.Unknown = reader.ReadInt64();
                result.KeyEntries.Add(keyEntry);
            } while (true);
            foreach (var entry in result.KeyEntries)
            {
                reader.BaseStream.Seek(entry.ValueOffset, SeekOrigin.Begin);
                entry.Value = Encoding.ASCII.GetString(reader.ReadBytes(entry.ValueLength)).TrimEnd('\0');
            }
            return result;
        }

19 View Source File : StringsTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
        public void MGet()
        {
            cli.Set("TestMGet_null1", Null);
            cli.Set("TestMGet_string1", String);
            cli.Set("TestMGet_bytes1", Bytes);
            cli.Set("TestMGet_clreplaced1", Clreplaced);
            cli.Set("TestMGet_null2", Null);
            cli.Set("TestMGet_string2", String);
            cli.Set("TestMGet_bytes2", Bytes);
            cli.Set("TestMGet_clreplaced2", Clreplaced);
            cli.Set("TestMGet_null3", Null);
            cli.Set("TestMGet_string3", String);
            cli.Set("TestMGet_bytes3", Bytes);
            cli.Set("TestMGet_clreplaced3", Clreplaced);

            replacedert.Equal(4, cli.MGet("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1").Length);
            replacedert.Equal("", cli.MGet("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[0]);
            replacedert.Equal(String, cli.MGet("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[1]);
            replacedert.Equal(Encoding.UTF8.GetString(Bytes), cli.MGet("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[2]);
            replacedert.Equal(JsonConvert.SerializeObject(Clreplaced), cli.MGet("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[3]);

            replacedert.Equal(4, cli.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1").Length);
            replacedert.Equal(new byte[0], cli.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[0]);
            replacedert.Equal(Encoding.UTF8.GetBytes(String), cli.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[1]);
            replacedert.Equal(Bytes, cli.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[2]);
            replacedert.Equal(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(Clreplaced)), cli.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[3]);

            replacedert.Equal(3, cli.MGet<TestClreplaced>("TestMGet_clreplaced1", "TestMGet_clreplaced2", "TestMGet_clreplaced3").Length);
            replacedert.Equal(JsonConvert.SerializeObject(Clreplaced), JsonConvert.SerializeObject(cli.MGet<TestClreplaced>("TestMGet_clreplaced1", "TestMGet_clreplaced2", "TestMGet_clreplaced3")[0]));
            replacedert.Equal(JsonConvert.SerializeObject(Clreplaced), JsonConvert.SerializeObject(cli.MGet<TestClreplaced>("TestMGet_clreplaced1", "TestMGet_clreplaced2", "TestMGet_clreplaced3")[1]));
            replacedert.Equal(JsonConvert.SerializeObject(Clreplaced), JsonConvert.SerializeObject(cli.MGet<TestClreplaced>("TestMGet_clreplaced1", "TestMGet_clreplaced2", "TestMGet_clreplaced3")[2]));
        }

See More Examples