WriteByte() public method

public WriteByte ( byte value ) : void
value byte
return void
コード例 #1
0
        public static void unescapeNAL(System.IO.MemoryStream _buf)
        {
            if (_buf.Position - _buf.Length < 2)
            {
                return;
            }
            System.IO.MemoryStream inb  = new System.IO.MemoryStream(_buf.ToArray());
            System.IO.MemoryStream outb = new System.IO.MemoryStream(_buf.ToArray());
            byte p1 = (byte)inb.ReadByte();

            outb.WriteByte(p1);
            byte p2 = (byte)inb.ReadByte();

            outb.WriteByte(p2);
            while (inb.Position < inb.Length)
            {
                byte b = (byte)inb.ReadByte();
                if (p1 != 0 || p2 != 0 || b != 3)
                {
                    outb.WriteByte(b);
                }
                p1 = p2;
                p2 = b;
            }
            _buf.SetLength(outb.Position);
        }
コード例 #2
0
ファイル: ArrayHandling.cs プロジェクト: Tradioyes/Npgsql
        /// <summary>
        /// Serialise the enumeration or array.
        /// </summary>
        public byte[] ArrayToArrayText(NpgsqlNativeTypeInfo TypeInfo, object NativeData, Boolean forExtendedQuery, NativeToBackendTypeConverterOptions options, bool arrayElement)
        {
            MemoryStream array = new MemoryStream();

            if (! forExtendedQuery)
            {
                if (! options.UseConformantStrings && options.Supports_E_StringPrefix)
                {
                    array.WriteByte((byte)ASCIIBytes.E);
                }

                array.WriteByte((byte)ASCIIBytes.SingleQuote);
            }

            if (! WriteItemText(TypeInfo, NativeData, array, forExtendedQuery, options))
            {
                array.Write(ASCIIArrayByteArrays.EmptyArray, 0, ASCIIArrayByteArrays.EmptyArray.Length);
            }

            if (! forExtendedQuery)
            {
                array.WriteByte((byte)ASCIIBytes.SingleQuote);
            }

            return array.ToArray();
        }
コード例 #3
0
ファイル: LCLoginOK.cs プロジェクト: RudyJ/ODK-DarkEmu
        public override void Write(ref NetworkStream netstream)
        {
            using (Stream stream = new MemoryStream())
            {
                // write id
                stream.Write(BitConverter.GetBytes((ushort)this.ID), 0, 2);

                // write body size
                stream.Write(BitConverter.GetBytes(0), 0, 4);

                // write isAdult
                stream.WriteByte(BitConverter.GetBytes(this.isAdult)[0]);

                // write UnderFifteen
                stream.WriteByte(BitConverter.GetBytes(this.UnderFifteen)[0]);

                // write Family
                stream.WriteByte(BitConverter.GetBytes(this.Family)[0]);

                // write Status
                stream.WriteByte(this.Status);

                // write LastDay
                stream.Write(BitConverter.GetBytes(this.LastDay), 0, 2);

                // write PayType
                stream.WriteByte(this.PayType);

                // copy stream to netstream
                stream.Position = 0;
                stream.CopyTo(netstream);
            }
        }
コード例 #4
0
 // RFC:  http://www.w3.org/TR/html5/forms.html#application/x-www-form-urlencoded-encoding-algorithm
 private void UrlEncodeAndWrite(string value, MemoryStream memoryStream)
 {
     foreach (char symbol in value)
     {
         if (unreservedChars.IndexOf(symbol) != -1)
         {
             memoryStream.WriteByte((byte)symbol);
         }
         else if (symbol == ' ')
         {
             memoryStream.WriteByte(plus);
         }
         else if (symbol < 255)
         {
             var encodedValue = Encoding.ASCII.GetBytes(String.Format("%{0:X2}", (byte)symbol));
             memoryStream.Write(encodedValue, 0, encodedValue.Length);
         }
         else
         {
             var bytes = Encoding.UTF8.GetBytes(new[] { symbol });
             foreach (var @byte in bytes)
             {
                 var encodedValue = Encoding.ASCII.GetBytes(String.Format("%{0:X2}", @byte));
                 memoryStream.Write(encodedValue, 0, encodedValue.Length);
             }
         }
     }
 }
コード例 #5
0
        public void initiateImageTransfer(DlmsClient dlms, PhyLayer phy, ImageInformation imageInfo)
        {
            try
            {
                System.IO.MemoryStream stream = new System.IO.MemoryStream();
                stream.WriteByte(DlmsType.STRUCTURE.tag);
                stream.WriteByte(2); // size
                stream.WriteByte(DlmsType.OCTET_STRING.tag);
                stream.WriteByte((byte)(imageInfo.getIdentifier().Length));


                //stream.WriteByte(imageInfo.getIdentifier());
                byte[] aux = imageInfo.getIdentifier();
                //Array.Reverse(aux);
                stream.Write(aux, 0, aux.Length);

                stream.WriteByte(DlmsType.UINT32.tag);
                //stream.WriteByte(ByteBuffer.allocate(4).putInt(imageInfo.getImage().Length).array());
                stream.Write(new byte[] { (byte)(imageInfo.getImage().Length >> 24), (byte)(imageInfo.getImage().Length >> 16), (byte)(imageInfo.getImage().Length >> 8), (byte)(imageInfo.getImage().Length) }, 0, imageInfo.getImage().Length);
                dlms.action(phy, createDesc(mtdTransferInitiate, stream.ToArray()));
            }
            catch (IOException)
            {
                throw new ImageTransferException(ImageTransferExceptionReason.INTERNAL_ERROR);
            }
        }
コード例 #6
0
ファイル: BitTest.cs プロジェクト: liwq-net/SwfLib
        public void ReadBitTest()
        {
            var mem = new MemoryStream();
            mem.WriteByte(0xaa);
            mem.WriteByte(0x73);
            mem.Seek(0, SeekOrigin.Begin);
            var reader = new SwfStreamReader(mem);

            Assert.AreEqual(true, reader.ReadBit(), "Bit 0");
            Assert.AreEqual(false, reader.ReadBit(), "Bit 1");
            Assert.AreEqual(true, reader.ReadBit(), "Bit 2");
            Assert.AreEqual(false, reader.ReadBit(), "Bit 3");
            Assert.AreEqual(true, reader.ReadBit(), "Bit 4");
            Assert.AreEqual(false, reader.ReadBit(), "Bit 5");
            Assert.AreEqual(true, reader.ReadBit(), "Bit 6");
            Assert.AreEqual(false, reader.ReadBit(), "Bit 7");

            Assert.AreEqual(false, reader.ReadBit(), "Bit 8");
            Assert.AreEqual(true, reader.ReadBit(), "Bit 9");
            Assert.AreEqual(true, reader.ReadBit(), "Bit 10");
            Assert.AreEqual(true, reader.ReadBit(), "Bit 11");
            Assert.AreEqual(false, reader.ReadBit(), "Bit 12");
            Assert.AreEqual(false, reader.ReadBit(), "Bit 13");
            Assert.AreEqual(true, reader.ReadBit(), "Bit 14");
            Assert.AreEqual(true, reader.ReadBit(), "Bit 15");

            Assert.AreEqual(mem.Length, mem.Position, "Should reach end of the stream");
        }
コード例 #7
0
ファイル: StreamEscaper.cs プロジェクト: foobert/Colorduino
        public byte[] Escape(byte msgId, byte[] data)
        {
            ushort sum1 = 0;
            ushort sum2 = 0;

            MemoryStream mem = new MemoryStream();

            // write start byte
            mem.WriteByte(0x7F);
            AppendByte(mem, msgId, ref sum1, ref sum2);

            for (int i = 0; i < data.Length; i++)
            {
                AppendByte(mem, data[i], ref sum1, ref sum2);
            }

            // write checksum bytes
            mem.WriteByte((byte)(sum2 & 0xFF));
            mem.WriteByte((byte)(sum1 & 0xFF));

            // write end byte
            mem.WriteByte(0x7E);

            return mem.ToArray();
        }
コード例 #8
0
ファイル: ZLibHelper.cs プロジェクト: Translator5/TuxLoL
        public static byte[] Compress(byte[] data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            using (var output = new MemoryStream())
            {
                // ZLib Header 0x78 0x9C
                output.WriteByte(0x78);
                output.WriteByte(0x9C);
                using (var input = new MemoryStream(data))
                {
                    using (var compressionStream = new DeflateStream(output, CompressionMode.Compress, true))
                    {
                        input.CopyTo(compressionStream);
                        compressionStream.Close();

                        // Adler32 hash of the uncompressed data
                        var adler32 = new Adler32();
                        adler32.Update(data);
                        byte[] hash = BitConverter.GetBytes((int) adler32.Value);
                        Array.Reverse(hash);
                        output.Write(hash, 0, hash.Length);
                        return output.ToArray();
                    }
                }
            }
        }
