System.IO.MemoryStream.ToArray()

Here are the examples of the csharp api System.IO.MemoryStream.ToArray() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

6711 Examples 7

19 View Source File : BufferExtension.cs
License : MIT License
Project Creator : 404Lcc

void IExtension.EndAppend(Stream stream, bool commit)
        {
            using (stream)
            {
                int len;
                if (commit && (len = (int)stream.Length) > 0)
                {
                    MemoryStream ms = (MemoryStream)stream;

                    if (buffer == null)
                    {   // allocate new buffer
                        buffer = ms.ToArray();
                    }
                    else
                    {   // resize and copy the data
                        // note: Array.Resize not available on CF
                        int offset = buffer.Length;
                        byte[] tmp = new byte[offset + len];
                        Helpers.BlockCopy(buffer, 0, tmp, 0, offset);

#if PORTABLE || WINRT // no GetBuffer() - fine, we'll use Read instead
                        int bytesRead;
                        long oldPos = ms.Position;
                        ms.Position = 0;
                        while (len > 0 && (bytesRead = ms.Read(tmp, offset, len)) > 0)
                        {
                            len -= bytesRead;
                            offset += bytesRead;
                        }
                        if(len != 0) throw new EndOfStreamException();
                        ms.Position = oldPos;
#else
                        Helpers.BlockCopy(Helpers.GetBuffer(ms), 0, tmp, offset, len);
#endif
                        buffer = tmp;
                    }
                }
            }
        }

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

public static byte[] Decompress(byte[] inputBytes)
        {
            MemoryStream newInStream = new MemoryStream(inputBytes);

            Decoder decoder = new Decoder();

            newInStream.Seek(0, 0);
            MemoryStream newOutStream = new MemoryStream();

            byte[] properties2 = new byte[5];
            if (newInStream.Read(properties2, 0, 5) != 5)
                throw (new Exception("input .lzma is too short"));
            long outSize = 0;
            for (int i = 0; i < 8; i++)
            {
                int v = newInStream.ReadByte();
                if (v < 0)
                    throw (new Exception("Can't Read 1"));
                outSize |= ((long)(byte)v) << (8 * i);
            }
            decoder.SetDecoderProperties(properties2);

            long compressedSize = newInStream.Length - newInStream.Position;
            decoder.Code(newInStream, newOutStream, compressedSize, outSize, null);

            byte[] b = newOutStream.ToArray();

            return b;
        }

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

[Fact]
        public void Append()
        {
            var key = "TestAppend_null";
            cli.Set(key, String);
            cli.Append(key, Null);
            replacedert.Equal(cli.Get(key), String);

            key = "TestAppend_string";
            cli.Set(key, String);
            cli.Append(key, String);
            replacedert.Equal(cli.Get(key), String + String);
            var ms = new MemoryStream();
            cli.Get(key, ms);
            replacedert.Equal(Encoding.UTF8.GetString(ms.ToArray()), String + String);
            ms.Close();

            key = "TestAppend_bytes";
            cli.Set(key, Bytes);
            cli.Append(key, Bytes);
            replacedert.Equal(Convert.ToBase64String(cli.Get<byte[]>(key)), Convert.ToBase64String(Bytes.Concat(Bytes).ToArray()));
        }

19 View Source File : EncodingUtil.cs
License : MIT License
Project Creator : 404Lcc

public static byte[] LengthEncode(byte[] bytes)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                using (BinaryWriter writer = new BinaryWriter(stream))
                {
                    writer.Write(bytes.Length);
                    writer.Write(bytes);
                    bytes = stream.ToArray();
                }
            }
            return bytes;
        }

19 View Source File : NAudioPlayer.cs
License : MIT License
Project Creator : 39M

public static AudioClip FromMp3Data(byte[] data)
    {
        // Load the data into a stream
        MemoryStream mp3stream = new MemoryStream(data);
        // Convert the data in the stream to WAV format
        Mp3FileReader mp3audio = new Mp3FileReader(mp3stream);
        WaveStream waveStream = WaveFormatConversionStream.CreatePcmStream(mp3audio);
        // Convert to WAV data
        WAV wav = new WAV(AudioMemStream(waveStream).ToArray());
        //Debug.Log(wav);
        AudioClip audioClip = AudioClip.Create("CustomClip", wav.SampleCount, 1, wav.Frequency, false);
        audioClip.SetData(wav.LeftChannel, 0);
        // Return the clip
        return audioClip;
    }

19 View Source File : Form1.cs
License : Mozilla Public License 2.0
Project Creator : 1M50RRY

private static byte[] EncryptAES(byte[] bytesToBeEncrypted, string preplacedword)
        {
            byte[] result = null;
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (RijndaelManaged rijndaelManaged = new RijndaelManaged())
                {
                    rijndaelManaged.KeySize = 256;
                    rijndaelManaged.BlockSize = 128;
                    Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(Encoding.ASCII.GetBytes(preplacedword), Encoding.ASCII.GetBytes(preplacedword), 1000);
                    rijndaelManaged.Key = rfc2898DeriveBytes.GetBytes(rijndaelManaged.KeySize / 8);
                    rijndaelManaged.IV = rfc2898DeriveBytes.GetBytes(rijndaelManaged.BlockSize / 8);
                    rijndaelManaged.Mode = CipherMode.CBC;
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndaelManaged.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
                        cryptoStream.Close();
                    }
                    result = memoryStream.ToArray();
                }
            }
            return result;
        }

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

public static byte[] Compress(byte[] inputBytes)
        {

            MemoryStream inStream = new MemoryStream(inputBytes);
            MemoryStream outStream = new MemoryStream();
            Encoder encoder = new Encoder();
            encoder.SetCoderProperties(propIDs, properties);
            encoder.WriteCoderProperties(outStream);
            long fileSize = inStream.Length;
            for (int i = 0; i < 8; i++)
                outStream.WriteByte((Byte)(fileSize >> (8 * i)));
            encoder.Code(inStream, outStream, -1, -1, null);
            return outStream.ToArray();
        }

19 View Source File : ProtobufNet.cs
License : MIT License
Project Creator : 1996v

