Esempio n. 1
0
        public override string ReadBytes(Stream stream)
        {
            int len = stream.ReadInt32();

            byte[] bytes = stream.ReadBytes(len);
            return(DefaultEncoding.GetString(bytes));
        }
Esempio n. 2
0
 private void reencode(string value)
 {
     if (ReplaceEndStringChar)
     {
         int _NeededBytes = DefaultEncoding.GetByteCount(value);
         if (_NeededBytes < _m_Size)
         {
             AppendEndStringChar = true;
         }
         else
         {
             value = value.Remove(value.Length - 1);
             AppendEndStringChar = true;
         }
     }
     if (AppendEndStringChar)
     {
         value = value + (char)0x00;
     }
     _m_name = new byte[_m_Size];
     byte[] data = DefaultEncoding.GetBytes(value);
     if (data.Length > _m_Size)
     {
         Buffer.BlockCopy(data, 0, _m_name, 0, _m_Size);
         return;
     }
     Buffer.BlockCopy(data, 0, _m_name, 0, data.Length);
 }
Esempio n. 3
0
        internal override void Write(BinaryWriter writer)
        {
            writer.Write(Version);
            writer.Write(VersionNeededToExtract);
            writer.Write(Flags);
            writer.Write(CompressionMethod);
            writer.Write(LastModifiedTime);
            writer.Write(LastModifiedDate);
            writer.Write(Crc);
            writer.Write(CompressedSize);
            writer.Write(UncompressedSize);

            byte[] nameBytes = DefaultEncoding.GetBytes(Name);
            writer.Write((ushort)nameBytes.Length);
            writer.Write((ushort)Extra.Length);
            writer.Write((ushort)Comment.Length);

            writer.Write(DiskNumberStart);
            writer.Write(InternalFileAttributes);
            writer.Write(ExternalFileAttributes);
            writer.Write(RelativeOffsetOfEntryHeader);

            writer.Write(nameBytes);
            writer.Write(Extra);
            writer.Write(Comment);
        }
Esempio n. 4
0
        private static void ReadZipFileComment(ZipFile zf)
        {
            // read the comment here
            byte[] block = new byte[2];
            zf.ReadStream.Read(block, 0, block.Length);

            Int16 commentLength = (short)(block[0] + block[1] * 256);

            if (commentLength > 0)
            {
                block = new byte[commentLength];
                zf.ReadStream.Read(block, 0, block.Length);

                // workitem 6513 - only use UTF8 as necessary
                // test reflexivity
                string s1 = DefaultEncoding.GetString(block, 0, block.Length);
                byte[] b2 = DefaultEncoding.GetBytes(s1);
                if (BlocksAreEqual(block, b2))
                {
                    zf.Comment = s1;
                }
                else
                {
                    // need alternate (non IBM437) encoding
                    // workitem 6415
                    // use UTF8 if the caller hasn't already set a non-default encoding
                    System.Text.Encoding e = (zf._provisionalAlternateEncoding.CodePage == 437)
                        ? System.Text.Encoding.UTF8
                        : zf._provisionalAlternateEncoding;
                    zf.Comment = e.GetString(block, 0, block.Length);
                }
            }
        }
Esempio n. 5
0
        private byte[] GeneratePeerId()
        {
            MemoryStream ms = new MemoryStream(20);

            byte[] clientIdBytes = DefaultEncoding.GetBytes(ClientId);
            ms.Write(clientIdBytes, 0, clientIdBytes.Length);
            byte[] dateBytes = BitConverter.GetBytes(DateTime.Now.ToBinary().GetHashCode());
            byte   hash      = 0;

            foreach (byte b in dateBytes)
            {
                hash ^= b;
            }

            ms.WriteByte(hash);
            ms.WriteByte((byte)System.Diagnostics.Process.GetCurrentProcess().Id);
            int padCount = (int)(20 - ms.Length);

            for (int i = padCount; i > 0; i--)
            {
                ms.WriteByte((byte)'0');
            }

            return(ms.ToArray());
        }
        /// <summary>
        /// Calcula o tamanho do parametro.
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        private long ComputeParameterLength(MultipartFormDataParameter parameter)
        {
            var  letterLenght   = DefaultEncoding.GetByteCount("&");
            var  boundrayLenght = DefaultEncoding.GetByteCount(_boundary);
            long length         = 0;

            return(DefaultEncoding.GetByteCount("--") + boundrayLenght + (letterLenght * 2) + DefaultEncoding.GetByteCount(string.Format("Content-Type: {0}", parameter.ContentType)) + (letterLenght * 2) + DefaultEncoding.GetByteCount("Content-Disposition: form-data; name=\"") + DefaultEncoding.GetByteCount(HttpUtility.UrlEncode(parameter.Name) ?? "") + letterLenght + (parameter is IFileMultipartFormDataParameter ? string.Format("; filename=\"{0}\"", (((IFileMultipartFormDataParameter)parameter).FileName)).Length : 0) + (letterLenght * 2) + (letterLenght * 2) + (parameter.TryComputeLength(out length) ? length : 0) + (letterLenght * 2));
        }
