/// <summary>
            ///
            /// </summary>
            /// <param name="buffer"></param>
            /// <param name="cancellationToken"></param>
            /// <returns></returns>
            public override async ValueTask <int> WriteAsync(ReadOnlyMemory <byte> buffer, CancellationToken cancellationToken = default)
            {
                UpdateLastActive();
                if (_closed)
                {
                    return(-1);
                }
                int written = -1;

                try
                {
                    var arr = ArrayPool <byte> .Shared.Rent(buffer.Length);

                    buffer.CopyTo(arr.AsMemory());
                    written = await _sock.SendToAsync(new ArraySegment <byte>(arr), SocketFlags.None, _remote);//TODO waiting for a overload.

                    ArrayPool <byte> .Shared.Return(arr, true);
                }
                catch (SocketException ex)
                {
                    _logger?.LogError(ex, "UdpClient2 SendToAsync error.");
                    return(-1);
                }
                return(written);
            }
        public override ReadOnlyMemory <byte> Encrypt(ReadOnlyMemory <byte> data, KerberosKey key, KeyUsage usage)
        {
            var k1 = key.GetKey(this);

            var salt = GetSalt((int)usage);

            var k2 = HMACMD5(k1, salt);

            var confounder = GenerateRandomBytes(ConfounderSize);

            var plaintextBuffer = new byte[data.Length + confounder.Length];
            var plaintext       = new Memory <byte>(plaintextBuffer);

            confounder.CopyTo(plaintext);
            data.CopyTo(plaintext.Slice(confounder.Length));

            var checksum = HMACMD5(k2, plaintextBuffer);

            var k3 = HMACMD5(k2, checksum);

            var ciphertext = new Memory <byte>(new byte[plaintext.Length + checksum.Length]);

            RC4.Transform(k3, plaintext.Span, ciphertext.Span.Slice(checksum.Length));

            checksum.CopyTo(ciphertext.Span);

            return(ciphertext);
        }