public override byte[] Serialize<T>(T input)
        {
            using (var ms = new MemoryStream())
            {
                ProtoBuf.Serializer.Serialize(ms, input);
                return ms.ToArray();
            }
        }

19 View Source File : ImageExtensions.cs
License : MIT License
Project Creator : A-Tabeshfard

public static byte[] ImageToByteArray(this System.Drawing.Image imageIn)
        {
            using (var ms = new System.IO.MemoryStream())
            {
                imageIn.Save(ms, imageIn.RawFormat);
                return ms.ToArray();
            }
        }

19 View Source File : DotNetToJScript.cs
License : MIT License
Project Creator : 1y0n

public static string Generate()
        {
            try
            {
                /*
                if (Environment.Version.Major != 2)
                {
                    WriteError("This tool should only be run on v2 of the CLR");
                    Environment.Exit(1);
                }
                */

                string output_file = null;
                string entry_clreplaced_name = DEFAULT_ENTRY_CLreplaced_NAME;
                string additional_script = String.Empty;
                bool mscorlib_only = false;
                bool scriptlet_moniker = false;
                bool scriptlet_uninstall = false;
                bool enable_debug = false;
                RuntimeVersion version = RuntimeVersion.Auto;
                ScriptLanguage language = ScriptLanguage.JScript;
                Guid clsid = Guid.Empty;

                bool show_help = false;
                

                string replacedembly_path = Global_Var.dll_path;
                /*
                if (!File.Exists(replacedembly_path) || show_help)
                {
                    Console.Error.WriteLine(@"Usage: DotNetToJScript {0} [options] path\to\asm", VERSION);
                    Console.Error.WriteLine("Copyright (C) James Forshaw 2017. Licensed under GPLv3.");
                    Console.Error.WriteLine("Source code at https://github.com/tyranid/DotNetToJScript");
                    Console.Error.WriteLine("Options");
                    opts.WriteOptionDescriptions(Console.Error);
                    Environment.Exit(1);
                }
                */

                IScriptGenerator generator;
                switch (language)
                {
                    case ScriptLanguage.JScript:
                        generator = new JScriptGenerator();
                        break;
                    case ScriptLanguage.VBA:
                        generator = new VBAGenerator();
                        break;
                    case ScriptLanguage.VBScript:
                        generator = new VBScriptGenerator();
                        break;
                    default:
                        throw new ArgumentException("Invalid script language option");
                }

                byte[] replacedembly = File.ReadAllBytes(replacedembly_path);
                try
                {
                    HashSet<string> valid_clreplacedes = GetValidClreplacedes(replacedembly);
                    if (!valid_clreplacedes.Contains(entry_clreplaced_name))
                    {
                        WriteError("Error: Clreplaced '{0}' not found is replacedembly.", entry_clreplaced_name);
                        if (valid_clreplacedes.Count == 0)
                        {
                            WriteError("Error: replacedembly doesn't contain any public, default constructable clreplacedes");
                        }
                        else
                        {
                            WriteError("Use one of the follow options to specify a valid clreplacedes");
                            foreach (string name in valid_clreplacedes)
                            {
                                WriteError("-c {0}", name);
                            }
                        }
                        Environment.Exit(1);
                    }
                }
                catch (Exception)
                {
                    WriteError("Error: loading replacedembly information.");
                    WriteError("The generated script might not work correctly");
                }

                BinaryFormatter fmt = new BinaryFormatter();
                MemoryStream stm = new MemoryStream();
                fmt.Serialize(stm, mscorlib_only ? BuildLoaderDelegateMscorlib(replacedembly) : BuildLoaderDelegate(replacedembly));

                string script = generator.GenerateScript(stm.ToArray(), entry_clreplaced_name, additional_script, version, enable_debug);
                if (scriptlet_moniker || scriptlet_uninstall)
                {
                    if (!generator.SupportsScriptlet)
                    {
                        throw new ArgumentException(String.Format("{0} generator does not support Scriptlet output", generator.ScriptName));
                    }
                    script = CreateScriptlet(script, generator.ScriptName, scriptlet_uninstall, clsid);
                }

                /*
                if (!String.IsNullOrEmpty(output_file))
                {
                    File.WriteAllText(output_file, script, new UTF8Encoding(false));
                }
                else
                {
                    Console.WriteLine(script);
                }
                */
                return script;
            }
            catch (Exception ex)
            {
                ReflectionTypeLoadException tex = ex as ReflectionTypeLoadException;
                if (tex != null)
                {
                    WriteError("Couldn't load replacedembly file");
                    foreach (var e in tex.LoaderExceptions)
                    {
                        WriteError(e.Message);
                    }
                }
                else
                {
                    WriteError(ex.Message);
                }
                return null;
            }
        }

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

public byte[] WriteData()
        {
            //保存当前pos
            var pos = (int) Writer.BaseStream.Position;
            //填充头部
            PutHeader();
            //填充包体
            BodyStream = new MemoryStream();
            BodyWriter = new BinaryWriter(BodyStream);
            PutBody();
            //需要加密的包体
            BodyDecrypted = BodyStream.ToArray();
            var enc = EncryptBody(BodyDecrypted, 0, BodyDecrypted.Length);
            // 加密内容写入最终buf
            Writer.Write(enc);
            // 填充尾部
            PutTail();
            // 回填
            PostFill(pos);
            return Writer.BaseStream.ToBytesArray();
        }

19 View Source File : Compression.cs
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec

public static byte[] Zip(string str)
        {
            var bytes = Encoding.UTF8.GetBytes(str);

            using (var msi = new MemoryStream(bytes))
            using (var mso = new MemoryStream())
            {
                using (var gs = new GZipStream(mso, CompressionMode.Compress))
                {
                    CopyTo(msi, gs);
                }

                return mso.ToArray();
            }
        }

19 View Source File : StreamSerializeTest.cs
License : MIT License
Project Creator : 1996v