コード例 #9
0
 public byte[] snrmRequest()
 {
     System.IO.MemoryStream dataout = new System.IO.MemoryStream();
     System.IO.MemoryStream data    = new System.IO.MemoryStream();
     if (parameters.maxInformationFieldLengthTx < 128)
     {
         data.WriteByte(0x05);
         data.WriteByte(1);
         data.WriteByte((byte)parameters.maxInformationFieldLengthTx);
     }
     else if (parameters.maxInformationFieldLengthTx > 128)
     {
         data.WriteByte(0x05);
         data.WriteByte(2);
         data.WriteByte((byte)(parameters.maxInformationFieldLengthTx >> 8));
         data.WriteByte((byte)parameters.maxInformationFieldLengthTx);
     }
     if (parameters.maxInformationFieldLengthRx < 128)
     {
         data.WriteByte(0x06);
         data.WriteByte(1);
         data.WriteByte((byte)parameters.maxInformationFieldLengthRx);
     }
     else if (parameters.maxInformationFieldLengthRx > 128)
     {
         data.WriteByte(0x06);
         data.WriteByte(2);
         data.WriteByte((byte)(parameters.maxInformationFieldLengthRx >> 8));
         data.WriteByte((byte)parameters.maxInformationFieldLengthRx);
     }
     if (parameters.windowSizeTx != 1)
     {
         data.WriteByte(0x07);
         data.WriteByte(4);
         data.WriteByte((byte)(parameters.windowSizeTx >> 24));
         data.WriteByte((byte)(parameters.windowSizeTx >> 16));
         data.WriteByte((byte)(parameters.windowSizeTx >> 8));
         data.WriteByte((byte)parameters.windowSizeTx);
     }
     if (parameters.windowSizeRx != 1)
     {
         data.WriteByte(0x08);
         data.WriteByte(4);
         data.WriteByte((byte)(parameters.windowSizeRx >> 24));
         data.WriteByte((byte)(parameters.windowSizeRx >> 16));
         data.WriteByte((byte)(parameters.windowSizeRx >> 8));
         data.WriteByte((byte)parameters.windowSizeRx);
     }
     if (data.Length > 0)
     {
         dataout.WriteByte(0x80);
         dataout.WriteByte(0x81);
         dataout.WriteByte((byte)data.Length);
         dataout.Write(data.ToArray(), 0, (int)data.Length);
     }
     byte[] dataBytes = dataout.ToArray();
     initFrame(SNRM_CONTROL, dataBytes.Length);
     updateFrame(dataBytes);
     return(getFrame());
 }
コード例 #10
0
ファイル: GB2312.cs プロジェクト: h87kg/wordmake
 /// <summary>
 /// 获取指定区的GB2312代码
 /// </summary>
 /// <param name="stream">指定区的GB2312代码将写入(已UTF8编码)</param>
 /// <param name="st">开始区号</param>
 /// <param name="end">结束区号</param>
 /// <exception cref="ArgumentOutOfRangeException"></exception>
 /// <exception cref="ArgumentNullException"></exception>
 public static void GetChars(Stream stream, int st, int end)
 {
     if (stream == null)
     {
         throw new ArgumentNullException("stream");
     }
     if (st <= 0 || st > 94)
     {
         throw new ArgumentOutOfRangeException("st","开始区号应大于或等于0或小于94");
     }
     if (end >95||end<=st)
     {
         throw new ArgumentOutOfRangeException("end","结束区号应大于开始区号并小于96");
     }
     MemoryStream ms = new MemoryStream((end-st)*94*2);
     for (byte q = (byte)(0xa0 + st); q < 0xa0 + end; q++)
     {
         for (byte w = 0xa0 + 1; w <= 94 + 0xa0; w++)
         {
             ms.WriteByte(q);
             ms.WriteByte(w);
         }
     }
     GBtoUTF8(stream, ms);
     ms.Dispose();
 }
コード例 #11
0
 public byte[] GetBytes(ID3v2TagVersion tagVersion)
 {
     if ((this.m_PictureData == null) || (this.m_PictureData.Length == 0))
     {
         return new byte[0];
     }
     this.TextEncoding = EncodingType.ISO88591;
     using (MemoryStream stream1 = new MemoryStream())
     {
         stream1.WriteByte((byte) this.m_TextEncoding);
         if (tagVersion == ID3v2TagVersion.ID3v22)
         {
             string text1 = this.PictureExtension;
             if (string.IsNullOrEmpty(text1) || (text1.Length < 3))
             {
                 text1 = "   ";
             }
             else if (text1.Length > 3)
             {
                 text1 = text1.Substring(0, 3);
             }
             Utils.Write(stream1, Encoding.ASCII.GetBytes(text1));
         }
         else
         {
             this.SetMimeType();
             Utils.Write(stream1, Utils.ISO88591GetBytes(this.m_MimeType));
             stream1.WriteByte(0);
         }
         stream1.WriteByte((byte) this.m_PictureType);
         Utils.Write(stream1, Utils.GetStringBytes(tagVersion, this.m_TextEncoding, this.m_Description, true));
         Utils.Write(stream1, this.m_PictureData);
         return this.m_FrameHeader.GetBytes(stream1, tagVersion, this.GetFrameID(tagVersion));
     }
 }
コード例 #12
0
ファイル: ListItemNode.cs プロジェクト: stan60250/BTwizard
        public byte[] ToBytes()
        {
            MemoryStream memoryStream = new MemoryStream();
            byte[] buffer;
            if (Child.Count > 0)
            {
                if (ValueType == 'l')
                {
                    memoryStream.WriteByte((byte)'l');
                }
                else if (ValueType == 'd')
                {
                    memoryStream.WriteByte((byte)'d');
                }

                Child.ForEach(node =>
                {
                    buffer = node.ToBytes();
                    memoryStream.Write(buffer, 0, buffer.Length);
                });
                memoryStream.WriteByte((byte)'e');
            }
            else
            {
                buffer = Encoding.UTF8.GetBytes(String.Format("{0}:", _value.Length));
                memoryStream.Write(buffer, 0, buffer.Length);
                memoryStream.Write(_value, 0, _value.Length);
            }

            return memoryStream.ToArray();
        }
コード例 #13
0
        public void Write(WebSocketOpCode opCode, byte[] payload, bool isLastFrame)
        {
            // best to write everything to a memory stream before we push it onto the wire
            // not really necessary but I like it this way
            using (MemoryStream memoryStream = new MemoryStream())
            {
                byte finBitSetAsByte = isLastFrame ? (byte)0x80 : (byte)0x00;
                byte byte1 = (byte)(finBitSetAsByte | (byte)opCode);
                memoryStream.WriteByte(byte1);

                // NB, dont set the mask flag. No need to mask data from server to client
                // depending on the size of the length we want to write it as a byte, ushort or ulong
                if (payload.Length < 126)
                {
                    byte byte2 = (byte)payload.Length;
                    memoryStream.WriteByte(byte2);
                }
                else if (payload.Length <= ushort.MaxValue)
                {
                    byte byte2 = 126;
                    memoryStream.WriteByte(byte2);
                    BinaryReaderWriter.WriteUShort((ushort)payload.Length, memoryStream, false);
                }
                else
                {
                    byte byte2 = 127;
                    memoryStream.WriteByte(byte2);
                    BinaryReaderWriter.WriteULong((ulong)payload.Length, memoryStream, false);
                }

                memoryStream.Write(payload, 0, payload.Length);
                byte[] buffer = memoryStream.ToArray();
                _stream.Write(buffer, 0, buffer.Length);
            }            
        }
コード例 #14
0
ファイル: Close.cs プロジェクト: aura1213/netmf-interpreter
        public MFTestResults VerifyClose()
        {
            MFTestResults result = MFTestResults.Pass;
            try
            {
                MemoryStream ms = new MemoryStream();
                ms.WriteByte(0);
                Log.Comment("Close stream");
                ms.Close();

                try
                {
                    Log.Comment("Verify actually closed by writing to it");
                    ms.WriteByte(0);
                    result = MFTestResults.Fail;
                    Log.Exception("Expected ObjectDisposedException");
                }
                catch (ObjectDisposedException) { /* pass case */ }
            }
            catch (Exception ex)
            {
                result = MFTestResults.Fail;
                Log.Exception("Unexpected exception", ex);
            }

            return result;
        }