Example #3
0
        public void CopyMemory()
        {
            var sourceMemory      = new ReadOnlyMemory <byte>(_data);
            var destinationMemory = _destination.AsMemory();

            sourceMemory.CopyTo(destinationMemory);
        }
        //private SymbolParser _symbolParser;

        /// <summary>
        /// Provides the functionality to map a DLL from memory into a process
        /// </summary>
        public void Assign(System.Diagnostics.Process process, ReadOnlyMemory <byte> dllBytes)
        {
            // Validate the arguments

            if (process is null || process.HasExited)
            {
                throw new ArgumentException("The process provided was invalid");
            }

            if (dllBytes.IsEmpty)
            {
                throw new ArgumentException("The DLL bytes provided were invalid");
            }

            EnterDebugMode();

            _dllBytes = new Memory <byte>(new byte[dllBytes.Length]);

            dllBytes.CopyTo(_dllBytes);

            _peImage = new PeImage(dllBytes);

            _processManager = new ProcessAccessor(process);

            //_symbolParser = new SymbolParser(RetrieveNtdllFilePath(process), "RtlInsertInvertedFunctionTable", "RtlRemoveInvertedFunctionTable");
        }
        private static int[] SuffixArrayByDoubling(ReadOnlyMemory <int> source)
        {
            var n  = source.Length;
            var sa = Enumerable.Range(0, n).ToArray();
            var s1 = new int[n];
            var s2 = new int[n];

            source.CopyTo(s1.AsMemory());

            for (var k = 1; k < n; k *= 2)
            {
                int Compare(int x, int y)
                {
                    if (s1[x] != s1[y])
                    {
                        return(s1[x].CompareTo(s1[y]));
                    }
                    var rx = x + k < n ? s1[x + k] : -1;
                    var ry = y + k < n ? s1[y + k] : -1;

                    return(rx.CompareTo(ry));
                }

                Array.Sort(sa, Compare);
                s2[sa[0]] = 0;
                for (var i = 1; i < n; i++)
                {
                    s2[sa[i]] = s2[sa[i - 1]] + (Compare(sa[i - 1], sa[i]) < 0 ? 1 : 0);
                }

                (s2, s1) = (s1, s2);
            }

            return(sa);
        }
        public override async Task <T> SendMessage <T>(string domain, ReadOnlyMemory <byte> req, CancellationToken cancellation = default)
        {
            var kdc = LocateKdc(domain);

            var messageBytes = new Memory <byte>(new byte[req.Length + 4]);

            Endian.ConvertToBigEndian(req.Length, messageBytes.Slice(0, 4));
            req.CopyTo(messageBytes.Slice(4, req.Length));

            var message = new KdcProxyMessage
            {
                TargetDomain  = domain,
                KerbMessage   = messageBytes,
                DcLocatorHint = Hint
            };

            var response = await Client.PostAsync(kdc, new BinaryContent(message.Encode()));

            response.EnsureSuccessStatusCode();

            var responseBody = await response.Content.ReadAsByteArrayAsync();

            var kdcResponse = KdcProxyMessage.Decode(responseBody);

            return(Decode <T>(kdcResponse.KerbMessage.Slice(4)));
        }
            public ValueTask WriteAsync(Socket socket, IReadOnlyList <ReadOnlyMemory <byte> > buffers, CancellationToken cancellationToken = default)
            {
                int bufferCount = buffers.Count;

                _gatheredSegments ??= new List <ArraySegment <byte> >(buffers.Count);

                for (int i = 0; i < bufferCount; ++i)
                {
                    ReadOnlyMemory <byte> buffer = buffers[i];

                    if (!MemoryMarshal.TryGetArray(buffer, out ArraySegment <byte> segment))
                    {
                        _pooledArrays ??= new List <byte[]>();

                        byte[] array = ArrayPool <byte> .Shared.Rent(buffer.Length);

                        _pooledArrays.Add(array);

                        buffer.CopyTo(array);

                        segment = new ArraySegment <byte>(array, 0, buffer.Length);
                    }

                    _gatheredSegments.Add(segment);
                }

                BufferList = _gatheredSegments;
                Reset();
                if (!socket.SendAsync(this))
                {
                    OnCompleted();
                }

                return(Task);
            }
        // don't work with CFLIST atm
        public static string CalculateKey(byte[] type, byte[] appnonce, byte[] netid, ReadOnlyMemory <byte> devnonce, byte[] appKey)
        {
            Aes aes = new AesManaged
            {
                Key     = appKey,
                Mode    = CipherMode.ECB,
                Padding = PaddingMode.None
            };
            var pt        = new byte[type.Length + appnonce.Length + netid.Length + devnonce.Length + 7];
            var destIndex = 0;

            Array.Copy(type, 0, pt, destIndex, type.Length);

            destIndex += type.Length;
            Array.Copy(appnonce, 0, pt, destIndex, appnonce.Length);

            destIndex += appnonce.Length;
            Array.Copy(netid, 0, pt, destIndex, netid.Length);

            destIndex += netid.Length;
            devnonce.CopyTo(new Memory <byte>(pt, destIndex, devnonce.Length));

            aes.IV = new byte[16];
            ICryptoTransform cipher;

            cipher = aes.CreateEncryptor();

            var key = cipher.TransformFinalBlock(pt, 0, pt.Length);

            return(ConversionHelper.ByteArrayToString(key));
        }
Example #9
0
        public override T Decode <T>(ReadOnlyMemory <byte> buffer, Flags flags, OpCode opcode)
        {
            if (typeof(T) == typeof(byte[]))
            {
                object value = DecodeBinary(buffer.Span);
                return((T)value);
            }

            if (typeof(T) == typeof(IMemoryOwner <byte>))
            {
                // Note: it is important for the consumer to dispose of the returned IMemoryOwner<byte>, in keeping
                // with IMemoryOwner<T> conventions. Failure to properly dispose this object will result in the memory
                // not being returned to the pool, which will increase GC impact across various parts of the framework.

                var memoryOwner = MemoryPool <byte> .Shared.RentAndSlice(buffer.Length);

                try
                {
                    buffer.CopyTo(memoryOwner.Memory);

                    // This boxes the SlicedMemoryOwner on the heap, making it act like a class to the consumer
                    return((T)(object)memoryOwner);
                }
                catch
                {
                    // Cleanup if the copy fails
                    memoryOwner.Dispose();
                    throw;
                }
            }

            throw new InvalidOperationException("The RawBinaryTranscoder can only decode byte arrays or IMemoryOwner<byte>.");
        }
        public static void Write(this Stream stream, ReadOnlyMemory <byte> buffer)
        {
            if (buffer.Length == 0)
            {
                return;
            }

            if (MemoryMarshal.TryGetArray(buffer, out var segment))
            {
                // ReSharper disable once AssignNullToNotNullAttribute
                stream.Write(segment.Array, segment.Offset, segment.Count);
            }
            else
            {
                var byteBuffer = ArrayPool <byte> .Shared.Rent(buffer.Length);

                try
                {
                    buffer.CopyTo(byteBuffer);
                    stream.Write(byteBuffer, 0, buffer.Length);
                }
                finally
                {
                    ArrayPool <byte> .Shared.Return(byteBuffer);
                }
            }
        }
