/// <summary> /// 同步对象和数据 /// </summary> /// <param name="fromDataToValue">是否将数据转换为值</param> protected override void SynchorizeData(bool fromDataToValue) { if (fromDataToValue) { if (_data == null || _data.Length == 0) { _value = string.Empty; } else { _value = TextEncoding.GetString(_data); } } else { if (string.IsNullOrEmpty(_value)) { _data = new byte[] { } } ; else { _data = TextEncoding.GetBytes(_value); } } }
protected override string ProcessDataBeforeSending(string data) { var input_bytes = TextEncoding.GetBytes(data); var output_bytes = Encryption.Encrypt(input_bytes); return(TextEncoding.GetString(output_bytes)); }
/// <summary> /// Sends a string message to the server. /// </summary> /// <param name="message"> /// A <see cref="System.String"/> /// </param> public void Send(string message) { message = message + "\r\n"; byte[] buffer = TextEncoding.GetBytes(message); stream.BeginWrite(buffer, 0, buffer.Length, onSend, null); Console.Write("Outgoing: {0}", message); }
internal void WriteChars(char[] chars, int offset, int len) { var charCount = len == 0 ? chars.Length : len; Debug.Assert(TextEncoding.GetByteCount(chars, 0, charCount) <= WriteSpaceLeft); WritePosition += TextEncoding.GetBytes(chars, offset, charCount, Buffer, WritePosition); }
public NpgsqlBuffer WriteCharArray(char[] s, int byteLen) { Contract.Assume(TextEncoding == Encoding.UTF8, "WriteString assumes UTF8-encoding"); int charPos = 0; for (; ;) { if (byteLen <= WriteSpaceLeft) { _writePosition += TextEncoding.GetBytes(s, charPos, s.Length - charPos, _buf, _writePosition); return(this); } int numCharsCanBeWritten = Math.Max(WriteSpaceLeft / 3, WriteSpaceLeft - (byteLen - (s.Length - charPos))); if (numCharsCanBeWritten >= 20) // Don't do this if the buffer is almost full { char lastChar = s[charPos + numCharsCanBeWritten - 1]; if (lastChar >= 0xD800 && lastChar <= 0xDBFF) { --numCharsCanBeWritten; // Don't use high/lead surrogate pair as last char in block } int wrote = TextEncoding.GetBytes(s, charPos, numCharsCanBeWritten, _buf, _writePosition); _writePosition += wrote; byteLen -= wrote; charPos += numCharsCanBeWritten; } else { Underlying.Write(_buf, 0, _writePosition); _writePosition = 0; } } }
public override void Serialize(Array item, Stream target) { var buffer = BinarySerializerService.SingletonBitConverter.GetBytes(item.Length); target.Write(buffer, 0, buffer.Length); foreach (var element in item) { if (null == element) { target.WriteByte(0x00); continue; } var type = element.GetType(); var name = type.AssemblyQualifiedName; if (null == name) { target.WriteByte(0x00); continue; } target.WriteByte(0x01); Trace.WriteLine(string.Format("Writing element at {0}", target.Position)); var textBuffer = TextEncoding.GetBytes(name); buffer = BinarySerializerService.SingletonBitConverter.GetBytes(textBuffer.Length); target.Write(buffer, 0, buffer.Length); target.Write(textBuffer, 0, textBuffer.Length); var serializer = BinarySerializerService.GetSerializer(type); serializer.Serialize(element, target); } }
public Blob(string sdata) { var data = TextEncoding.GetBytes(sdata); _current = new Region(data, data.Length, 0); _alen = 0; _list = new List <Region> (); _list.Add(_current); }
public static void WriteUInt32LengthPrefixedString(BinaryWriter writer, string value) { if (value == null) { WriteUInt32LengthPrefixedString(writer, String.Empty); return; } writer.Write((uint)value.Length); writer.Write(TextEncoding.GetBytes(value)); }
private void WritePendingMessages(object state) { try { // Send pending messages in queue until flood preventer indicates to stop. long sendDelay = 0; while (this.messageSendQueue.Count > 0) { Debug.Assert(this.messageSendQueue.Count < 100); // Check that flood preventer currently permits sending of messages. if (FloodPreventer != null) { sendDelay = FloodPreventer.GetSendDelay(); if (sendDelay > 0) { break; } } // Send next message in queue. var message = this.messageSendQueue.Dequeue(); var line = message.Item1; var token = message.Item2; var lineBuffer = TextEncoding.GetBytes(line); SendAsync(lineBuffer, token); // Tell flood preventer mechanism that message has just been sent. if (FloodPreventer != null) { FloodPreventer.HandleMessageSent(); } } // Make timer fire when next message in send queue should be written. this.sendTimer.Change(Math.Max(sendDelay, minimumSendWaitTime), Timeout.Infinite); } catch (SocketException exSocket) { HandleSocketError(exSocket); } catch (ObjectDisposedException) { // Ignore. } #if !DEBUG catch (Exception ex) { OnError(new IrcErrorEventArgs(ex)); } #endif finally { } }
public override void Serialize(string item, Stream target) { if (null == item) { return; } var bytes = TextEncoding.GetBytes(item); var len = bytes.Length; target.Write(BinarySerializerService.SingletonBitConverter.GetBytes(len), 0, sizeof(int)); target.Write(bytes, 0, bytes.Length); }
protected override string ProcessDataBeforeReceiving(string data) { var data_bytes = TextEncoding.GetBytes(data); if (!Encryption.StateReady) { Encryption.Decrypt(data_bytes, 16); Encryption.Encrypt(data_bytes.Skip(16).ToArray(), 16); Encryption.StateReady = true; return(null); } return(TextEncoding.GetString(Encryption.Decrypt(data_bytes))); }
public static byte[] GetProtocolUpgradeResponse(string ClientWebsocketKey) { return(TextEncoding.GetBytes("HTTP/1.1 101 Switching Protocols" + Environment.NewLine + "Connection: Upgrade" + Environment.NewLine + "Upgrade: websocket" + Environment.NewLine + "Sec-WebSocket-Accept: " + Convert.ToBase64String( SHA1.Create().ComputeHash( TextEncoding.GetBytes( ClientWebsocketKey + HandshakeKey ) ) ) + Environment.NewLine + Environment.NewLine)); }
public static void WriteAsciiString(Stream output, string value) { if (output == null) { throw new ArgumentNullException("output"); } if (value == null) { throw new ArgumentNullException("value"); } byte[] data = TextEncoding.GetBytes(value); output.Write(data, 0, data.Length); }
public static void WriteUInt16LengthPrefixedString(BinaryWriter writer, string value) { if (value == null) { WriteUInt16LengthPrefixedString(writer, String.Empty); return; } if (value.Length > ushort.MaxValue) { throw new ArgumentOutOfRangeException("value has more than 65,535 chars."); } writer.Write((ushort)value.Length); writer.Write(TextEncoding.GetBytes(value)); }
/// <summary> /// Encrypts a string using the Rijndael crypto algorithm. /// </summary> /// <param name="toEncrypt">The specified string to be encrypted.</param> /// <param name="secretKey">The secret key byte array to be used when encrypting the string.</param> ///<param name="keySize">The key size.</param> ///<param name="blockSize">The block size.</param> /// <returns>A Base64 encrypted string.</returns> public string Encrypt(string toEncrypt, out byte[] secretKey, int?keySize, int?blockSize) { var bytesToEncrypt = TextEncoding.GetBytes(toEncrypt); var rijn = Create(keySize, blockSize); using (var ms = new MemoryStream()) { var initializationVector = EncryptorEncoding.GetBytes(InitializationVectorString); secretKey = EncryptorEncoding.GetBytes(SecretKeyString); using (var cs = new CryptoStream(ms, rijn.CreateEncryptor(secretKey, initializationVector), CryptoStreamMode.Write)) { cs.Write(bytesToEncrypt, 0, bytesToEncrypt.Length); } return(Convert.ToBase64String(ms.ToArray())); } }
public static void WriteFixedString(Stream output, string value, int fixedSize) { if (output == null) { throw new ArgumentNullException("output"); } if (value == null) { throw new ArgumentNullException("value"); } if (value.Length > fixedSize) { throw new ArgumentOutOfRangeException("value is greater than fixed size."); } byte[] data = new byte[fixedSize]; // Initalised to all '\0'. TextEncoding.GetBytes(value, 0, value.Length, data, 0); output.Write(data, 0, data.Length); }
public override Stream openStream() { //This is a bit hacky, but since the StreamReader defaults to utf-8 we don't actually have to include //the preamble in those strings. This fixes problems with other libraries (like libRocket) that cannot //deal with the preamble, but expect UTF-8. if (TextEncoding == Encoding.UTF8) { return(new MemoryStream(TextEncoding.GetBytes(CachedString))); } else { byte[] preamble = TextEncoding.GetPreamble(); byte[] data = TextEncoding.GetBytes(CachedString); MemoryStream ms = new MemoryStream(preamble.Length + data.Length); ms.Write(preamble, 0, preamble.Length); ms.Write(data, 0, data.Length); ms.Seek(0, SeekOrigin.Begin); return(ms); } }
/// <summary> /// Creates a verification code with the given username, password, and session key. /// </summary> /// <returns>The verification code.</returns> private string CreateVerificationCode() { byte[] input, output; input = TextEncoding.GetBytes(m_username + m_sessionKey.ToString("x8") + m_password); using (MD5 md5 = MD5.Create()) { output = md5.ComputeHash(input); Debug.Assert(output != null && output.Length > 0); } StringBuilder builder = new StringBuilder(32); foreach (byte b in output) { builder.Append(b.ToString("x2")); } return(builder.ToString()); }
public bool SaveRecord() { if ((_Position + 1) < RecordCount) // if not appending { foreach (ColumnInfo item in Columns) { if (GetString(item).Length > (Const.MemoBlockLen - Const.MemoBlockTermLen)) { // if the memo string to be stored inside an existing record cannot fit inside one existing block: // bail out instead of appending to the dbt file, as this leaves dead blocks inside it. // -> Clear() and rewrite entire file instead. return(false); } } } StreamSeek(_Stream, HeaderLength + _Position * RecordLength); byte[] bytes = TextEncoding.GetBytes(_RecordBuf); StreamWrite(_Stream, bytes); IsDirty = true; return(true); }
private byte[] decryptAesCbcPkcs7(byte[] encrypted, byte[] key, byte[] iv) { var aes = Aes.Create(); aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; var decryptor = aes.CreateDecryptor(key, iv); string plaintext; using (MemoryStream msDecrypt = new MemoryStream(encrypted)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { plaintext = srDecrypt.ReadToEnd(); } } } return(TextEncoding.GetBytes(plaintext)); }
public string Encrypt(string plaintext, string password, Schema schemaVersion) { this.configureSettings(schemaVersion); byte[] plaintextBytes = TextEncoding.GetBytes(plaintext); PayloadComponents components = new PayloadComponents(); components.schema = new byte[] { (byte)schemaVersion }; components.options = new byte[] { (byte)this.options }; components.salt = this.generateRandomBytes(Cryptor.saltLength); components.hmacSalt = this.generateRandomBytes(Cryptor.saltLength); components.iv = this.generateRandomBytes(Cryptor.ivLength); byte[] key = this.generateKey(components.salt, password); switch (this.aesMode) { case AesMode.CTR: components.ciphertext = this.encryptAesCtrLittleEndianNoPadding(plaintextBytes, key, components.iv); break; case AesMode.CBC: components.ciphertext = this.encryptAesCbcPkcs7(plaintextBytes, key, components.iv); break; } components.hmac = this.generateHmac(components, password); List <byte> binaryBytes = new List <byte>(); binaryBytes.AddRange(this.assembleHeader(components)); binaryBytes.AddRange(components.ciphertext); binaryBytes.AddRange(components.hmac); return(Convert.ToBase64String(binaryBytes.ToArray())); }
/// <summary> /// Send message text to specific clients in asynchronous mode with default encoding, see TextEncoding property. /// </summary> /// <param name="clientIDCollection">The clients' id collection to receive messsage.</param> /// <param name="text">The message text to be sent.</param> /// <param name="callback">The callback that will be called after sending operation.</param> /// <returns>An System.IAsyncResult collection that references the asynchronous send.</returns> public IEnumerable <IAsyncResult> SendTextAsync(IEnumerable <long> clientIDCollection, string text, AsyncCallback callback) { return(SendMessageAsync(clientIDCollection, TextEncoding.GetBytes(text), callback)); }
/// <summary> /// Send message text to specific client in asynchronous mode with default encoding, see TextEncoding property. /// </summary> /// <param name="clientID">The id of the client to receive messsage.</param> /// <param name="text">The message text to be sent.</param> /// <param name="callback">The callback that will be called after sending operation.</param> /// <returns>An System.IAsyncResult that references the asynchronous send.</returns> public IAsyncResult SendTextAsync(long clientID, string text, AsyncCallback callback) { return(SendMessageAsync(clientID, TextEncoding.GetBytes(text), callback)); }
/// <summary> /// Send message text to specific client in synchronous mode with default encoding, see TextEncoding property. /// </summary> /// <param name="clientID">The client id to send messsage.</param> /// <param name="text">The message text to be sent.</param> /// <returns>The number of bytes sent to the server.</returns> public void SendText(long clientID, string text) { SendMessage(clientID, TextEncoding.GetBytes(text)); }
internal void WriteCharsSimple(char[] chars, int len = 0) { Contract.Requires(TextEncoding.GetByteCount(chars) <= WriteSpaceLeft); WritePosition += TextEncoding.GetBytes(chars, 0, len == 0 ? chars.Length : len, _buf, WritePosition); }
internal void WriteStringSimple(string s, int len = 0) { Contract.Requires(TextEncoding.GetByteCount(s) <= WriteSpaceLeft); WritePosition += TextEncoding.GetBytes(s, 0, len == 0 ? s.Length : len, _buf, WritePosition); }
public void WriteString(string s, int len = 0) { Debug.Assert(TextEncoding.GetByteCount(s) <= WriteSpaceLeft); WritePosition += TextEncoding.GetBytes(s, 0, len == 0 ? s.Length : len, Buffer, WritePosition); }
/// <summary> /// Send message text to specific group collection in asynchronous mode with default encoding, see TextEncoding property. /// </summary> /// <param name="groupNameCollection">The group collection to receive the message.</param> /// <param name="text">The message text to be sent.</param> public void SendGroupTextAsync(IEnumerable <string> groupNameCollection, string text) { SendGroupMessageAsync(groupNameCollection, TextEncoding.GetBytes(text)); }
/// <summary> /// Send message text to all clients in asynchronous mode. /// </summary> /// <param name="text">The message text to be sent.</param> /// <param name="callback">The callback that will be called after sending operation.</param> /// <returns>An System.IAsyncResult collection that references the asynchronous send.</returns> public IEnumerable <IAsyncResult> BroadcastText(string text, AsyncCallback callback) { return(BroadcastMessage(TextEncoding.GetBytes(text), callback)); }
/// <summary> /// Encodes the body of a <c>HeartbeatMessage</c> object into the target byte array. /// </summary> /// <param name="target">the target byte array.</param> /// <param name="offset">the position to start writing.</param> /// <returns>The number of bytes written into <c>bytes</c>.</returns> protected override int GetBodyBytes(byte[] target, int offset) { string body = m_username; return(TextEncoding.GetBytes(body, 0, body.Length, target, offset)); }