コード例 #15
0
 /// <summary>
 /// Generates the APDU for a GET request </summary>
 /// <param name="att"> LnDescriptor describing the object to be accessed </param>
 /// <returns> byte array representation of the APDU </returns>
 /// <exception cref="DlmsException"> </exception>
 public byte[] requestGet(LnDescriptor att)
 {
     try
     {
         System.IO.MemoryStream stream = new System.IO.MemoryStream();
         stream.WriteByte(Constants.xDlmsApdu.NoCiphering.GET_REQUEST);
         stream.WriteByte((byte)(connection.datablock.blockNum == 0 ? 1 : 2));
         stream.WriteByte((byte)(parameters.priority | parameters.serviceClass | Constants.INVOKE_ID));
         if (connection.datablock.blockNum != 0)
         {
             //stream.WriteByte(ByteBuffer.allocate(4).putInt(connection.datablock.blockNum).array());
             stream.Write(new byte[] { (byte)(connection.datablock.blockNum >> 24), (byte)(connection.datablock.blockNum >> 16), (byte)(connection.datablock.blockNum >> 8), (byte)(connection.datablock.blockNum) }, 0, 4);
         }
         else
         {
             //Array.Reverse(att.getClassId());
             stream.Write(att.getClassId(), 0, att.getClassId().Length);
             //Array.Reverse(att.getObis());
             stream.Write(att.getObis(), 0, att.getObis().Length);
             stream.WriteByte((byte)(att.getIndex()));
             stream.WriteByte((byte)(att.getRequestData().Length == 0 ? 0 : 1));
             //Array.Reverse(att.getRequestData());
             stream.Write(att.getRequestData(), 0, att.getRequestData().Length);
         }
         return(packFrame(Constants.xDlmsApdu.GlobalCiphering.GET_REQUEST, stream.ToArray()));
     }
     catch (IOException)
     {
         throw new DlmsException(DlmsException.DlmsExceptionReason.INTERNAL_ERROR);
     }
 }
コード例 #16
0
ファイル: Hybi13Handler.cs プロジェクト: ReactiveMarkets/Styx
        private static byte[] FrameData(byte[] payload, FrameType frameType)
        {
            using (var memoryStream = new MemoryStream())
            {
                var op = (byte) ((byte) frameType + 128);

                memoryStream.WriteByte(op);

                if (payload.Length > UInt16.MaxValue)
                {
                    memoryStream.WriteByte(127);
                    var lengthBytes = payload.Length.ToBigEndianBytes<ulong>();
                    memoryStream.Write(lengthBytes, 0, lengthBytes.Length);
                }
                else if (payload.Length > 125)
                {
                    memoryStream.WriteByte(126);
                    var lengthBytes = payload.Length.ToBigEndianBytes<ushort>();
                    memoryStream.Write(lengthBytes, 0, lengthBytes.Length);
                }
                else
                {
                    memoryStream.WriteByte((byte) payload.Length);
                }

                memoryStream.Write(payload, 0, payload.Length);

                return memoryStream.ToArray();
            }
        }
コード例 #17
0
ファイル: MLLP.cs プロジェクト: fo-dicom/mdcm
 public string Receive()
 {
     int ib = 0x00;
     MemoryStream ms = new MemoryStream();
     for (; _stream.ReadByte() != 0x0B; ) ;
     while (true) {
         if (ib == 0x1C) {
             ib = _stream.ReadByte();
             if (ib == 0x0D)
                 break;
             ms.WriteByte(0x1C);
             ms.WriteByte((byte)ib);
         }
         else {
             ib = _stream.ReadByte();
             if (ib != 0x1C)
                 ms.WriteByte((byte)ib);
         }
     }
     if (_version3) {
         _stream.Write(ACK, 0, ACK.Length);
         _stream.Flush();
     }
     #if SILVERLIGHT
     return Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length);
     #else
     return Encoding.ASCII.GetString(ms.ToArray());
     #endif
 }
コード例 #18
0
ファイル: Program.cs プロジェクト: GGammu/InsideCSharp
        static void Main(string[] args)
        {
            MemoryStream m = new MemoryStream(64);
            Console.WriteLine("Lenth: {0}\tPosition: {1}\tCapacity: {2}",
                m.Length, m.Position, m.Capacity);

            for (int i = 0; i < 64; i++)
            {
                m.WriteByte((byte)i);
            }

            string s = "Foo";
            for (int i = 0; i < 3; i++)
            {
                m.WriteByte((byte)s[i]);
            }

            Console.WriteLine("Length: {0}\tPosition: {1}\tCapacity: {2}",
                m.Length, m.Position, m.Capacity);

            Console.WriteLine("\nContents:");
            byte[] ba = m.GetBuffer();

            foreach (byte b in ba)
            {
                Console.Write("{0,-3}", b);
            }

            FileStream fs = new FileStream("Goo.txt", FileMode.Create, FileAccess.Write);
            m.WriteTo(fs);
            fs.Close();
            m.Close();

            Console.ReadLine();
        }
コード例 #19
0
ファイル: PKLibDecompress.cs プロジェクト: fanthos/Game-Heal
 public byte[] Explode(int ExpectedSize)
 {
     int num;
     byte[] buffer = new byte[ExpectedSize];
     Stream stream = new MemoryStream(buffer);
     while ((num = this.DecodeLit()) != -1)
     {
         if (num < 0x100)
         {
             stream.WriteByte((byte) num);
         }
         else
         {
             int length = num - 0xfe;
             int num3 = this.DecodeDist(length);
             if (num3 == 0)
             {
                 goto Label_0067;
             }
             int num4 = ((int) stream.Position) - num3;
             while (length-- > 0)
             {
                 stream.WriteByte(buffer[num4++]);
             }
         }
     }
     Label_0067:
     if (stream.Position == ExpectedSize)
     {
         return buffer;
     }
     byte[] destinationArray = new byte[stream.Position];
     Array.Copy(buffer, 0, destinationArray, 0, destinationArray.Length);
     return destinationArray;
 }
コード例 #20
0
ファイル: PEReaderTests.cs プロジェクト: ChuangYang/corefx
        public void SubStream()
        {
            var stream = new MemoryStream();
            stream.WriteByte(0xff);
            stream.Write(Misc.Members, 0, Misc.Members.Length);
            stream.WriteByte(0xff);
            stream.WriteByte(0xff);

            stream.Position = 1;
            var peReader1 = new PEReader(stream, PEStreamOptions.LeaveOpen, Misc.Members.Length);

            Assert.Equal(Misc.Members.Length, peReader1.GetEntireImage().Length);
            peReader1.GetMetadataReader();

            stream.Position = 1;
            var peReader2 = new PEReader(stream, PEStreamOptions.LeaveOpen | PEStreamOptions.PrefetchMetadata, Misc.Members.Length);

            Assert.Equal(Misc.Members.Length, peReader2.GetEntireImage().Length);
            peReader2.GetMetadataReader();
            stream.Position = 1;

            var peReader3 = new PEReader(stream, PEStreamOptions.LeaveOpen | PEStreamOptions.PrefetchEntireImage, Misc.Members.Length);

            Assert.Equal(Misc.Members.Length, peReader3.GetEntireImage().Length);
            peReader3.GetMetadataReader();
        }
コード例 #21
0
ファイル: MyMail.cs プロジェクト: wangsc1985/FA
            /// <summary>
            /// QuotedPrintable编码接码
            /// </summary>
            /// <param name="p_Text">原始文字</param>
            /// <param name="p_Encoding">编码方式</param>
            /// <returns>接码后信息</returns>
            public string DecodeQuotedPrintable(string p_Text, System.Text.Encoding p_Encoding)
            {
                System.IO.MemoryStream _Stream = new System.IO.MemoryStream();
                char[] _CharValue = p_Text.ToCharArray();
                for (int i = 0; i != _CharValue.Length; i++)
                {
                    switch (_CharValue[i])
                    {
                    case '=':
                        if (_CharValue[i + 1] == '\r' || _CharValue[i + 1] == '\n')
                        {
                            i += 2;
                        }
                        else
                        {
                            try
                            {
                                _Stream.WriteByte(Convert.ToByte(_CharValue[i + 1].ToString() + _CharValue[i + 2].ToString(), 16));
                                i += 2;
                            }
                            catch
                            {
                                _Stream.WriteByte(Convert.ToByte(_CharValue[i]));
                            }
                        }
                        break;

                    default:
                        _Stream.WriteByte(Convert.ToByte(_CharValue[i]));
                        break;
                    }
                }
                return(p_Encoding.GetString(_Stream.ToArray()));
            }