[Theory]
        [InlineData(typeof(sbyte))]
        [InlineData(typeof(Int16))]
        [InlineData(typeof(Int32))]
        [InlineData(typeof(Dictionary<sbyte, List<object>>))]
        [InlineData(typeof(Dictionary<Int16, List<object>>))]
        [InlineData(typeof(List<string>))]
        [InlineData(typeof(List<object>))]
        [InlineData(typeof(List<List<object>>))]
        [InlineData(typeof(byte[]))]
        [InlineData(typeof(char[]))]
        [InlineData(typeof(double[]))]
        [InlineData(typeof(DateTime[]))]
        [InlineData(typeof(_clreplaced1))]
        [InlineData(typeof(_clreplaced2))]
        [InlineData(typeof(_clreplaced3))]
        public void MemoryStreamSerializeAsyncTest(Type type)
        {
            var obj = RandomHelper.RandomValueWithOutStringEmpty(type);
            byte[] buf = BssomSerializer.Serialize(obj);

            MemoryStream stream = new MemoryStream();
            BssomSerializer.SerializeAsync(stream, obj).Wait();

            stream.Position.Is(buf.Length);
            buf.Is(stream.ToArray());
        }

19 View Source File : EncodingUtil.cs
License : MIT License
Project Creator : 404Lcc

public static byte[] SerializationEncode(object obj)
        {
            byte[] bytes;
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, obj);
                bytes = stream.ToArray();
            }
            return bytes;
        }

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

public static Ird 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 IRD structure", nameof(content));

            if (BitConverter.ToInt32(content, 0) != Ird.Magic)
                using (var compressedStream = new MemoryStream(content, false))
                using (var gzip = new GZipStream(compressedStream, CompressionMode.Decompress))
                using (var decompressedStream = new MemoryStream())
                {
                    gzip.CopyTo(decompressedStream);
                    content = decompressedStream.ToArray();
                }
            if (BitConverter.ToInt32(content, 0) != Ird.Magic)
                throw new FormatException("Not a valid IRD file");

            var result = new Ird();
            using (var stream = new MemoryStream(content, false))
            using (var reader = new BinaryReader(stream, Encoding.UTF8))
            {
                reader.ReadInt32(); // magic
                result.Version = reader.ReadByte();
                result.ProductCode = Encoding.ASCII.GetString(reader.ReadBytes(9));
                result.replacedleLength = reader.ReadByte();
                result.replacedle = Encoding.UTF8.GetString(reader.ReadBytes(result.replacedleLength));
                result.UpdateVersion = Encoding.ASCII.GetString(reader.ReadBytes(4)).Trim();
                result.GameVersion = Encoding.ASCII.GetString(reader.ReadBytes(5)).Trim();
                result.AppVersion = Encoding.ASCII.GetString(reader.ReadBytes(5)).Trim();
                if (result.Version == 7)
                    result.Id = reader.ReadInt32();
                result.HeaderLength = reader.ReadInt32();
                result.Header = reader.ReadBytes(result.HeaderLength);
                result.FooterLength = reader.ReadInt32();
                result.Footer = reader.ReadBytes(result.FooterLength);
                result.RegionCount = reader.ReadByte();
                result.RegionMd5Checksums = new List<byte[]>(result.RegionCount);
                for (var i = 0; i < result.RegionCount; i++)
                    result.RegionMd5Checksums.Add(reader.ReadBytes(16));
                result.FileCount = reader.ReadInt32();
                result.Files = new List<IrdFile>(result.FileCount);
                for (var i = 0; i < result.FileCount; i++)
                {
                    var file = new IrdFile();
                    file.Offset = reader.ReadInt64();
                    file.Md5Checksum = reader.ReadBytes(16);
                    result.Files.Add(file);
                }
                result.Unknown = reader.ReadInt32();
                if (result.Version == 9)
                    result.Pic = reader.ReadBytes(115);
                result.Data1 = reader.ReadBytes(16);
                result.Data2 = reader.ReadBytes(16);
                if (result.Version < 9)
                    result.Pic = reader.ReadBytes(115);
                result.Uid = reader.ReadInt32();
                var dataLength = reader.BaseStream.Position;
                result.Crc32 = reader.ReadUInt32();

                var crc32 = Crc32Algorithm.Compute(content, 0, (int)dataLength);
                if (result.Crc32 != crc32)
                    throw new InvalidDataException($"Corrupted IRD data, expected {result.Crc32:x8}, but was {crc32:x8}");
            }
            return result;
        }

19 View Source File : ObjectSerializationExtension.cs
License : MIT License
Project Creator : 734843327

public static byte[] SerializeToByteArray(this object obj)
		{
			if (obj == null)
			{
				return null;
			}
			var bf = new BinaryFormatter();
			using (var ms = new MemoryStream())
			{
				bf.Serialize(ms, obj);
				return ms.ToArray();
			}
		}

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

public Byte[] ReadAll()
        {
            var ns = _stream as NetworkStream;
            if (ns != null)
            {
                using (var ms = new MemoryStream())
                {
                    try
                    {
                        var data = new byte[1024];
                        while (ns.DataAvailable && ns.CanRead)
                        {
                            int numBytesRead = 0;
                            lock (_streamLock)
                                numBytesRead = ns.Read(data, 0, data.Length);
                            if (numBytesRead <= 0) break;
                            ms.Write(data, 0, numBytesRead);
                            if (numBytesRead < data.Length) break;
                        }
                    }
                    catch { }
                    return ms.ToArray();
                }
            }
            var ss = _stream as SslStream;
            if (ss != null)
            {
                using (var ms = new MemoryStream())
                {
                    try
                    {
                        var data = new byte[1024];
                        while (ss.CanRead)
                        {
                            int numBytesRead = 0;
                            lock (_streamLock)
                                numBytesRead = ss.Read(data, 0, data.Length);
                            if (numBytesRead <= 0) break;
                            ms.Write(data, 0, numBytesRead);
                            if (numBytesRead < data.Length) break;
                        }
                    }
                    catch { }
                    return ms.ToArray();
                }
            }
            return new byte[0];
        }

19 View Source File : IPCSupport.cs
License : GNU General Public License v3.0
Project Creator : 9E4ECDDE

