Esempio n. 1
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. 2
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. 3
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. 4
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());
        }
Esempio n. 5
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. 6
0
 //------------------------------------------------------------------------------------------------------------------
 public static byte[] StringToBuffer(ref string Str)
 {
     if (Str == null || Str == "")
     {
         return(new byte[0]);
     }
     else
     {
         return(DefaultEncoding.GetBytes(Str));
     }
 }
        /// <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));
        }
        /// <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. 9
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. 10
0
 public OctetsStream Marshal(string str, Encoding encoding)
 {
     try
     {
         Marshal(encoding == null
             ? DefaultEncoding.GetBytes(str)
             : encoding.GetBytes(str));
     }
     catch
     {
         throw new MarshalException();
     }
     return(this);
 }
        /// <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));
        }
Esempio n. 12
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);
        }
Esempio n. 13
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. 14
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. 15
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()));
        }
        /// <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);
        }
        internal override void Write(BinaryWriter writer)
        {
            writer.Write(Version);
            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(Extra == null ? (ushort)0 : (ushort)Extra.Length);
            if (Extra != null)
            {
                writer.Write(Extra);
            }
            writer.Write(nameBytes);
        }
        protected virtual SymmetricAlgorithm CreateSymmetricAlgorithm(string key)
        {
            SymmetricAlgorithm algorithm = CreateSymmetricAlgorithm();

            BeforeSetSymmetricAlgorithm?.Invoke(this, new EventArgs <SymmetricAlgorithm>(algorithm));

            #region Key
            var bytesFromKey = DefaultEncoding.GetBytes(DefaultKeyEncodeMode.DecodeToString(key, DefaultEncoding));
            if (bytesFromKey.Length >= algorithm.KeySize / 8)
            {
                algorithm.Key = bytesFromKey;
            }
            else
            {
                var keyBytes = new byte[algorithm.KeySize / 8];
                Array.Copy(bytesFromKey, 0, keyBytes, 0, Math.Min(keyBytes.Length, bytesFromKey.Length));
                algorithm.Key = keyBytes;
            }
            #endregion

            #region IV
            // ECB模式不需要设置IV
            if (algorithm.Mode != CipherMode.ECB)
            {
                if (IV != null)
                {
                    algorithm.IV = IV;
                }
                else
                {
                    var ivBytes = new byte[algorithm.BlockSize / 8];
                    Array.Copy(algorithm.Key, 0, ivBytes, 0, Math.Min(ivBytes.Length, algorithm.Key.Length));
                    algorithm.IV = ivBytes;
                }
            }
            #endregion

            AfterSetSymmetricAlgorithm?.Invoke(this, new EventArgs <SymmetricAlgorithm>(algorithm));
            return(algorithm);
        }
Esempio n. 19
0
            public void Write(DataStream str, long baseOffset)
            {
                DataWriter bw = new DataWriter(str);

                // Go to offset if we can. Maybe we are writing in a position
                // that it doesn't exist still (it will write written later)
                // so in this case we fill it with zeros
                long tableOffset = baseOffset + this.Offset;

                if (tableOffset > str.Length)
                {
                    str.WriteTimes(0, tableOffset - str.Length);
                }

                // And finally seek there
                str.Seek(baseOffset + this.Offset, SeekMode.Origin);

                byte nodeType;

                // Write file info
                foreach (ElementInfo info in this.Files)
                {
                    nodeType = (byte)DefaultEncoding.GetByteCount(info.Name);                     // Name length
                    bw.Write(nodeType);
                    bw.Write(DefaultEncoding.GetBytes(info.Name));
                }

                // Write folder info
                foreach (ElementInfo info in this.Folders)
                {
                    nodeType = (byte)(0x80 | DefaultEncoding.GetByteCount(info.Name));
                    bw.Write(nodeType);
                    bw.Write(DefaultEncoding.GetBytes(info.Name));
                    bw.Write(info.Id);
                }

                bw.Write((byte)0x00);                   // End of info
                bw = null;
            }