コード例 #22
0
        /// <summary>
        /// Converts image to UPD packet payload
        /// 
        /// <---      8      ---> <---      8      --->
        /// ┌────────────────────┬────────────────────┐
        /// │Message type        │Comp.-len in byte   │
        /// ├────────────────────┴────────────────────┤
        /// │          Number of vectors              │
        /// ├─────────────────────────────────────────┤
        /// │                                         │
        /// ...               Vectors!              ...
        /// │                                         │
        /// └─────────────────────────────────────────┘
        /// 
        /// </summary>
        /// <returns></returns>
        public byte[] ToPacket()
        {
            using (MemoryStream ms = new MemoryStream())
            {
                // Write package type
                ms.WriteByte((byte)PacketType.Image);

                // Write component length
                ms.WriteByte(COMPONENT_LENGTH);

                // Write number of vectors
                //ms.WriteByte((byte)_vectors.GetLength(0));
                ms.Write(BitConverter.GetBytes(_vectors.GetLength(0)), 0, 2);

                // Write vectors
                for (int i = 0; i < _vectors.GetLength(0); i++)
                {
                    ms.WriteByte(_vectors[i, 0]);
                    ms.WriteByte(_vectors[i, 1]);
                    ms.WriteByte(_vectors[i, 2]);
                }

                return ms.ToArray();
            }
        }
コード例 #23
0
ファイル: fitFileWriter.cs プロジェクト: Anderman/fitRepair
 public fitFileWrite(StreamReader file, FileStream fitFile)
 {
     MemoryStream memStream = new MemoryStream();
     fitstream = new FitFieldStream(memStream);
     memStream.Seek(HEADERSIZE, SeekOrigin.Begin);
     while (!file.EndOfStream)
     {
         string[] str = file.ReadLine().Split(';');
         if (str[0] == "data")
             writeData(str, st);
         if (str[0] == "def")
             writeDefintion(str);
     }
     int size = (int)memStream.Position - HEADERSIZE;
     memStream.Seek(0, SeekOrigin.Begin);
     writeFitHeader(size, HEADERSIZE);
     UInt16 crc = 0;
     memStream.Seek(0, SeekOrigin.Begin);
     while (memStream.Position < memStream.Length)
     {
         crc = fitstream.Get16(crc, (byte)memStream.ReadByte());
     }
     memStream.WriteByte((byte)(crc & 0xFF));
     memStream.WriteByte((byte)(crc >> 8));
     fitFile.Write(memStream.GetBuffer(), 0, (int)memStream.Position);
 }
コード例 #24
0
ファイル: Class.cs プロジェクト: weedindeed/EndlessClient
		public byte[] SerializeToByteArray()
		{
			byte[] ret = new byte[ClassFile.DATA_SIZE + 1 + Name.Length];
			for (int i = 0; i < ret.Length; ++i)
				ret[i] = 254;

			using (MemoryStream mem = new MemoryStream(ret))
			{
				mem.WriteByte(Packet.EncodeNumber(Name.Length, 1)[0]);
				byte[] name = Encoding.ASCII.GetBytes(Name);
				mem.Write(name, 0, name.Length);

				mem.WriteByte(Base);
				mem.WriteByte(Type);

				mem.Write(Packet.EncodeNumber(Str, 2), 0, 2);
				mem.Write(Packet.EncodeNumber(Int, 2), 0, 2);
				mem.Write(Packet.EncodeNumber(Wis, 2), 0, 2);
				mem.Write(Packet.EncodeNumber(Agi, 2), 0, 2);
				mem.Write(Packet.EncodeNumber(Con, 2), 0, 2);
				mem.Write(Packet.EncodeNumber(Cha, 2), 0, 2);
			}

			return ret;
		}
コード例 #25
0
        public override void Write(ref NetworkStream netstream)
        {
            using (Stream stream = new MemoryStream())
            {
                // write id
                stream.Write(BitConverter.GetBytes((ushort)this.ID), 0, 2);

                // write temporary size
                stream.Write(BitConverter.GetBytes(0), 0, 4);

                // store header size
                int headersize = (int)stream.Position;

                // write name
                stream.WriteByte((byte)this.Name.Length);
                stream.Write(Encoding.ASCII.GetBytes(this.Name), 0, this.Name.Length);

                // write exists
                stream.WriteByte(BitConverter.GetBytes(this.Exists)[0]);

                // go back and write body size
                this.BodySize = (uint)(stream.Length - headersize);

                stream.Position = 2;
                stream.Write(BitConverter.GetBytes(this.BodySize), 0, 4);

                // copy stream to netstream
                stream.Position = 0;
                stream.CopyTo(netstream);
            }
        }
コード例 #26
0
        /// <summary>
        /// Generates the next APDU for establishment of a association with the metering devices
        /// The number and content of the APDU will vary according to the HdlcParams configuration </summary>
        /// <returns> the array of bytes that represents the next APDU to be sent for connection establishment </returns>
        /// <exception cref="DlmsException"> </exception>
        public byte[] connectionRequest()
        {
            try
            {
                switch (state)
                {
                case yadi.dlms.cosem.Cosem.ConnectionState.DISCONNECTED:
                    connection.reset();
                    return(Aarq.request(parameters, connection));                    //OK

                case yadi.dlms.cosem.Cosem.ConnectionState.CONNECTED:
                    LnDescriptor           att    = new LnDescriptor(DlmsClass.ASSOCIATION_LN.id, new Obis("0.0.40.0.0.255"), 1);
                    byte[]                 data   = Security.processChallanger(parameters, connection);
                    System.IO.MemoryStream stream = new System.IO.MemoryStream();
                    stream.WriteByte(Constants.DataType.OCTET_STRING);
                    stream.WriteByte((byte)data.Length);

                    //Array.Reverse(data);
                    stream.Write(data, 0, data.Length);

                    att.setRequestData(stream.ToArray());
                    return(requestAction(att));

                case yadi.dlms.cosem.Cosem.ConnectionState.AUTHENTICATED:
                    throw new System.InvalidOperationException();

                default:
                    throw new System.InvalidOperationException();
                }
            }
            catch (IOException)
            {
                throw new DlmsException(DlmsException.DlmsExceptionReason.INTERNAL_ERROR);
            }
        }
コード例 #27
0
ファイル: ChunkingEncoder.cs プロジェクト: palpha/EasyGelf
 public IEnumerable<byte[]> Encode(byte[] bytes)
 {
     if (bytes.Length <= maxSize)
         yield return bytes;
     else
     {
         var messageChunkSize = maxSize - HeaderSize;
         var chunksCount = bytes.Length / messageChunkSize + 1;
         if(chunksCount > MaxChunkCount)
             throw new ArgumentOutOfRangeException("bytes");
         var remainingBytes = bytes.Length;
         var messageId = idGenerator.GenerateId(bytes);
         for (var chunkSequenceNumber = 0; chunkSequenceNumber < chunksCount; ++chunkSequenceNumber)
         {
             var chunkOffset = chunkSequenceNumber * messageChunkSize;
             var chunkBytes = Math.Min(messageChunkSize, remainingBytes);
             using (var stream = new MemoryStream(messageChunkSize))
             {
                 stream.WriteByte(0x1e);
                 stream.WriteByte(0x0f);
                 stream.Write(messageId, 0, messageId.Length);
                 stream.WriteByte((byte)chunkSequenceNumber);
                 stream.WriteByte((byte)chunksCount);
                 stream.Write(bytes, chunkOffset, chunkBytes);
                 yield return stream.ToArray();
             }
             remainingBytes -= chunkBytes;
         }
     }
 }
コード例 #28
0
ファイル: TlsClientSession.cs プロジェクト: nickchal/pash
		protected void WriteHandshake (MemoryStream ms)
		{
			Context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers (SecurityProtocolType.Tls);
			ms.WriteByte (0x16); // Handshake
			ms.WriteByte (3); // version-major
			ms.WriteByte (1); // version-minor
		}