public byte[] ToByteArray()
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    using (BinaryWriter binaryWriter = new BinaryWriter(ms))
                    {
                        binaryWriter.Write(name);
                        binaryWriter.Write(boneCount);
                        List<byte[]> bonesBytes = new List<byte[]>(bones.Select((b) => b.ToByteArray()));
                        foreach (byte[] boneByteData in bonesBytes)
                        {
                            binaryWriter.Write(boneByteData.Length);
                            binaryWriter.Write(boneByteData);
                        }
                        return ms.ToArray();
                    }
                }
            }

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

[Test]
        public void BasicTest()
        {
            TestFileSystem fileSystem = new TestFileSystem();

            fileSystem.AddFile("A\\table1.cs", TestTable1Text);

            var generated = ExistingCodeExplorer
                .EnumerateTableDescriptorsModelAttributes("A", fileSystem)
                .ParseAttribute(true)
                .Createreplacedysis()
                .Select(meta=> ModelClreplacedGenerator.Generate(meta, "Org", "", true, fileSystem, out _).SyntaxTree)
                .ToList();

            var trees = new List<SyntaxTree>();

            foreach (var syntaxTree in generated)
            {
                trees.Add(CSharpSyntaxTree.ParseText(syntaxTree.ToString()));
            }

            trees.Add(CSharpSyntaxTree.ParseText(TestTable1Text));

            var compilation = CSharpCompilation.Create("SqModels",
                trees,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable)); 

            compilation = compilation.AddReferences(
                MetadataReference.CreateFromFile(replacedembly.Load("netstandard, Version=2.0.0.0").Location),
                MetadataReference.CreateFromFile(typeof(object).replacedembly.GetreplacedemblyLocation()),
                MetadataReference.CreateFromFile(replacedembly
                    .Load("System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
                    .Location),
                MetadataReference.CreateFromFile(typeof(SqQueryBuilder).replacedembly.GetreplacedemblyLocation()));

            MemoryStream ms = new MemoryStream();

            var emitResult = compilation.Emit(ms);
            if (!emitResult.Success)
            {
                Diagnostic first = emitResult.Diagnostics.First();

                var sourceCode = first.Location.SourceTree?.ToString();
                var s = sourceCode?.Substring(first.Location.SourceSpan.Start, first.Location.SourceSpan.Length);
                Console.WriteLine(sourceCode);
                replacedert.Fail(first.GetMessage()+ (string.IsNullOrEmpty(s)?null:$" \"{s}\""));
            }

            var replacedembly = replacedembly.Load(ms.ToArray());

            var allTypes = replacedembly.GetTypes();

            replacedert.AreEqual(21, allTypes.Length);
        }

19 View Source File : ImageExtensions.cs
License : MIT License
Project Creator : A-Tabeshfard

public static byte[] IconToBytes(this System.Drawing.Icon icon)
        {
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                icon.Save(ms);
                return ms.ToArray();
            }
        }

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

async public static Task<string> GetBodyRawText(HttpRequest req) {
			var charsetIndex = req.ContentType.IndexOf("charset=");
			var charset = Encoding.UTF8;
			if (charsetIndex != -1) {
				var charsetText = req.ContentType.Substring(charsetIndex + 8);
				charsetIndex = charsetText.IndexOf(';');
				if (charsetIndex != -1) charsetText = charsetText.Remove(charsetIndex);
				switch (charsetText.ToLower()) {
					case "utf8":
					case "utf-8":
						break;
					default:
						charset = Encoding.GetEncoding(charsetText);
						break;
				}
			}
			req.Body.Position = 0;
			using (var ms = new MemoryStream()) {
				await req.Body.CopyToAsync(ms);
				return charset.GetString(ms.ToArray());
			}
		}

19 View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : 2dust

public static string UnGzip(byte[] buf)
        {
            MemoryStream sb = new MemoryStream();
            using (GZipStream input = new GZipStream(new MemoryStream(buf),
            CompressionMode.Decompress,
            false))
            {
                input.CopyTo(sb);
            }
            return Encoding.UTF8.GetString(sb.ToArray());
        }

19 View Source File : cAES256.cs
License : MIT License
Project Creator : 0xPh0enix

public static byte[] Decrypt(byte[] bData, byte[] bKey)
        {
            byte[] bDecrypted = null;

            using (MemoryStream mStream = new MemoryStream())
            {
                using (RijndaelManaged rmAES = new RijndaelManaged())
                {
                    rmAES.KeySize = 256;
                    rmAES.BlockSize = 128;

                    Rfc2898DeriveBytes rfcKey = new Rfc2898DeriveBytes(bKey, bSalt, 1000);

                    rmAES.Key = rfcKey.GetBytes(rmAES.KeySize / 8);
                    rmAES.IV = rfcKey.GetBytes(rmAES.BlockSize / 8);

                    rmAES.Mode = CipherMode.CBC;

                    using (CryptoStream cStream = new CryptoStream(mStream, rmAES.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cStream.Write(bData, 0, bData.Length);
                        cStream.Close();
                    }

                    bDecrypted = mStream.ToArray();
                }
            }

            return bDecrypted;
        }

19 View Source File : Compression.cs
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec

public static string Unzip(byte[] bytes)
        {
            using (var msi = new MemoryStream(bytes))
            using (var mso = new MemoryStream())
            {
                using (var gs = new GZipStream(msi, CompressionMode.Decompress))
                {
                    CopyTo(gs, mso);
                }

                return Encoding.UTF8.GetString(mso.ToArray());
            }
        }

19 View Source File : Server.cs
License : MIT License
Project Creator : 1ZouLTReX1

public bool ReceiveOnce()
    {
        /*
         * returns one message in a byte array which then get processed by the client
         * one message may require serveral calls to '.Receive' function.
         */

        // Receive the response from the remote device.
        if (offset >= bytesRec)
        {
            if (SafeReceive(ref buffer, ref bytesRec, ref offset))
                return false;
        }

        len = Globals.DeSerializeLenPrefix(buffer, offset);
        offset += sizeof(int);

        while (len > 0)
        {
            cut = Math.Min(len, bytesRec - offset);
            ms.Write(buffer, offset, cut);
            len -= cut;
            offset += cut;

            if (len > 0)
            {
                // The left over of the previous message.
                if (SafeReceive(ref buffer, ref bytesRec, ref offset))
                    return false;
            }
        }

        // Process one message from the stream.
        data = ms.ToArray();
        // Clear the buffer.
        ms.SetLength(0);

        // Process the new received message.
        ProcessMessage(data);
        return true;
    }

19 View Source File : ProtobufUtil.cs
License : MIT License
Project Creator : 404Lcc

public static byte[] Serialize(object message)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                Serializer.Serialize(stream, message);
                return stream.ToArray();
            }
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] preplacedwordBytes)
        {
            byte[] encryptedBytes = null;

            byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

            using (MemoryStream ms = new MemoryStream())
            {
                using (RijndaelManaged AES = new RijndaelManaged())
                {
                    AES.KeySize = 256;
                    AES.BlockSize = 128;

                    var key = new Rfc2898DeriveBytes(preplacedwordBytes, saltBytes, 1000);
                    AES.Key = key.GetBytes(AES.KeySize / 8);
                    AES.IV = key.GetBytes(AES.BlockSize / 8);

                    AES.Mode = CipherMode.CBC;

                    using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
                        cs.Close();
                    }
                    encryptedBytes = ms.ToArray();
                }
            }

            return encryptedBytes;
        }