Esempio n. 7
0
        /// <summary>
        /// Converts bytes using the default encoding
        /// </summary>
        private string ConvertBytesToStringWithDefaultEncoding(byte[] line)
        {
            if (line == null)
            {
                return("");
            }

            return(DefaultEncoding.GetString(line));
        }
Esempio n. 8
0
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="buff"></param>
        public void Send(byte[] buff)
        {
            string recv = DefaultEncoding.GetString(buff);

            LogRevMsg.LogText("发送", recv);
            Lib.LogManager.Logger.LogInfo("发送:" + "\r" + recv);
            this.comm.Write(buff, 0, buff.Length);
            //MachineAdapter.Common.Manager.MonitorManager.Instance.SendLog(recv);
        }
Esempio n. 9
0
        private void ParseBody(byte[] data)
        {
            this.UnprocessedData = new byte[] { };
            if (StartBoundary == "--") //isEmpty = > singlepart
            {
                this._bodyBytes = data;
            }
            else //multipart
            {
                var    crlf  = DefaultEncoding.GetBytes(CRLF);
                int    index = 0;
                byte[] stringBytes;
                //чтение собственного текста
                {
                    int nextIndex = index;
                    while (readLine(data, ref nextIndex, out stringBytes))
                    {
                        if (stringBytes.ValueEquals(this.StartBoundaryBytes1) || stringBytes.ValueEquals(this.EndBoundaryBytes))
                        {
                            this._bodyBytes = data.GetSubArray(0, index);
                            break;
                        }

                        index = nextIndex;
                    }
                    index = nextIndex;
                }

                //достигнут конец данных
                if (stringBytes == null || stringBytes.ValueEquals(this.EndBoundaryBytes))
                {
                    return;
                }

                int endIndex = BytesExtensions.IndexOf(data, this.EndBoundaryBytes, index);
                if (endIndex == -1)
                {
                    endIndex = data.Length;
                }

                while (index < endIndex)
                {
                    int nextIndex = BytesExtensions.IndexOf(data, this.StartBoundaryBytes1, index);
                    if (nextIndex == -1)
                    {
                        nextIndex = data.Length + crlf.Length;
                    }
                    var childData = data.GetSubArray(index, nextIndex - index - crlf.Length);
                    var child     = createMimeReader(this, childData);
                    this.Children.Add(child);
                    index = nextIndex + this.StartBoundaryBytes1.Length + crlf.Length;
                }
            }
        }
Esempio n. 10
0
 //------------------------------------------------------------------------------------------------------------------
 public static byte[] StringToBuffer(ref string Str)
 {
     if (Str == null || Str == "")
     {
         return(new byte[0]);
     }
     else
     {
         return(DefaultEncoding.GetBytes(Str));
     }
 }
Esempio n. 11
0
        /// <summary>
        /// Decrypt with private key
        /// </summary>
        /// <param name="data"></param>
        /// <param name="encryptionEncodeMode"><see cref="CryptoBase.DefaultEncryptionEncodeMode"/></param>
        /// <param name="privateKey">Private key</param>
        /// <returns></returns>
        public string Decrypt(string data, EncodeMode encryptionEncodeMode, string privateKey)
        {
            if (string.IsNullOrWhiteSpace(data))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(data));
            }
            if (string.IsNullOrWhiteSpace(privateKey))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(privateKey));
            }

            return(DefaultEncoding.GetString(Decrypt(encryptionEncodeMode.DecodeToBytes(data, DefaultEncoding), privateKey)));
        }