コード例 #29
0
ファイル: AuthToken.cs プロジェクト: 89sos98/csharp-sdk
 public static byte[] Make(string scope)
 {
     Encoding encoding = Encoding.ASCII;
     byte[] accessKey = encoding.GetBytes(Config.ACCESS_KEY);
     byte[] secretKey = encoding.GetBytes(Config.SECRET_KEY);
     byte[] upToken = null;
     try
     {
         byte[] policyBase64 = encoding.GetBytes(Base64UrlSafe.Encode(scope));
         byte[] digestBase64 = null;
         using (HMACSHA1 hmac = new HMACSHA1(secretKey))
         {
             byte[] digest = hmac.ComputeHash(policyBase64);
             digestBase64 = encoding.GetBytes(Base64UrlSafe.Encode(digest));
         }
         using (MemoryStream buffer = new MemoryStream())
         {
             buffer.Write(accessKey, 0, accessKey.Length);
             buffer.WriteByte((byte)':');
             buffer.Write(digestBase64, 0, digestBase64.Length);
             buffer.WriteByte((byte)':');
             buffer.Write(policyBase64, 0, policyBase64.Length);
             upToken = buffer.ToArray();
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e.ToString());
     }
     return upToken;
 }
コード例 #30
0
        public override ChunkRaw CreateRawChunk()
        {
            if (key.Length == 0)
            {
                throw new System.Exception("Text chunk key must be non empty");
            }
            var ba = new IO.MemoryStream();

            ChunkHelper.WriteBytesToStream(ba, ChunkHelper.ToBytes(key));
            ba.WriteByte(0);               // separator
            ba.WriteByte(compressed ? (byte)1 : (byte)0);
            ba.WriteByte(0);               // compression method (always 0)
            ChunkHelper.WriteBytesToStream(ba, ChunkHelper.ToBytes(langTag));
            ba.WriteByte(0);               // separator
            ChunkHelper.WriteBytesToStream(ba, ChunkHelper.ToBytesUTF8(translatedTag));
            ba.WriteByte(0);               // separator
            byte[] textbytes = ChunkHelper.ToBytesUTF8(val);
            if (compressed)
            {
                textbytes = ChunkHelper.CompressBytes(textbytes, true);
            }
            ChunkHelper.WriteBytesToStream(ba, textbytes);
            byte[]   b     = ba.ToArray();
            ChunkRaw chunk = CreateEmptyChunk(b.Length, false);

            chunk.Data = b;
            return(chunk);
        }
コード例 #31
0
 internal static byte[] Cipher(byte[] buffer, ref byte[] key, bool decrypt)
 {
     var cipher = new Blowfish(key);
     var b = new byte[8];
     using (var m = new MemoryStream(buffer, true))
     {
         while (m.Position < m.Length)
         {
             //Endian swap 2 sets of 4 bytes
             for (int i = 3; i >= 0; i--)
             {
                 b[i] = (byte)m.ReadByte();
             }
             for (int i = 7; i >= 4; i--)
             {
                 b[i] = (byte)m.ReadByte();
             }
             //cipher the 8 bytes
             if (decrypt) cipher.Decipher(b, 8);
             else cipher.Encipher(b, 8);
             //Reset stream position to prepare for writing.
             m.Position -= 8;
             //Endian swap 4 bytes twice
             for (int i = 3; i >= 0; i--)
             {
                 m.WriteByte(b[i]);
             }
             for (int i = 7; i >= 4; i--)
             {
                 m.WriteByte(b[i]);
             }
         }
     }
     return buffer;
 }
コード例 #32
0
		public static void Main(string[] args)
		{
			{
				var m = new MemoryStream();

				m.WriteByte((byte)'A');
				m.WriteByte((byte)'\n');
				m.Position = 0;

				var x = new StreamReader(m);

				var z = x.ReadLine();

				Console.WriteLine(z);
			}

			{
				var m = new MemoryStream();

				m.WriteByte((byte)'\r');
				m.WriteByte((byte)'\n');
				m.Position = 0;

				var x = new StreamReader(m);

				var z = x.ReadLine();

				Console.WriteLine(z);
			}
		}
コード例 #33
0
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IDefaultPage page)
        {
            var m = new MemoryStream();

            m.WriteByte((byte)'H');
            m.WriteByte((byte)'E');
            m.WriteByte((byte)'L');
            m.WriteByte((byte)'L');
            m.WriteByte((byte)'O');

            var a = m.ToArray();

            //Native.API.var_dump(a);

            var w = new StringBuilder();

            foreach (var item in a)
            {
                w.Append(item.ToString("x2"));
            }

            w.Append(", " + Convert.ToBase64String(a));

            // {48454c4c4f, SEVMTE8=}
            var e = w.ToString();

            new IHTMLPre { innerText = e }.AttachToDocument();

            @"Hello world".ToDocumentTitle();
            // Send data from JavaScript to the server tier
            service.WebMethod2(
                @"A string from JavaScript.",
                value => value.ToDocumentTitle()
            );
        }
コード例 #34
0
        public override void Write(ref NetworkStream netstream)
        {
            using (Stream stream = new MemoryStream())
            {
                // write Packet ID
                stream.Write(BitConverter.GetBytes((ushort)this.ID), 0, 2);

                // write Packet Size
                stream.Write(BitConverter.GetBytes(this.BodySize), 0, 4);

                // write UserID
                stream.WriteByte((byte)this.UserID.Length);
                stream.Write(Encoding.ASCII.GetBytes(this.UserID), 0, this.UserID.Length);

                // write PCName
                stream.WriteByte((byte)this.PCName.Length);
                stream.Write(Encoding.ASCII.GetBytes(this.PCName), 0, this.PCName.Length);

                // write AuthKey
                stream.Write(BitConverter.GetBytes(this.AuthKey), 0, 4);

                // copy stream to netstream
                stream.Position = 0;
                stream.CopyTo(netstream);
            }
        }
コード例 #35
0
        private byte[] GetBytes(CassandraType[] components)
        {
            using (var bytes = new MemoryStream())
            {
                foreach (var c in components)
                {
                    var b = (byte[])c;
                    var length = (ushort)b.Length;

                    // comparator part
                    bytes.WriteByte((byte)1);
                    bytes.WriteByte((byte)_aliases.FirstOrDefault(x => x.Value == c.GetType()).Key);

                    // value length
                    bytes.Write(BitConverter.GetBytes(length), 0, 2);

                    // value
                    bytes.Write(b, 0, length);

                    // end of component
                    bytes.WriteByte((byte)0);
                }

                return bytes.ToArray();
            }
        }
コード例 #36
0
        private static byte[] generateInitiateRequest(CosemParameters parameters)
        {
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            stream.WriteByte(Constants.xDlmsApdu.NoCiphering.INITIATE_REQUEST);
            stream.WriteByte(0);                              //Dedicated key
            stream.WriteByte(0);                              //Response-allowed
            stream.WriteByte(0);                              //Proposed quality of service
            stream.WriteByte(Constants.DLMS_VERSION);         //Dlms version
            stream.WriteByte(Constants.ConformanceBlock.TAG); //Conformance block tag
            byte[] conformance = generateConformanceBlock(parameters);
            stream.WriteByte((byte)(conformance.Length));
            stream.Write(conformance, 0, conformance.Length);             //Conformance block

            //stream.WriteByte(ByteBuffer.allocate(2).putShort(parameters.maxPduSize).array());
            stream.WriteByte((byte)(parameters.maxPduSize >> 8)); //Max pdu size
            stream.WriteByte((byte)(parameters.maxPduSize));

            System.IO.MemoryStream stream2 = new System.IO.MemoryStream();
            if (parameters.securityType != SecurityType.NONE)
            {
                stream2.WriteByte(Constants.xDlmsApdu.GlobalCiphering.INITIATE_REQUEST);
                byte[] data = Security.authenticatedEncryption(parameters, stream.ToArray());
                stream2.WriteByte((byte)(data.Length));
                stream2.Write(data, 0, data.Length);
            }
            else
            {
                //stream2.WriteByte(stream.ToArray());
                byte[] aux = stream.ToArray();
                stream2.Write(aux, 0, aux.Length);
            }
            return(stream2.ToArray());
        }