Esempio n. 20
0
        private byte[] ParseHeaders(byte[] data)
        {
            var crlf = DefaultEncoding.GetBytes(CRLF);

            var endOfHeader   = false;
            var currentHeader = "";
            int index         = 0;

            while (index < data.Length && !endOfHeader)
            {
                int lineBreakIndex = BytesExtensions.IndexOf(data, crlf, index);
                var breakFound     = (lineBreakIndex != -1);
                if (!breakFound)
                {
                    lineBreakIndex = data.Length;
                }

                int subStringLength = lineBreakIndex - index;

                var headerLineBytes = new byte[subStringLength];
                Array.Copy(data, index, headerLineBytes, 0, subStringLength);

                var line = DefaultEncoding.GetString(headerLineBytes);
                processHeaderLine(ref currentHeader, line, ref endOfHeader);
                index = lineBreakIndex;
                if (breakFound)
                {
                    index += crlf.Length;
                }
            }

            this._headerBytes = new byte[index];
            Array.Copy(data, this._headerBytes, index);
            processCommonHeaderAttribs();
            return(getUnprocessedData(data, index));
        }
        public void DefaultEncodingTest()
        {
            // from PS 3.5-2009, Page 107
            // H.3.2 Example 2: Value 1 of Attribute Specific Character Set (0008,0005) is ISO 2022 IR 13.

            byte[] bytes = new byte[] { 0xd4, 0xcf, 0xc0, 0xde, 0x5e, 0xc0, 0xdb, 0xb3, 0x3d, 0x1b, 0x24, 0x42, 0x3b, 0x33, 0x45, 0x44,
                                        0x1b, 0x28, 0x4a, 0x5e, 0x1b, 0x24, 0x42, 0x42, 0x40, 0x4f, 0x3a, 0x1b, 0x28, 0x4a, 0x3d, 0x1b,
                                        0x24, 0x42, 0x24, 0x64, 0x24, 0x5e, 0x24, 0x40, 0x1b, 0x28, 0x4a, 0x5e, 0x1b, 0x24, 0x42, 0x24,
                                        0x3f, 0x24, 0x6d, 0x24, 0x26, 0x1b, 0x28, 0x4a };

            DefaultEncoding encoding = new DefaultEncoding();

            string text = "\x00d7d4\x00d7cf\x00d7c0\x00d7de^\x00d7c0\x00d7db\x00d7b3=\x00d71b$B;3ED\x00d71b(J^\x00d71b$BB@O:\x00d71b(J=\x00d71b$B$d$^$@\x00d71b(J^\x00d71b$B$?$m$&\x00d71b(J";

            string decode = encoding.GetString(bytes);

            Assert.AreEqual(decode, text);

            byte[] temp = encoding.GetBytes(text.ToCharArray());

            string second = encoding.GetString(temp);

            Assert.AreEqual(second, text);
        }
Esempio n. 22
0
 private bool readLine(byte[] data, ref int index, out byte[] stringBytes)
 {
     if (index >= data.Length)
     {
         stringBytes = null;
         return(false);
     }
     else
     {
         var crlf      = DefaultEncoding.GetBytes(CRLF);
         var crlfIndex = BytesExtensions.IndexOf(data, crlf, index);
         if (crlfIndex == -1)
         {
             stringBytes = data.GetSubArrayStartingAt(index);
             index       = data.Length;
         }
         else
         {
             stringBytes = data.GetSubArray(index, crlfIndex - index);
             index       = crlfIndex + crlf.Length;
         }
         return(true);
     }
 }
Esempio n. 23
0
 public override void WriteBytes(string obj, Stream stream)
 {
     byte[] bytes = DefaultEncoding.GetBytes(obj);
     stream.WriteInt32(bytes.Length);
     stream.WriteBytes(bytes);
 }
 /// <summary>
 /// 使用指定的哈希算法来计算哈希值
 /// </summary>
 /// <param name="data"></param>
 /// <param name="hashAlgorithm"></param>
 /// <returns></returns>
 public string ComputeHash(string data, HashAlgorithm hashAlgorithm)
 {
     return(ComputeHash(DefaultEncoding.GetBytes(data), hashAlgorithm));
 }
Esempio n. 25
0
        public static byte[] ObjectToByteArray <T>(this T data)
        {
            var json = JsonConvert.SerializeObject(data);

            return(DefaultEncoding.GetBytes(json));
        }
Esempio n. 26
0
        /// <summary>
        /// 创建Post方式的HTTP请求
        /// 可接受IDictionary&lt;string,object&gt;,IEnumerable&lt;keyvaluePair&lt;string,object&gt;&gt;,
        /// IEnumerable&lt;object&gt;,string(a=a1&amp;b=b1),object等类型参数
        /// </summary>
        /// <param name="url">请求url</param>
        /// <param name="requestParams">请求参数</param>
        /// <param name="contentType">请求内容类型</param>
        /// <returns></returns>
        public HttpWebResponse CreatePostHttpResponse(string url, object requestParams = null, HttpContentType contentType = HttpContentType.Json)
        {
            if (!url.ToLower().StartsWith("http") && !string.IsNullOrEmpty(BaseUrl))
            {
                url = BaseUrl + url;
            }
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {   //如果是发送HTTPS请求
                request.ProtocolVersion = HttpVersion.Version10;
                request.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }
            request.Method = "POST";
            if (contentType == HttpContentType.Json)
            {
                request.Accept      = "application/json";
                request.ContentType = "application/json;charset=utf-8;";
            }
            else if (contentType == HttpContentType.Form)
            {
                request.ContentType = "application/x-www-form-urlencoded";
            }

            request.UserAgent = UserAgent;

            if (Headers != null && Headers.Count > 0)
            {
                foreach (string key in Headers.AllKeys)
                {
                    request.Headers.Add(key, Headers[key]);
                }
            }
            request.Timeout          = Timeout;
            request.ReadWriteTimeout = Timeout;
            request.CookieContainer  = new CookieContainer();
            request.CookieContainer.Add(Cookies);

            //如果需要Post数据
            if (requestParams != null)
            {
                string paramStr = null;
                if (contentType == HttpContentType.Json)
                {
                    paramStr = JsonHelper.SerializeObject(requestParams);
                }
                else
                {
                    paramStr = GetParameterString(requestParams);
                }
                if (!string.IsNullOrEmpty(paramStr))
                {
                    byte[] data = DefaultEncoding.GetBytes(paramStr);
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }
            }
            return(request.GetResponse() as HttpWebResponse);
        }
        public void Write(string text)
        {
            var buf = DefaultEncoding.GetBytes(text);

            Write(buf, 0, buf.Length);
        }