Esempio n. 12
0
        /// <summary>
        /// Encrypt with public key
        /// </summary>
        /// <param name="data"></param>
        /// <param name="encryptionEncodeMode"><see cref="CryptoBase.DefaultEncryptionEncodeMode"/></param>
        /// <param name="publicKey">Public key</param>
        /// <returns></returns>
        public string Encrypt(string data, EncodeMode encryptionEncodeMode, string publicKey)
        {
            if (string.IsNullOrWhiteSpace(data))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(data));
            }
            if (string.IsNullOrWhiteSpace(publicKey))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(publicKey));
            }

            return(encryptionEncodeMode.EncodeToString(Encrypt(DefaultEncoding.GetBytes(data), publicKey), DefaultEncoding));
        }
Esempio n. 13
0
        /// <summary>
        /// Sign with private key
        /// </summary>
        /// <param name="data"></param>
        /// <param name="signatureEncodeMode"><see cref="CryptoAndSignatureBase.DefaultSignatureEncodeMode"/></param>
        /// <param name="privateKey">Private key</param>
        /// <returns></returns>
        public string SignData(string data, EncodeMode signatureEncodeMode, string privateKey)
        {
            if (string.IsNullOrWhiteSpace(data))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(data));
            }
            if (string.IsNullOrWhiteSpace(privateKey))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(privateKey));
            }

            return(signatureEncodeMode.EncodeToString(SignData(DefaultEncoding.GetBytes(data), privateKey), DefaultEncoding));
        }
Esempio n. 14
0
 /// <summary>String preceeded by uint length</summary>
 /// <param name="message"></param>
 public void WriteUIntPascalString(string message)
 {
     if (message.Length > 0)
     {
         byte[] bytes = DefaultEncoding.GetBytes(message);
         WriteUInt(bytes.Length + 1);
         Write(bytes);
         Write((byte)0);
     }
     else
     {
         WriteUInt(0);
     }
 }
Esempio n. 15
0
 public OctetsStream Marshal(string str, Encoding encoding)
 {
     try
     {
         Marshal(encoding == null
             ? DefaultEncoding.GetBytes(str)
             : encoding.GetBytes(str));
     }
     catch
     {
         throw new MarshalException();
     }
     return(this);
 }
Esempio n. 16
0
        public override int GetHashCode()
        {
            unchecked
            {
                int hashCode = DataTypeId != null?DataTypeId.GetHashCode() : 0;

                hashCode = (hashCode * 397) ^ (Name != null ? Name.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (DefaultEncoding != null ? DefaultEncoding.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (BaseDataType != null ? BaseDataType.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ StructureType;
                hashCode = (hashCode * 397) ^ (Fields != null ? Fields.GetHashCode() : 0);
                return(hashCode);
            }
        }
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="data"></param>
        /// <param name="key">密钥</param>
        /// <returns></returns>
        public virtual string Encrypt(string data, string key)
        {
            if (string.IsNullOrWhiteSpace(data))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(data));
            }
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(key));
            }

            var bytes   = DefaultEncoding.GetBytes(data);
            var encrypt = Encrypt(bytes, key);

            return(DefaultEncryptionEncodeMode.EncodeToString(encrypt, DefaultEncoding));
        }
        public void KoreanTest()
        {
            byte[] bytes = new byte[] { 0x48, 0x6f, 0x6e, 0x67, 0x5e, 0x47, 0x69, 0x6c, 0x64, 0x6f, 0x6e, 0x67, 0x3d, 0x1b, 0x24, 0x29,
                                        0x43, 0xfb, 0xf3, 0x5e, 0x1b, 0x24, 0x29, 0x43, 0xd1, 0xce, 0xd4, 0xd7, 0x3d, 0x1b, 0x24, 0x29,
                                        0x43, 0xc8, 0xab, 0x5e, 0x1b, 0x24, 0x29, 0x43, 0xb1, 0xe6, 0xb5, 0xbf };
            string unicode = @"Hong^Gildong=洪^吉洞=홍^길동";

            // first test the default encoding
            DefaultEncoding encoding = new DefaultEncoding();

            string temp = encoding.GetString(bytes);

            Assert.AreEqual(temp, "Hong^Gildong=\x00d71b$)C\x00d7fb\x00d7f3^\x00d71b$)C\x00d7d1\x00d7ce\x00d7d4\x00d7d7=\x00d71b$)C\x00d7c8\x00d7ab^\x00d71b$)C\x00d7b1\x00d7e6\x00d7b5\x00d7bf", "Default decoding failed.");

            EncodeDecodeTest(@"\ISO 2022 IR 149", unicode, bytes);
        }