コード例 #37
0
        /// <summary>
        /// Perform the next step
        /// </summary>
        /// <param name="s">Null if it's the initial response</param>
        /// <param name="doc">Document to create Steps in</param>
        /// <returns></returns>
        public override Step step(Step s, XmlDocument doc)
        {
            Debug.Assert(s == null);
            Auth a = new Auth(doc);
            a.Mechanism = MechanismType.PLAIN;
            MemoryStream ms = new MemoryStream();

            // message = [authorize-id] NUL authenticate-id NUL password

            // Skip authzid.
            ms.WriteByte(0);
            string u = this[USERNAME];
            if ((u == null) || (u == ""))
                throw new SASLException("Username required");
            byte[] bu = System.Text.Encoding.UTF8.GetBytes(u);
            ms.Write(bu, 0, bu.Length);
            ms.WriteByte(0);
            string p = this[PASSWORD];
            if ((p == null) || (p == ""))
                throw new SASLException("Password required");
            byte[] pu = System.Text.Encoding.UTF8.GetBytes(p);
            ms.Write(pu, 0, pu.Length);

            a.Bytes = ms.ToArray();
            return a;
        }
コード例 #38
0
        public override ChunkRaw CreateRawChunk()
        {
            var ba = new IO.MemoryStream();

            ChunkHelper.WriteBytesToStream(ba, ChunkHelper.ToBytes(PalName));
            ba.WriteByte(0);               // separator
            ba.WriteByte((byte)SampleDepth);
            int nentries = GetNentries();

            for (int n = 0; n < nentries; n++)
            {
                for (int i = 0; i < 4; i++)
                {
                    if (SampleDepth == 8)
                    {
                        PngHelperInternal.WriteByte(ba, (byte)Palette[n * 5 + i]);
                    }
                    else
                    {
                        PngHelperInternal.WriteInt2(ba, Palette[n * 5 + i]);
                    }
                }
                PngHelperInternal.WriteInt2(ba, Palette[n * 5 + 4]);
            }
            byte[]   b     = ba.ToArray();
            ChunkRaw chunk = CreateEmptyChunk(b.Length, false);

            chunk.Data = b;
            return(chunk);
        }
コード例 #39
0
ファイル: Packets.cs プロジェクト: polserver/poltools
 private static void WriteBE32(MemoryStream ms, uint p)
 {
     ms.WriteByte((byte)(p >> 0x18));
     ms.WriteByte((byte)(p >> 0x10));
     ms.WriteByte((byte)(p >> 0x08));
     ms.WriteByte((byte)p);
 }
コード例 #40
0
        public static byte[] authenticatedEncryption(CosemParameters parameters, byte[] data)
        {
            if (parameters.securityType == SecurityType.NONE)
            {
                return(data);
            }
            int ivCounter = parameters.getInvocationCounter();
            int sc        = 0;

            switch (parameters.securityType)
            {
            case SecurityType.AUTHENTICATION:
                sc = SC_AUTHENTICATION;
                byte[] authData = new byte[parameters.ak.Length + data.Length + 1];
                authData[0] = SC_AUTHENTICATION;
                Array.Copy(parameters.ak, 0, authData, 1, parameters.ak.Length);
                Array.Copy(data, 0, authData, parameters.ak.Length + 1, data.Length);
                byte[] mac   = aesGcm(new byte[0], authData, parameters, ivCounter);
                byte[] data_ = new byte[data.Length + mac.Length];
                Array.Copy(data, 0, data_, 0, data.Length);
                Array.Copy(mac, 0, data_, data.Length, mac.Length);
                data = data_;
                break;

            case SecurityType.AUTHENTICATION_ENCRYPTION:
                sc          = SC_AUTHENTICATION_ENCRYPTION;
                authData    = new byte[parameters.ak.Length + 1];
                authData[0] = SC_AUTHENTICATION_ENCRYPTION;
                Array.Copy(parameters.ak, 0, authData, 1, parameters.ak.Length);
                data = aesGcm(data, authData, parameters, ivCounter);
                break;

            case SecurityType.ENCRYPTION:
                sc   = SC_ENCRYPTION;
                data = aesGcm(data, new byte[0], parameters, ivCounter);
                break;

            default:
                throw new System.InvalidOperationException();
            }

            try
            {
                System.IO.MemoryStream stream = new System.IO.MemoryStream();
                stream.WriteByte((byte)sc);
                stream.WriteByte((byte)(ivCounter >> 24));
                stream.WriteByte((byte)(ivCounter >> 16));
                stream.WriteByte((byte)(ivCounter >> 8));
                stream.WriteByte((byte)(ivCounter));
                stream.Write(data, 0, data.Length);
                return(stream.ToArray());
            }
            catch (IOException)
            {
                throw new DlmsException(DlmsException.DlmsExceptionReason.INTERNAL_ERROR);
            }
        }
コード例 #41
0
        public override SmtpResponse DataLine(ISmtpSessionInfo sessionInfo, byte[] lineBuf)
        {
            var fileName = GetFileNameFromSessionInfo(sessionInfo);

            FS.Write(lineBuf, 0, lineBuf.Length);
            FS.WriteByte(13);
            FS.WriteByte(10);
            return(SmtpResponse.None);
        }
コード例 #42
0
 public byte[] Serialize()
 {
     lock (_lock) {
         using (var memoryStream = new System.IO.MemoryStream()) {
             foreach (ArrayItem item in _array)
             {
                 memoryStream.WriteByte((byte)(((ushort)item.BlockType) / 256));
                 memoryStream.WriteByte((byte)(((ushort)item.BlockType) % 256));
                 memoryStream.WriteByte((byte)item.Count);
             }
             return(memoryStream.ToArray());
         }
     }
 }
コード例 #43
0
ファイル: coder.cs プロジェクト: ratesquant/ACQ.Games
 /*
  * The output bit routine just has to set a bit in the current byte
  * if requested to.  After that, it updates the mask.  If the mask
  * shows that the current byte is filled up, it is time to go to the
  * next character in the buffer.  If the next character is past the
  * end of the buffer, it is time to flush the buffer.
  */
 private void output_bit(int bit)
 {
     if (Convert.ToBoolean(bit))
     {
         current_output_byte |= output_mask;
     }
     output_mask >>= 1;
     if (output_mask == 0)
     {
         output_mask = 0x80;
         output_buffer.WriteByte(current_output_byte);
         current_output_byte = 0;
     }
 }
コード例 #44
0
        public virtual void StartWalking(WalkDirection dir, ulong startTime, Vector2d startPos)
        {
            if (!IsAlive || Tools.TicksToSeconds(Map.TimeTicks - myLastCastTime) < CastAnimationDuration)
            {
                return;
            }

            myNextWalkDirection = dir;

            myWalkStartTime = startTime;
            myWalkStartPos  = startPos;

            if (dir == WalkDirection.Up || dir == WalkDirection.Down)
            {
                OriginX = startPos.X;
            }
            else
            {
                OriginY = startPos.Y;
            }

            if (IsServer)
            {
                System.IO.MemoryStream stream = new System.IO.MemoryStream();
                stream.WriteByte((byte)myNextWalkDirection);
                stream.Write(BitConverter.GetBytes(myWalkStartTime), 0, sizeof(UInt64));
                stream.Write(BitConverter.GetBytes(myWalkStartPos.X), 0, sizeof(Double));
                stream.Write(BitConverter.GetBytes(myWalkStartPos.Y), 0, sizeof(Double));
                SendStateUpdate("StartWalking", stream);
                stream.Close();

                myLastWalkStateSent = Map.TimeTicks;
            }
        }
コード例 #45
0
        public Assembly InstanceCache(string key)
        {
            if (htEx.ContainsKey(key))
            {
                return((Assembly)(htEx[key]));
            }
            else
            {
                Byte[]                 content = null;
                FileStream             f       = new FileStream(key, FileMode.Open, FileAccess.Read, FileShare.Read);
                int                    b1;
                System.IO.MemoryStream tempStream = new System.IO.MemoryStream();
                while ((b1 = f.ReadByte()) != -1)
                {
                    tempStream.WriteByte(((byte)b1));
                }
                f.Close();

                content = tempStream.ToArray();
                Assembly valuenew = Assembly.Load(content);

                lock (obj)
                {
                    if (!htEx.ContainsKey(key))
                    {
                        htEx[key] = valuenew;
                    }
                }



                return(valuenew);
            }
        }