Example #11
0
        private unsafe void GenerateKey(ReadOnlyMemory <byte> modulus, ReadOnlyMemory <byte> generator, ref IntPtr hPrivateKey)
        {
            var status = BCryptGenerateKeyPair(this.hAlgorithm, ref hPrivateKey, this.ModulusSize, 0);

            ThrowIfNotNtSuccess(status);

            var structSize = sizeof(BCRYPT_DH_PARAMETER_HEADER) + modulus.Length + generator.Length;

            using (var rented = CryptoPool.Rent <byte>(structSize))
            {
                rented.Memory.Span.Fill(0);

                fixed(byte *pParam = &MemoryMarshal.GetReference(rented.Memory.Span))
                {
                    BCRYPT_DH_PARAMETER *param = (BCRYPT_DH_PARAMETER *)pParam;

                    param->Header.CbLength    = structSize;
                    param->Header.CbKeyLength = modulus.Length;
                    param->Header.DwMagic     = BCRYPT_DH_PARAMETERS_MAGIC;

                    modulus.CopyTo(rented.Memory.Slice(sizeof(BCRYPT_DH_PARAMETER_HEADER)));
                    generator.CopyTo(rented.Memory.Slice(sizeof(BCRYPT_DH_PARAMETER_HEADER) + modulus.Length));

                    status = BCryptSetProperty(hPrivateKey, BCRYPT_DH_PARAMETERS, pParam, param->Header.CbLength, 0);
                    ThrowIfNotNtSuccess(status);
                }
            }

            status = BCryptFinalizeKeyPair(hPrivateKey, 0);
            ThrowIfNotNtSuccess(status);
        }
Example #12
0
        public static async Task NewPackageAsync(this TcpDataReader tcpDataReader, ReadOnlyMemory <byte> bytes)
        {
            var buf = await tcpDataReader.AllocateBufferToWriteAsync(CancellationToken.None);

            bytes.CopyTo(buf);
            tcpDataReader.CommitWrittenData(bytes.Length);
        }
Example #13
0
        private static void Write(PipeWriter writer, ReadOnlyMemory <byte> value)
        {
            var buffer = writer.GetMemory(value.Length);

            value.CopyTo(buffer);
            writer.Advance(value.Length);
        }
Example #14
0
        /// <summary>
        ///   Reads the next value as a Integer with a specified tag, returning the contents
        ///   as a <see cref="BigInteger"/> over the original data.
        /// </summary>
        /// <param name="expectedTag">The tag to check for before reading.</param>
        /// <returns>
        ///   The bytes of the Integer value, in signed big-endian form.
        /// </returns>
        /// <exception cref="CryptographicException">
        ///   the next value does not have the correct tag --OR--
        ///   the length encoding is not valid under the current encoding rules --OR--
        ///   the contents are not valid under the current encoding rules
        /// </exception>
        /// <exception cref="ArgumentException">
        ///   <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is
        ///   <see cref="TagClass.Universal"/>, but
        ///   <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not correct for
        ///   the method
        /// </exception>
        public BigInteger ReadInteger(Asn1Tag expectedTag)
        {
            ReadOnlyMemory <byte> contents =
                this.GetIntegerContents(expectedTag, UniversalTagNumber.Integer, out int headerLength);

            // TODO: Split this for netcoreapp/netstandard to use the Big-Endian BigInteger parsing
            byte[]     tmp = CryptoPool.Rent(contents.Length);
            BigInteger value;

            try
            {
                byte fill = (contents.Span[0] & 0x80) == 0 ? (byte)0 : (byte)0xFF;

                // Fill the unused portions of tmp with positive or negative padding.
                new Span <byte>(tmp, contents.Length, tmp.Length - contents.Length).Fill(fill);
                contents.CopyTo(tmp);

                // Convert to Little-Endian.
                AsnWriter.Reverse(new Span <byte>(tmp, 0, contents.Length));
                value = new BigInteger(tmp);
            }
            finally
            {
                // Let CryptoPool.Return clear the whole tmp so that not even the sign bit
                // is returned to the array pool.
                CryptoPool.Return(tmp);
            }

            this._data = this._data.Slice(headerLength + contents.Length);
            return(value);
        }