Esempio n. 19
0
        public int SetString(string key, string text, int maxLen)
        {
            byte[] bytes = DefaultEncoding.GetBytes(text);
            int    len   = Math.Min(bytes.Length, maxLen);

            foreach (int offset in ifsCurrentIniFileSection.GetIntList(key))
            {
                Array.Copy(bytes, 0, Data, BaseOffset + offset, len);

                for (int i = len; i < maxLen; i++)
                {
                    Data[BaseOffset + offset + i] = 0;
                }
            }

            return(len);
        }
        internal override void Read(MarkingBinaryReader reader)
        {
            Version           = reader.ReadUInt16();
            Flags             = reader.ReadUInt16();
            CompressionMethod = reader.ReadUInt16();
            LastModifiedTime  = reader.ReadUInt16();
            LastModifiedDate  = reader.ReadUInt16();
            Crc              = reader.ReadUInt32();
            CompressedSize   = reader.ReadUInt32();
            UncompressedSize = reader.ReadUInt32();
            ushort nameLength  = reader.ReadUInt16();
            ushort extraLength = reader.ReadUInt16();

            byte[] name = reader.ReadBytes(nameLength);
            Extra = reader.ReadBytes(extraLength);
            Name  = DefaultEncoding.GetString(name, 0, name.Length);
        }
Esempio n. 21
0
        /// <summary>
        /// Verification with public key
        /// </summary>
        /// <param name="data"></param>
        /// <param name="signature"></param>
        /// <param name="signatureEncodeMode"><see cref="CryptoAndSignatureBase.DefaultSignatureEncodeMode"/></param>
        /// <param name="publicKey">Public key</param>
        /// <returns></returns>
        public bool VerifyData(string data, string signature, EncodeMode signatureEncodeMode, string publicKey)
        {
            if (string.IsNullOrWhiteSpace(data))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(data));
            }
            if (string.IsNullOrWhiteSpace(signature))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(signature));
            }
            if (string.IsNullOrWhiteSpace(publicKey))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(publicKey));
            }

            return(VerifyData(DefaultEncoding.GetBytes(data), signatureEncodeMode.DecodeToBytes(signature, DefaultEncoding), publicKey));
        }
Esempio n. 22
0
            /// <summary>
            /// Gets the size of the table info.
            /// </summary>
            /// <returns>Size of the table info.</returns>
            public int GetInfoSize()
            {
                int size = 1;   // End node type

                foreach (ElementInfo info in this.files)
                {
                    size += 1;  // Node type
                    size += DefaultEncoding.GetByteCount(info.Name);
                }

                foreach (ElementInfo info in this.folders)
                {
                    size += 3;  // Node type + folder ID
                    size += DefaultEncoding.GetByteCount(info.Name);
                }

                return(size);
            }
Esempio n. 23
0
        public string GetString(string key, int maxLen)
        {
            int[] offsets = ifsCurrentIniFileSection.GetIntList(key);

            if (offsets.Length == 0)
            {
                return(null);
            }

            int length = GetByte(key + "Length");

            if (length == 0)
            {
                length = maxLen;
            }

            return(DefaultEncoding.GetString(Data, BaseOffset + offsets[0], length).TrimEnd('\0'));
        }
Esempio n. 24
0
        protected override void WriteMessageInternal(BinaryWriter writer)
        {
            base.WriteMessageInternal(writer);

            var topicData = Topic != null?DefaultEncoding.GetBytes(Topic) : new byte[]
            {
            };
            var contentTypeData = ContentType != null?DefaultEncoding.GetBytes(ContentType) : new byte[]
            {
            };

            WriteString(writer, ContentType);

            WriteString(writer, Topic);

            writer.Write((long)Data.Length);
            writer.Write(Data);
        }