19 View Source File : StreamSerializeTest.cs
License : MIT License
Project Creator : 1996v

[Theory]
        [InlineData(typeof(sbyte))]
        [InlineData(typeof(Int16))]
        [InlineData(typeof(Int32))]
        [InlineData(typeof(Dictionary<sbyte, List<object>>))]
        [InlineData(typeof(Dictionary<Int16, List<object>>))]
        [InlineData(typeof(List<string>))]
        [InlineData(typeof(List<object>))]
        [InlineData(typeof(List<List<object>>))]
        [InlineData(typeof(byte[]))]
        [InlineData(typeof(char[]))]
        [InlineData(typeof(double[]))]
        [InlineData(typeof(DateTime[]))]
        [InlineData(typeof(_clreplaced1))]
        [InlineData(typeof(_clreplaced2))]
        [InlineData(typeof(_clreplaced3))]
        public void MemoryStreamSerializeTest(Type type)
        {
            var obj = RandomHelper.RandomValueWithOutStringEmpty(type);
            byte[] buf = BssomSerializer.Serialize(obj);

            MemoryStream stream = new MemoryStream();
            BssomSerializer.Serialize(stream, obj);

            stream.Position.Is(buf.Length);
            buf.Is(stream.ToArray());
        }

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

public static byte[] ImageToBytes(Image image)
        {
            var format = image.RawFormat;
            using (var ms = new MemoryStream())
            {
                if (format.Equals(ImageFormat.Jpeg))
                {
                    image.Save(ms, ImageFormat.Jpeg);
                }
                else if (format.Equals(ImageFormat.Png))
                {
                    image.Save(ms, ImageFormat.Png);
                }
                else if (format.Equals(ImageFormat.Bmp))
                {
                    image.Save(ms, ImageFormat.Bmp);
                }
                else if (format.Equals(ImageFormat.Gif))
                {
                    image.Save(ms, ImageFormat.Gif);
                }
                else if (format.Equals(ImageFormat.Icon))
                {
                    image.Save(ms, ImageFormat.Icon);
                }

                //var buffer = new byte[ms.Length];
                ////Image.Save()会改变MemoryStream的Position,需要重新Seek到Begin
                //ms.Seek(0, SeekOrigin.Begin);
                //ms.Read(buffer, 0, buffer.Length);
                //return buffer;
                return ms.ToArray();
            }
        }

19 View Source File : cAES256.cs
License : MIT License
Project Creator : 0xPh0enix