Example #15
0
        /// <summary>
        ///     Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.
        /// </summary>
        /// <param name="buffer">The buffer to write data from.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="P:System.Threading.CancellationToken.None" />.</param>
        /// <returns>A task that represents the asynchronous write operation.</returns>
        public Task WriteAsync2(ReadOnlyMemory <byte> buffer, CancellationToken cancellationToken)
        {
            var buf = ArrayPool <byte> .Shared.Rent(buffer.Length);

            buffer.CopyTo(buf);
            return(stream.WriteAsync(buf, 0, buf.Length, cancellationToken));
        }
Example #16
0
            protected private override void ImplWriteBytes(ref State state, ReadOnlyMemory <byte> bytes)
            {
                var length = bytes.Length;

                if (flushLock != 0 || length <= ioBuffer.Length) // write to the buffer
                {
                    DemandSpace(length, this, ref state);
                    bytes.CopyTo(new Memory <byte>(ioBuffer, ioIndex, length));
                    ioIndex += length;
                }
                else
                {
                    // writing data that is bigger than the buffer (and the buffer
                    // isn't currently locked due to a sub-object needing the size backfilled)
                    state.Flush(); // commit any existing data from the buffer
                                   // now just write directly to the underlying stream

                    // prefer using the array API, even on .NET Core (for now),
                    // because many implementations won't have overridden the method yet
                    if (MemoryMarshal.TryGetArray(bytes, out var segment))
                    {
                        dest.Write(segment.Array, segment.Offset, segment.Count);
                    }
                    else
                    {
#if PLAT_SPAN_OVERLOADS
                        dest.Write(bytes.Span);
#else
                        WriteFallback(bytes.Span, dest);
#endif
                    }
                    // since we've flushed offset etc is 0, and remains
                    // zero since we're writing directly to the stream
                }
            }
Example #17
0
        public static ReadOnlyMemory <byte> Decrypt(
            ReadOnlyMemory <byte> ciphertext,
            ReadOnlyMemory <byte> key,
            ReadOnlyMemory <byte> iv
            )
        {
            if (!CalculateLength(ciphertext.Length, out int padSize, out int maxLength))
            {
                return(ciphertext);
            }

            using (var rental = CryptoPool.Rent <byte>(maxLength))
            {
                var aes = CryptoPal.Platform.Aes();

                Memory <byte> ciphertextRented;

                if (padSize == BlockSize)
                {
                    ciphertextRented = rental.Memory.Slice(0, ciphertext.Length);

                    ciphertext.CopyTo(ciphertextRented);
                }
                else
                {
                    var depadded = Depad(ciphertext, padSize);

                    var decryptedPad = aes.Decrypt(depadded, key, iv);

                    ciphertextRented = rental.Memory.Slice(0, maxLength);

                    ciphertext.CopyTo(ciphertextRented);

                    decryptedPad.Slice(decryptedPad.Length - padSize)
                    .CopyTo(
                        ciphertextRented.Slice(ciphertext.Length)
                        );
                }

                if (ciphertext.Length >= TwoBlockSizes)
                {
                    SwapLastTwoBlocks(ciphertextRented.Span);
                }

                return(aes.Decrypt(ciphertextRented, key, iv).Slice(0, ciphertext.Length));
            }
        }
        private static ReadOnlyMemory <byte> Pad(ReadOnlyMemory <byte> data, int length)
        {
            var copy = new Memory <byte>(new byte[length]);

            data.CopyTo(copy.Slice(length - data.Length));

            return(copy);
        }
Example #19
0
 internal SpriteData(string path, ReadOnlyMemory <byte> data, SKBitmap image)
 {
     Path      = path;
     Reference = GC.AllocateUninitializedArray <byte>((int)data.Length);
     data.CopyTo(Reference);
     Data  = new(Reference);
     Image = image;
 }
        internal ReadOnlyMemory <TableFieldInfo> GetAllFields()
        {
            var res = new TableFieldInfo[PrimaryKeyFields.Length + Fields.Length];

            PrimaryKeyFields.CopyTo(res);
            Fields.CopyTo(res.AsMemory(PrimaryKeyFields.Length));
            return(res);
        }