Esempio n. 25
0
 public string Unmarshal_string(Encoding encoding)
 {
     try
     {
         int size = Uncompact_uint32();
         if (_pos + size > Size)
         {
             throw new MarshalException();
         }
         int cur = _pos;
         _pos += size;
         return((encoding == null) ?
                DefaultEncoding.GetString(Buffer(), cur, size) : encoding.GetString(Buffer(), cur, size));
     }
     catch
     {
         throw new MarshalException();
     }
 }
        internal static Decoder GetThreadStatic(this Decoder nonDefault)
        {
            if (nonDefault != null)
            {
                nonDefault.Reset();
                return(nonDefault);
            }

            var decoder = _perThreadDecoder;

            if (decoder == null)
            {
                _perThreadDecoder = decoder = DefaultEncoding.GetDecoder();
            }
            else
            {
                decoder.Reset();
            }
            return(decoder);
        }
        /// <summary>
        /// Tries to parse the given raw <paramref name="message" /> to the contract of the <see cref="T:Arcus.Messaging.Pumps.Abstractions.MessageHandling.IMessageHandler`2" />.
        /// </summary>
        /// <param name="message">The raw incoming message that will be tried to parse against the <see cref="T:Arcus.Messaging.Pumps.Abstractions.MessageHandling.IMessageHandler`2" />'s message contract.</param>
        /// <param name="messageType">The type of the message that the message handler can process.</param>
        /// <param name="result">The resulted parsed message when the <paramref name="message" /> conforms with the message handlers' contract.</param>
        /// <returns>
        ///     [true] if the <paramref name="message" /> conforms the <see cref="T:Arcus.Messaging.Pumps.Abstractions.MessageHandling.IMessageHandler`2" />'s contract; otherwise [false].
        /// </returns>
        public override bool TryDeserializeToMessageFormat(string message, Type messageType, out object result)
        {
            try
            {
                if (messageType == typeof(CloudEvent))
                {
                    CloudEvent cloudEvent = JsonEventFormatter.DecodeStructuredEvent(DefaultEncoding.GetBytes(message));

                    result = cloudEvent;
                    return(true);
                }
            }
            catch (Exception exception)
            {
                Logger.LogWarning(exception, "Unable to deserialize the CloudEvent");
            }

            result = null;
            return(false);
        }
Esempio n. 28
0
        private static byte[] GetContentByteArray(IEnumerable <KeyValuePair <string, string> > nameValues)
        {
            if (nameValues == null)
            {
                throw new ArgumentNullException("nameValues");
            }
            var stringBuilder = new StringBuilder();

            foreach (var current in nameValues)
            {
                if (stringBuilder.Length > 0)
                {
                    stringBuilder.Append('&');
                }
                stringBuilder.Append(Encode(current.Key));
                stringBuilder.Append('=');
                stringBuilder.Append(Encode(current.Value));
            }
            return(DefaultEncoding.GetBytes(stringBuilder.ToString()));
        }
        internal static Encoder GetThreadStatic(this Encoder nonDefault)
        {
            if (nonDefault != null)
            {
                nonDefault.Reset();
                return(nonDefault);
            }

            var encoder = _perThreadEncoder;

            if (encoder == null)
            {
                _perThreadEncoder = encoder = DefaultEncoding.GetEncoder();
            }
            else
            {
                encoder.Reset();
            }
            return(encoder);
        }
Esempio n. 30
0
        private string GetString(IEnumerable <byte> list)
        {
            var bytes = list.ToArray();

            var te = GetTransferEncoding();

            switch (te)
            {
            case System.Net.Mime.TransferEncoding.Base64:
                return(Convert.ToBase64String(bytes));

            case System.Net.Mime.TransferEncoding.QuotedPrintable:
            {
                var encoding = GetEncoding(this.ContentType.CharSet);
                return(encoding.GetString(bytes));
            }

            default:
                return(DefaultEncoding.GetString(bytes));
            }
        }