public static byte[] Encrypt(byte[] bData, byte[] bKey)
        {
            byte[] bEncrypted = null;

            using (MemoryStream mStream = new MemoryStream())
            {
                using (RijndaelManaged rmAES = new RijndaelManaged())
                {
                    rmAES.KeySize = 256;
                    rmAES.BlockSize = 128;

                    Rfc2898DeriveBytes rfcKey = new Rfc2898DeriveBytes(bKey, bSalt, 1000);

                    rmAES.Key = rfcKey.GetBytes(rmAES.KeySize / 8);
                    rmAES.IV = rfcKey.GetBytes(rmAES.BlockSize / 8);

                    rmAES.Mode = CipherMode.CBC;

                    using (CryptoStream cStream = new CryptoStream(mStream, rmAES.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cStream.Write(bData, 0, bData.Length);
                        cStream.Close();
                    }
                    bEncrypted = mStream.ToArray();
                }
            }

            return bEncrypted;
        }

19 View Source File : EncodingUtil.cs
License : MIT License
Project Creator : 404Lcc

public static byte[] SocketModelEncode(SocketModel model)
        {
            byte[] bytes;
            using (MemoryStream stream = new MemoryStream())
            {
                using (BinaryWriter writer = new BinaryWriter(stream))
                {
                    writer.Write(model.type);
                    writer.Write(model.area);
                    writer.Write(model.command);
                    if (model.message != null)
                    {
                        writer.Write(SerializationEncode(model.message));
                    }
                    bytes = stream.ToArray();
                }
            }
            return bytes;

        }

19 View Source File : StreamSerializeTest.cs
License : MIT License
Project Creator : 1996v

public byte[] ToArray() => this.stream.ToArray();

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

public static byte[] ToBytesArray(this Stream stream)
        {
            return ((MemoryStream) stream).ToArray();
        }

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

private static async Task Step18ExportToJson(ISqDatabase database)
        {
            var tableUser = new TableUser(Alias.Empty);

            var selectExpr = Select(tableUser.FirstName, tableUser.LastName)
                .From(tableUser)
                .Where(tableUser.LastName == "Sturman")
                .Done();

            //Exporting
            var memoryStream = new MemoryStream();
            var jsonWriter = new Utf8JsonWriter(memoryStream);
            selectExpr.SyntaxTree().ExportToJson(jsonWriter);

            string json = Encoding.UTF8.GetString(memoryStream.ToArray());

            Console.WriteLine(json);

            //Importing
            var restored = (ExprQuerySpecification)ExprDeserializer
                .DeserializeFormJson(JsonDoreplacedent.Parse(json).RootElement);

            var result = await restored
                .QueryList(database, r => (tableUser.FirstName.Read(r), tableUser.LastName.Read(r)));

            foreach (var name in result)
            {
                Console.WriteLine(name);
            }
        }

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

public byte[] Md52()
        {
            var byteBuffer = new BinaryWriter(new MemoryStream());
            byteBuffer.Write(MD51);
            byteBuffer.BeWrite(0);
            byteBuffer.BeWrite(QQ);
            return MD5.Create().ComputeHash(((MemoryStream) byteBuffer.BaseStream).ToArray());
        }

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

[Fact]
		public void Append() {
			var key = "TestAppend_null";
			rds.Set(key, base.String);
			rds.Append(key, base.Null);
			replacedert.Equal(rds.Get(key), base.String);

			key = "TestAppend_string";
			rds.Set(key, base.String);
			rds.Append(key, base.String);
			replacedert.Equal(rds.Get(key), base.String + base.String);
			var ms = new MemoryStream();
			rds.Get(key, ms);
			replacedert.Equal(Encoding.UTF8.GetString(ms.ToArray()), base.String + base.String);
			ms.Close();

			key = "TestAppend_bytes";
			rds.Set(key, base.Bytes);
			rds.Append(key, base.Bytes);
			replacedert.Equal(Convert.ToBase64String(rds.Get<byte[]>(key)), Convert.ToBase64String(base.Bytes.Concat(base.Bytes).ToArray()));
		}

19 View Source File : SimpleJSON.cs
License : MIT License
Project Creator : 734843327

public string SaveToBase64()
		{
			using (var stream = new System.IO.MemoryStream())
			{
				SaveToStream(stream);
				stream.Position = 0;
				return System.Convert.ToBase64String(stream.ToArray());
			}
		}

19 View Source File : DefaultCaptchaImageGenerator.cs
License : MIT License
Project Creator : 1992w

public byte[] Generate(int width, int height, string captchaCode)
        {
            using (Bitmap baseMap = new Bitmap(width, height))
            {
                using (Graphics graph = Graphics.FromImage(baseMap))
                {

                    graph.Clear(GetRandomLightColor());

                    DrawCaptchaCode(graph, width, height, captchaCode);
                    DrawDisorderLine(graph, width, height);
                    AdjustRippleEffect(baseMap);

                    MemoryStream ms = new MemoryStream();

                    baseMap.Save(ms, ImageFormat.Png);

                    return ms.ToArray();
                }
            }
        }

19 View Source File : HTTP.cs
License : MIT License
Project Creator : 944095635

private byte[] GetByte()
        {
            byte[] ResponseByte = null;
            using (MemoryStream _stream = new MemoryStream())
            {
                //GZIIP处理
                if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
                {
                    //开始读取流并设置编码方式
                    new GZipStream(response.GetResponseStream(), CompressionMode.Decompress).CopyTo(_stream, 10240);
                }
                else
                {
                    //开始读取流并设置编码方式
                    response.GetResponseStream().CopyTo(_stream, 10240);
                }
                //获取Byte
                ResponseByte = _stream.ToArray();
            }
            return ResponseByte;
        }

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

public byte[] Prepare(RedisCommand command)
        {
            var parts = command.Command.Split(' ');
            int length = parts.Length + command.Arguments.Length;
            StringBuilder sb = new StringBuilder();
            sb.Append(MultiBulk).Append(length).Append(EOL);

            foreach (var part in parts)
                sb.Append(Bulk).Append(_io.Encoding.GetByteCount(part)).Append(EOL).Append(part).Append(EOL);

            MemoryStream ms = new MemoryStream();
            var data = _io.Encoding.GetBytes(sb.ToString());
            ms.Write(data, 0, data.Length);

            foreach (var arg in command.Arguments)
            {
                if (arg != null && arg.GetType() == typeof(byte[]))
                {
                    data = arg as byte[];
                    var data2 = _io.Encoding.GetBytes($"{Bulk}{data.Length}{EOL}");
                    ms.Write(data2, 0, data2.Length);
                    ms.Write(data, 0, data.Length);
                    ms.Write(new byte[] { 13, 10 }, 0, 2);
                }
                else
                {
                    string str = String.Format(CultureInfo.InvariantCulture, "{0}", arg);
                    data = _io.Encoding.GetBytes($"{Bulk}{_io.Encoding.GetByteCount(str)}{EOL}{str}{EOL}");
                    ms.Write(data, 0, data.Length);
                }
                //string str = String.Format(CultureInfo.InvariantCulture, "{0}", arg);
                //sb.Append(Bulk).Append(_io.Encoding.GetByteCount(str)).Append(EOL).Append(str).Append(EOL);
            }

            return ms.ToArray();
        }

19 View Source File : IPCSupport.cs
License : GNU General Public License v3.0
Project Creator : 9E4ECDDE

public unsafe byte[] ToByteArray()
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    using (BinaryWriter binaryWriter = new BinaryWriter(ms))
                    {
                        binaryWriter.Write(name);
                        binaryWriter.Write(damping);
                        binaryWriter.Write(elasticity);
                        binaryWriter.Write(stiffness);
                        binaryWriter.Write(inert);
                        binaryWriter.Write(radius);
                        binaryWriter.Write(endLength);
                        binaryWriter.Write(endOffset.x);
                        binaryWriter.Write(endOffset.y);
                        binaryWriter.Write(endOffset.z);
                        binaryWriter.Write(gravity.x);
                        binaryWriter.Write(gravity.y);
                        binaryWriter.Write(gravity.z);
                        binaryWriter.Write(force.x);
                        binaryWriter.Write(force.y);
                        binaryWriter.Write(force.z);
                        return ms.ToArray();
                    }
                }
            }

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

public static byte[] ToBytes(this Stream stream) {
            if (stream is MemoryStream ms)
                return ms.ToArray();

            long length;
            if (stream.CanSeek) {
                try {
                    length = stream.Length - stream.Position;
                } catch {
                    length = 0;
                }
            } else {
                length = 0;
            }

            if (length != 0) {
                byte[] data = new byte[length];
                using (ms = new MemoryStream(data, 0, (int) length, true, true)) {
                    stream.CopyTo(ms);
                }
                return data;
            }

            using (ms = new()) {
                stream.CopyTo(ms);
                length = ms.Position;
                ms.Seek(0, SeekOrigin.Begin);
                byte[] buffer = ms.GetBuffer();
                if (buffer.Length != length)
                    buffer = ms.ToArray();
                return buffer;
            }
        }