コード例 #46
0
        /// <summary>
        /// The function can be used to generate a hashed version of a user-provided password
        /// to store in a database for authentication purposes.
        /// </summary>
        /// <param name="password">The secret password to generate the key from.</param>
        /// <param name="salt">A (byte) string to use for better protection from dictionary attacks.</param>
        /// <param name="dklen">The cumulative length of the keys to produce.</param>
        /// <param name="count">Iteration count.</param>
        /// <returns>A byte string of length dklen that can be used as key material.</returns>
        /// <seealso cref="https://stackoverflow.com/questions/18648084/rfc2898-pbkdf2-with-sha256-as-digest-in-c-sharp"/>
        /// <seealso cref="https://pycryptodome.readthedocs.io/en/latest/src/protocol/kdf.html"/>
        static byte[] PBKDF2_SHA256_GetBytes(byte[] password, byte[] salt, int dklen, int count)
        {
            // NOTE: The iteration count should be as high as possible without causing
            // unreasonable delay. Note also that the password and salt are byte arrays, not strings.
            // After use, the password and salt should be cleared (with Array.Clear)

            using (var hmac = new System.Security.Cryptography.HMACSHA256(password))
            {
                int hashLength = hmac.HashSize / 8;
                if ((hmac.HashSize & 7) != 0)
                {
                    hashLength++;
                }
                int keyLength = dklen / hashLength;
                if ((long)dklen > (0xFFFFFFFFL * hashLength) || dklen < 0)
                {
                    throw new ArgumentOutOfRangeException("dklen");
                }
                if (dklen % hashLength != 0)
                {
                    keyLength++;
                }
                byte[] extendedkey = new byte[salt.Length + 4];
                Buffer.BlockCopy(salt, 0, extendedkey, 0, salt.Length);
                using (var ms = new System.IO.MemoryStream())
                {
                    for (int i = 0; i < keyLength; i++)
                    {
                        extendedkey[salt.Length]     = (byte)(((i + 1) >> 24) & 0xFF);
                        extendedkey[salt.Length + 1] = (byte)(((i + 1) >> 16) & 0xFF);
                        extendedkey[salt.Length + 2] = (byte)(((i + 1) >> 8) & 0xFF);
                        extendedkey[salt.Length + 3] = (byte)(((i + 1)) & 0xFF);
                        byte[] u = hmac.ComputeHash(extendedkey);
                        Array.Clear(extendedkey, salt.Length, 4);
                        byte[] f = u;
                        for (int j = 1; j < count; j++)
                        {
                            u = hmac.ComputeHash(u);
                            for (int k = 0; k < f.Length; k++)
                            {
                                f[k] ^= u[k];
                            }
                        }
                        ms.Write(f, 0, f.Length);
                        Array.Clear(u, 0, u.Length);
                        Array.Clear(f, 0, f.Length);
                    }
                    byte[] dk = new byte[dklen];
                    ms.Position = 0;
                    ms.Read(dk, 0, dklen);
                    ms.Position = 0;
                    for (long i = 0; i < ms.Length; i++)
                    {
                        ms.WriteByte(0);
                    }
                    Array.Clear(extendedkey, 0, extendedkey.Length);
                    return(dk);
                }
            }
        }
コード例 #47
0
        public static byte[] GetBytesFromFile(string filePath)
        {
            System.IO.Stream       theStream  = null;
            System.IO.MemoryStream tempStream = null;
            try
            {
                theStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                int b1;
                tempStream = new System.IO.MemoryStream();
                while ((b1 = theStream.ReadByte()) != -1)
                {
                    tempStream.WriteByte(((byte)b1));
                }
                return(tempStream.ToArray());
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (theStream != null)
                {
                    theStream.Close();
                }
                if (tempStream != null)
                {
                    tempStream.Close();
                }
            }

            return(null);
        }
コード例 #48
0
        public IDataObject GetClipboardData()
        {
            if (DataType == Domain.ClipboardDataType.Text)
            {
                return(new DataObject(DataFormats.Text, Text));
            }

            if (DataType == Domain.ClipboardDataType.FileDrop)
            {
                var result = new DataObject();
                result.SetFileDropList(StringToCollection(Text));
//	            var result = new DataObject(DataFormats.FileDrop, StringToArray(Text));

                var strm = new System.IO.MemoryStream();
                strm.WriteByte((byte)DragDropEffects.Copy);
                result.SetData("Preferred Dropeffect", strm);
                return(result);
            }

            if (DataType == Domain.ClipboardDataType.Image)
            {
                var result = new DataObject();
                result.SetImage(Image);

                var strm = new System.IO.MemoryStream();
                strm.WriteByte((byte)DragDropEffects.Copy);
                result.SetData("Preferred Dropeffect", strm);
                return(result);
            }

            return(null);
        }
コード例 #49
0
        public byte[] DownloadFile(string strFilePath, string path)
        {
            FileStream fs = null;
            string     CurrentUploadFolderPath = HttpContext.Current.Server.MapPath(path);
            string     CurrentUploadFilePath   = CurrentUploadFolderPath + "\\" + strFilePath;

            if (File.Exists(CurrentUploadFilePath))
            {
                try
                {
                    ///打开现有文件以进行读取。
                    fs = File.OpenRead(CurrentUploadFilePath);
                    int b1;
                    System.IO.MemoryStream tempStream = new System.IO.MemoryStream();
                    while ((b1 = fs.ReadByte()) != -1)
                    {
                        tempStream.WriteByte(((byte)b1));
                    }
                    return(tempStream.ToArray());
                }
                catch (Exception ex)
                {
                    return(new byte[0]);
                }
                finally
                {
                    fs.Close();
                }
            }
            else
            {
                return(new byte[0]);
            }
        }
コード例 #50
0
        private void addLast(PDFArray contents)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            ms.WriteByte((byte)'Q');
            ms.WriteByte((byte)'\r');
            ms.WriteByte((byte)'q');
            ms.WriteByte((byte)'\r');
            ms.WriteByte((byte)'Q');

            PDFDictionary       dict = new PDFDictionary();
            PDFDictionaryStream ds   = new PDFDictionaryStream(dict, ms);

            contents.AddItem(ds);
            _canvas              = new Canvas(ms, Resources, PageRect);
            _canvas.ChangeGroup += new ChangeGroupEventHandler(m_canvas_ChangeGroup);
        }
コード例 #51
0
        internal static byte[] processChallanger(CosemParameters parameters, CosemConnection connection)
        {
            try
            {
                switch (parameters.authenticationType.innerEnumValue)
                {
                case AuthenticationType.InnerEnum.PUBLIC:
                case AuthenticationType.InnerEnum.LLS:
                    throw new System.InvalidOperationException();

                case AuthenticationType.InnerEnum.HLS:
                    return(aes128(connection.challengeServerToClient, parameters.llsHlsSecret));

                case AuthenticationType.InnerEnum.HLS_MD5:
                    return(md5(connection.challengeServerToClient, parameters.llsHlsSecret));

                case AuthenticationType.InnerEnum.HLS_SHA1:
                    return(sha1(connection.challengeServerToClient, parameters.llsHlsSecret));

                case AuthenticationType.InnerEnum.HLS_GMAC:
                    int ivCounter = parameters.getInvocationCounter();
                    System.IO.MemoryStream data = new System.IO.MemoryStream();
                    data.WriteByte(SC_AUTHENTICATION);
                    data.Write(parameters.ak, 0, parameters.ak.Length);
                    data.Write(connection.challengeServerToClient, 0, connection.challengeServerToClient.Length);
                    System.IO.MemoryStream stream = new System.IO.MemoryStream();
                    stream.WriteByte(SC_AUTHENTICATION);
                    stream.WriteByte((byte)(ivCounter >> 24));
                    stream.WriteByte((byte)(ivCounter >> 16));
                    stream.WriteByte((byte)(ivCounter >> 8));
                    stream.WriteByte((byte)(ivCounter));
                    byte[] aux = Security.aesGcm(new byte[0], data.ToArray(), parameters, ivCounter);
                    stream.Write(aux, 0, aux.Length);
                    return(stream.ToArray());

                default:
                    throw new System.ArgumentException();
                }
            }
            catch (IOException)
            {
                throw new DlmsException(DlmsException.DlmsExceptionReason.INTERNAL_ERROR);
            }
        }