Example #21
0
        public override int Read(byte[] buffer, int offset, int count)
        {
            ReadOnlyMemory <byte> bytes = Read(count, false);

            bytes.CopyTo(new Memory <byte>(buffer).Slice(offset, count));

            return(bytes.Length);
        }
Example #22
0
        public static void WriteToROM(int Addr, ReadOnlyMemory <byte> val)
        {
            int f      = RomUtils.GetFileIndexForWriting(Addr);
            int dest   = Addr - RomData.MMFileList[f].Addr;
            var memory = new Memory <byte>(RomData.MMFileList[f].Data);

            val.CopyTo(memory.Slice(dest));
        }
        /// <summary>
        /// Expand the Received Body Bytes
        /// </summary>
        /// <param name="bytes">The Received Bytes</param>
        protected virtual void ExpandBody(ReadOnlyMemory <byte> bytes)
        {
            byte[] bodyBytes = new byte[bytes.Length];

            bytes.CopyTo(bodyBytes);

            _body = bodyBytes;
        }
Example #24
0
            public ReusableTask WriteAsync(ITorrentFileInfo file, long offset, ReadOnlyMemory <byte> buffer)
            {
                var result = new byte[buffer.Length];

                buffer.CopyTo(result.AsMemory());
                WrittenData.Add(Tuple.Create(file, offset, result));
                return(ReusableTask.CompletedTask);
            }
Example #25
0
            public MemoryOwner(ReadOnlyMemory <byte> memory)
            {
                // The memory is read-only, and the memory owner expects a mutable area
                // of memory. In this case we will create a copy of the data.
                // TODO: Can we redesign this to where this isn't necessary?
                UnderlyingMemory = MemoryPool <byte> .Shared.Rent(memory.Length);

                memory.CopyTo(UnderlyingMemory.Memory);
            }
Example #26
0
 public static async ValueTask WriteAsync(this Stream stream, ReadOnlyMemory <byte> buffer, CancellationToken cancellationToken = default)
 {
     using (var rentedBuffer = new RentedBuffer <byte>(buffer.Length))
     {
         buffer.CopyTo(rentedBuffer.Memory);
         var segment = rentedBuffer.Segment;
         await stream.WriteAsync(segment.Array, segment.Offset, segment.Count, cancellationToken);
     }
 }
Example #27
0
        /// <summary>
        /// KRB-FX-CF1: Concatenate two strings into a single string.
        /// KRB-FX-CF1(UTF-8 string, UTF-8 string) -> (UTF-8 string)
        /// KRB-FX-CF1(x, y) := x || y
        /// </summary>
        /// <param name="x">The first string</param>
        /// <param name="y">The second string</param>
        /// <returns>Returns the two strings concatenated</returns>
        public static ReadOnlyMemory <byte> Cf1(ReadOnlyMemory <byte> x, ReadOnlyMemory <byte> y)
        {
            Memory <byte> result = new byte[x.Length + y.Length];

            x.CopyTo(result);
            y.CopyTo(result.Slice(x.Length));

            return(result);
        }
Example #28
0
        public static ReadOnlyMemory <byte> FormatKerberosMessageStream(ReadOnlyMemory <byte> message)
        {
            var kerbMessage = new Memory <byte>(new byte[message.Length + 4]);

            BinaryPrimitives.WriteInt32BigEndian(kerbMessage.Span.Slice(0, 4), message.Length);

            message.CopyTo(kerbMessage.Slice(4));

            return(kerbMessage);
        }
Example #29
0
        public Chip8Platform(ReadOnlyMemory <byte> romImage)
        {
            this.ram = new Memory <byte>(new byte[0x1000]);
            this.font.CopyTo(this.ram);
            romImage.CopyTo(this.ram.Slice(0x200));

            this.cpu = new Chip8Cpu(this);
            this.apu = new Chip8Apu(this);
            this.ppu = new Chip8Ppu(this);
        }
Example #30
0
        private static byte[] Reverse(ReadOnlyMemory <byte> data)
        {
            var copy = new byte[data.Length];

            data.CopyTo(copy);

            Array.Reverse(copy);

            return(copy);
        }