19 View Source File : ImageExtensions.cs
License : MIT License
Project Creator : A-Tabeshfard

public static byte[] ToBytes(this System.Drawing.Image image, System.Drawing.Imaging.ImageFormat format)
        {
            if (image == null)
                throw new System.ArgumentNullException(nameof(image));

            if (format == null)
                throw new System.ArgumentNullException(nameof(format));

            using (var stream = new System.IO.MemoryStream())
            {
                image.Save(stream, format);
                return stream.ToArray();
            }
        }

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

public static byte[] ReadFile(string path) {
				if (File.Exists(path)) {
					string destFileName = Path.GetTempFileName();
					File.Copy(path, destFileName, true);
					int read = 0;
					byte[] data = new byte[1024];
					using (MemoryStream ms = new MemoryStream()) {
						using (FileStream fs = new FileStream(destFileName, FileMode.OpenOrCreate, FileAccess.Read)) {
							do {
								read = fs.Read(data, 0, data.Length);
								if (read <= 0) break;
								ms.Write(data, 0, read);
							} while (true);
						}
						File.Delete(destFileName);
						data = ms.ToArray();
					}
					return data;
				}
				return new byte[] { };
			}

19 View Source File : DotNetToJScript.cs
License : MIT License
Project Creator : 1y0n

static string CreateScriptlet(string script, string script_name, bool register_script, Guid clsid)
        {
            XmlDoreplacedent doc = new XmlDoreplacedent();
            doc.LoadXml(Global_Var.scriptlet_template);
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.NewLineOnAttributes = true;
            settings.Encoding = new UTF8Encoding(false);

            XmlElement reg_node = (XmlElement)doc.SelectSingleNode("/package/component/registration");
            XmlNode root_node = register_script ? reg_node : doc.SelectSingleNode("/package/component");
            XmlNode script_node = root_node.AppendChild(doc.CreateElement("script"));
            script_node.Attributes.Append(doc.CreateAttribute("language")).Value = script_name;
            script_node.AppendChild(doc.CreateCDataSection(script));
            if (clsid != Guid.Empty)
            {
                reg_node.SetAttribute("clreplacedid", clsid.ToString("B"));
            }

            using (MemoryStream stm = new MemoryStream())
            {
                using (XmlWriter writer = XmlWriter.Create(stm, settings))
                {
                    doc.Save(writer);
                }
                return Encoding.UTF8.GetString(stm.ToArray());
            }
        }

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

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

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

                cipher.Mode = CipherMode.CBC;

                using (ICryptoTransform encryptor = cipher.CreateEncryptor(keyBytes, vectorBytes))
                {
                    using (MemoryStream to = new MemoryStream())
                    {
                        using (CryptoStream writer = new CryptoStream(to, encryptor, CryptoStreamMode.Write))
                        {
                            writer.Write(valueBytes, 0, valueBytes.Length);
                            writer.FlushFinalBlock();
                            encrypted = to.ToArray();
                        }
                    }
                }
                cipher.Clear();
            }
            return Convert.ToBase64String(encrypted);
        }

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