コード例 #52
0
 private byte[] PBKDF2Sha256GetBytes(int dklen, byte[] password, byte[] salt, int iterationCount)
 {
     using (var hmac = new System.Security.Cryptography.HMACSHA256(password))
     {
         int hashLength = hmac.HashSize / 8;
         if ((hmac.HashSize & 7) != 0)
         {
             hashLength++;
         }
         int keyLength = dklen / hashLength;
         if ((long)dklen > (0xFFFFFFFFL * hashLength) || dklen < 0)
         {
             throw new ArgumentOutOfRangeException("dklen");
         }
         if (dklen % hashLength != 0)
         {
             keyLength++;
         }
         byte[] extendedkey = new byte[salt.Length + 4];
         Buffer.BlockCopy(salt, 0, extendedkey, 0, salt.Length);
         using (var ms = new System.IO.MemoryStream())
         {
             for (int i = 0; i < keyLength; i++)
             {
                 extendedkey[salt.Length]     = (byte)(((i + 1) >> 24) & 0xFF);
                 extendedkey[salt.Length + 1] = (byte)(((i + 1) >> 16) & 0xFF);
                 extendedkey[salt.Length + 2] = (byte)(((i + 1) >> 8) & 0xFF);
                 extendedkey[salt.Length + 3] = (byte)(((i + 1)) & 0xFF);
                 byte[] u = hmac.ComputeHash(extendedkey);
                 Array.Clear(extendedkey, salt.Length, 4);
                 byte[] f = u;
                 for (int j = 1; j < iterationCount; j++)
                 {
                     u = hmac.ComputeHash(u);
                     for (int k = 0; k < f.Length; k++)
                     {
                         f[k] ^= u[k];
                     }
                 }
                 ms.Write(f, 0, f.Length);
                 Array.Clear(u, 0, u.Length);
                 Array.Clear(f, 0, f.Length);
             }
             byte[] dk = new byte[dklen];
             ms.Position = 0;
             ms.Read(dk, 0, dklen);
             ms.Position = 0;
             for (long i = 0; i < ms.Length; i++)
             {
                 ms.WriteByte(0);
             }
             Array.Clear(extendedkey, 0, extendedkey.Length);
             return(dk);
         }
     }
 }
コード例 #53
0
        internal static bool verifyChallenger(CosemParameters parameters, CosemConnection connection, byte[] data)
        {
            if (data == null || data.Length == 0)
            {
                return(false);
            }
            try
            {
                byte[] calculated = new byte[0];
                switch (parameters.authenticationType.innerEnumValue)
                {
                case AuthenticationType.InnerEnum.PUBLIC:
                case AuthenticationType.InnerEnum.LLS:
                    throw new System.InvalidOperationException();

                case AuthenticationType.InnerEnum.HLS:
                    calculated = aes128(connection.challengeServerToClient, parameters.llsHlsSecret);
                    break;

                case AuthenticationType.InnerEnum.HLS_MD5:
                    calculated = md5(connection.challengeClientToServer, parameters.llsHlsSecret);
                    break;

                case AuthenticationType.InnerEnum.HLS_SHA1:
                    calculated = sha1(connection.challengeClientToServer, parameters.llsHlsSecret);
                    break;

                case AuthenticationType.InnerEnum.HLS_GMAC:
                    if (data[0] != SC_AUTHENTICATION)
                    {
                        return(false);
                    }
                    System.IO.MemoryStream stream = new System.IO.MemoryStream();
                    stream.WriteByte(SC_AUTHENTICATION);
                    stream.Write(parameters.ak, 0, parameters.ak.Length);
                    stream.Write(connection.challengeClientToServer, 0, connection.challengeClientToServer.Length);
                    //connection.serverInvocationCounter = BitConverter.ToInt32(helper.extensions.copyOfRange(data, 1, 5), 0);
                    var aux = helper.extensions.copyOfRange(data, 1, 5);
                    connection.serverInvocationCounter = BitConverter.ToInt32(new byte[] { (aux[3]), (aux[2]), (aux[1]), (aux[0]) }, 0);
                    data = helper.extensions.copyOfRange(data, 5, data.Length);
                    CosemParameters cosemParams = new CosemParameters();
                    cosemParams.setSystemTitle(connection.serverSysTitle);
                    cosemParams.setEk(parameters.ek);
                    calculated = Security.aesGcm(new byte[0], stream.ToArray(), cosemParams, connection.serverInvocationCounter);
                    break;

                default:
                    throw new System.ArgumentException();
                }
                return(Enumerable.SequenceEqual(data, calculated));
            }
            catch (IOException)
            {
                throw new DlmsException(DlmsException.DlmsExceptionReason.INTERNAL_ERROR);
            }
        }
コード例 #54
0
        static public Image ConvertByteArrayToImage(byte[] File)
        {
            System.IO.MemoryStream memoryStream1 = new System.IO.MemoryStream();
            foreach (byte b in File)
            {
                memoryStream1.WriteByte(b);
            }
            Image image1 = Image.FromStream(memoryStream1);

            return(image1);
        }
コード例 #55
0
ファイル: Program.cs プロジェクト: EgorVidVal/ServerTcp
        static void ByteToImage(byte[] b)
        {
            System.IO.MemoryStream memoryStream1 = new System.IO.MemoryStream();
            foreach (byte b1 in b)
            {
                memoryStream1.WriteByte(b1);
            }
            Image image1 = Image.FromStream(memoryStream1);

            image1.Save("C:\\pict.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
        }
コード例 #56
0
        /// <summary>
        /// ConvertStreamToByteBuffer:把给定的文件流转换为二进制字节数组。
        /// </summary>
        /// <param name="theStream"></param>
        /// <returns></returns>
        public static byte[] ConvertStreamToByteBuffer(System.IO.Stream theStream)
        {
            int b1;

            System.IO.MemoryStream tempStream = new System.IO.MemoryStream();
            while ((b1 = theStream.ReadByte()) != -1)
            {
                tempStream.WriteByte(((byte)b1));
            }
            return(tempStream.ToArray());
        }
コード例 #57
0
        private void openSettings()
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Filter = "JSON files(*.json)|*.json";
            ofd.ShowDialog();

            var settings = File.ReadAllLines(ofd.FileName);

            foreach (var item in settings)
            {
                var items = JsonConvert.DeserializeObject <SavingSettings>(item);

                for (int i = 0; i < settings.Length; i++)
                {
                    if (items.SettingName == "postcardPanel")
                    {
                        MemoryStream memoryStream1 = new System.IO.MemoryStream();
                        foreach (byte b1 in items.SettingImage)
                        {
                            memoryStream1.WriteByte(b1);
                        }
                        Image image1 = Image.FromStream(memoryStream1);
                        postcardPanel.BackgroundImage = image1;
                    }
                }
                for (int i = 0; i < Templates.postcardLabelss.Count(); i++)
                {
                    if (Templates.postcardLabelss[i].Name == items.SettingName)
                    {
                        Templates.postcardLabelss[i].Text      = items.SettingValue;
                        Templates.postcardLabelss[i].Font      = items.Font;
                        Templates.postcardLabelss[i].ForeColor = items.Color;

                        break;
                    }
                    if (Templates.postcardPanels[i].Name == items.SettingName)
                    {
                        MemoryStream memoryStream1 = new System.IO.MemoryStream();
                        if (items.SettingImage != null)
                        {
                            foreach (byte b1 in items.SettingImage)
                            {
                                memoryStream1.WriteByte(b1);
                            }
                            Image image1 = Image.FromStream(memoryStream1);

                            Templates.postcardPanels[i].BackgroundImage = image1;
                            break;
                        }
                    }
                }
            }
        }
コード例 #58
0
    private static void b64_from_24bit(byte b2, byte b1, byte b0, int n, IO.MemoryStream finalResult)
    {
        const string b64t = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

        int w = ((b2) << 16) | ((b1) << 8) | (b0);

        while (n-- > 0)
        {
            finalResult.WriteByte((byte)b64t[w & 0x3f]);
            w >>= 6;
        }
    }
コード例 #59
0
        public unsafe static string PtrUTF8StrToString(this IntPtr element)
        {
            System.IO.MemoryStream w = new System.IO.MemoryStream(10 * 1024);
            var p = (byte *)element;

            while (*p != 0)
            {
                w.WriteByte(*p);
                p++;
            }
            return(w.Length == 0 ? string.Empty : utf8WithoutBom.GetString(w.ToArray(), 0, (int)w.Length));
        }
コード例 #60
0
    public static byte[] Decode(string src)
    {
        var m = new System.IO.MemoryStream();
        int p = 0;

        while (p < src.Length)
        {
            if (src[p] == '=')
            {
                if (src[p + 1] != '\r' || src[p + 2] != '\n')
                {
                    m.WriteByte(Convert.ToByte(src.Substring(p + 1, 2), 16));
                }
                p += 3;
            }
            else
            {
                m.WriteByte((byte)src[p++]);
            }
        }
        return(m.ToArray());
    }