[Test]
        public async Task BasicTest()
        {

            using var dbManager = new DbManager(new DbManagerTest(),
                new SqlConnection("Initial Catalog=_1_2_3tbl;"),
                new GenTablesOptions(ConnectionType.MsSql, "fake", "Tab", "", "MyTables", verbosity: Verbosity.Quiet));

            var tables = await dbManager.SelectTables();

            replacedert.AreEqual(2, tables.Count);

            var tableMap = tables.ToDictionary(t => t.DbName);

            IReadOnlyDictionary<TableRef, ClreplacedDeclarationSyntax> existingCode =
                new Dictionary<TableRef, ClreplacedDeclarationSyntax>();

            var generator =
                new TableClreplacedGenerator(tableMap, "MyCompany.MyProject.Tables", existingCode);


            var trees = tables.Select(t => CSharpSyntaxTree.Create(generator.Generate(t, out _))).ToList();

            var compilation = CSharpCompilation.Create("Tables",
                trees,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            compilation = compilation.AddReferences(
                MetadataReference.CreateFromFile(replacedembly.Load("netstandard, Version=2.0.0.0").Location),
                MetadataReference.CreateFromFile(typeof(object).replacedembly.GetreplacedemblyLocation()),
                MetadataReference.CreateFromFile(replacedembly
                    .Load("System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
                    .Location),
                MetadataReference.CreateFromFile(typeof(SqQueryBuilder).replacedembly.GetreplacedemblyLocation()));

            MemoryStream ms = new MemoryStream();

            var emitResult = compilation.Emit(ms);
            if (!emitResult.Success)
            {
                replacedert.Fail(emitResult.Diagnostics.FirstOrDefault()?.GetMessage());
            }

            var replacedembly = replacedembly.Load(ms.ToArray());

            var allTypes = replacedembly.GetTypes();

            var table1 = (TableBase) Activator.CreateInstance(allTypes.Find(t => t.Name == tables[0].Name));
            replacedert.NotNull(table1);
            var table2 = (TableBase) Activator.CreateInstance(allTypes.Find(t => t.Name == tables[1].Name));
            replacedert.NotNull(table2);


            string table1ExpectedSql =
                "CREATE TABLE [dbo].[TableZ]([Id] int NOT NULL  IDENreplacedY (1, 1) DEFAULT (0),[ValueA] [nvarchar](255) NOT NULL DEFAULT (''),[Value_A] decimal(2,6),CONSTRAINT [PK_dbo_TableZ] PRIMARY KEY ([Id]));";
            replacedert.AreEqual(table1ExpectedSql, TSqlExporter.Default.ToSql(table1.Script.Create()));

            string table2ExpectedSql =
                "CREATE TABLE [dbo].[TableA]([Id] int NOT NULL  IDENreplacedY (1, 1) DEFAULT (0),[Value] datetime NOT NULL DEFAULT (GETUTCDATE()),CONSTRAINT [PK_dbo_TableA] PRIMARY KEY ([Id]),CONSTRAINT [FK_dbo__TableA_to_dbo__TableZ] FOREIGN KEY ([Id]) REFERENCES [dbo].[TableZ]([Id]),INDEX [IX_dbo_TableA_Value_DESC] UNIQUE([Value] DESC));";
            replacedert.AreEqual(table2ExpectedSql, TSqlExporter.Default.ToSql(table2.Script.Create()));
        }

19 View Source File : Program.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 0xthirteen

static void Main(string[] args)
        {
            AppDomain.CurrentDomain.replacedemblyResolve += (sender, argtwo) => {
                replacedembly thisreplacedembly = replacedembly.GetEntryreplacedembly();
                String resourceName = string.Format("SharpRDP.{0}.dll.bin",
                    new replacedemblyName(argtwo.Name).Name);
                var replacedembly = replacedembly.GetExecutingreplacedembly();
                using (var rs = replacedembly.GetManifestResourceStream(resourceName))
                using (var zs = new DeflateStream(rs, CompressionMode.Decompress))
                using (var ms = new MemoryStream())
                {
                    zs.CopyTo(ms);
                    return replacedembly.Load(ms.ToArray());
                }
            };

            var arguments = new Dictionary<string, string>();
            foreach (string argument in args)
            {
                int idx = argument.IndexOf('=');
                if (idx > 0)
                    arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1);
            }

            string username = string.Empty;
            string domain = string.Empty;
            string preplacedword = string.Empty;
            string command = string.Empty;
            string execElevated = string.Empty;
            string execw = "";
            bool connectdrive = false;
            bool takeover = false;
            bool nla = false;
            
            if (arguments.ContainsKey("username"))
            {
                if (!arguments.ContainsKey("preplacedword"))
                {
                    Console.WriteLine("[X] Error: A preplacedword is required");
                    return;
                }
                else
                {
                    if (arguments["username"].Contains("\\"))
                    {
                        string[] tmp = arguments["username"].Split('\\');
                        domain = tmp[0];
                        username = tmp[1];
                    }
                    else
                    {
                        domain = ".";
                        username = arguments["username"];
                    }
                    preplacedword = arguments["preplacedword"];
                }
            }

            if (arguments.ContainsKey("preplacedword") && !arguments.ContainsKey("username"))
            {
                Console.WriteLine("[X] Error: A username is required");
                return;
            }
            if ((arguments.ContainsKey("computername")) && (arguments.ContainsKey("command")))
            {
                Client rdpconn = new Client();
                command = arguments["command"];
                if (arguments.ContainsKey("exec"))
                {
                    if (arguments["exec"].ToLower() == "cmd")
                    {
                        execw = "cmd";
                    }
                    else if (arguments["exec"].ToLower() == "powershell" || arguments["exec"].ToLower() == "ps")
                    {
                        execw = "powershell";
                    }
                }
                if (arguments.ContainsKey("elevated"))
                {
                    if(arguments["elevated"].ToLower() == "true" || arguments["elevated"].ToLower() == "win+r" || arguments["elevated"].ToLower() == "winr")
                    {
                        execElevated = "winr";
                    }
                    else if(arguments["elevated"].ToLower() == "taskmgr" || arguments["elevated"].ToLower() == "taskmanager")
                    {
                        execElevated = "taskmgr";
                    }
                    else
                    {
                        execElevated = string.Empty;
                    }
                }
                if (arguments.ContainsKey("connectdrive"))
                {
                    if(arguments["connectdrive"].ToLower() == "true")
                    {
                        connectdrive = true;
                    }
                }
                if (arguments.ContainsKey("takeover"))
                {
                    if (arguments["takeover"].ToLower() == "true")
                    {
                        takeover = true;
                    }
                }
                if (arguments.ContainsKey("nla"))
                {
                    if (arguments["nla"].ToLower() == "true")
                    {
                        nla = true;
                    }
                }
                string[] computerNames = arguments["computername"].Split(',');
                foreach (string server in computerNames)
                {
                    rdpconn.CreateRdpConnection(server, username, domain, preplacedword, command, execw, execElevated, connectdrive, takeover, nla);
                }
            }
            else
            {
                HowTo();
                return;
            }

        }

19 View Source File : Client.cs
License : MIT License
Project Creator : 1ZouLTReX1

public Byte[] ReceiveOnce()
    {
        /*
         * returns one message in a byte array which then get processed by the client
         * one message may require serveral calls to '.Receive' function.
         */

        // Receive the response from the remote device.
        if (offset >= bytesRec)
        {
            if (SafeReceive(ref buffer, ref bytesRec, ref offset))
                return null;
        }

        len = Globals.DeSerializeLenPrefix(buffer, offset);
        offset += sizeof(int);

        while (len > 0)
        {
            cut = Math.Min(len, bytesRec - offset);
            ms.Write(buffer, offset, cut);
            len -= cut;
            offset += cut;

            if (len > 0)
            {
                // The left over of the previous message.
                if (SafeReceive(ref buffer, ref bytesRec, ref offset))
                    return null;
            }
        }

        // Process one message from the stream.
        data = ms.ToArray();
        // Clear the buffer.
        ms.SetLength(0);

        return data;
    }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public static byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] preplacedwordBytes)
        {
            byte[] decryptedBytes = null;
            byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

            using (MemoryStream ms = new MemoryStream())
            {
                using (RijndaelManaged AES = new RijndaelManaged())
                {
                    AES.KeySize = 256;
                    AES.BlockSize = 128;

                    var key = new Rfc2898DeriveBytes(preplacedwordBytes, saltBytes, 1000);
                    AES.Key = key.GetBytes(AES.KeySize / 8);
                    AES.IV = key.GetBytes(AES.BlockSize / 8);

                    AES.Mode = CipherMode.CBC;

                    using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
                        cs.Close();
                    }
                    decryptedBytes = ms.ToArray();
                }
            }

            return decryptedBytes;
        }

See More Examples