internal SmppQuerySmReq(ByteBuilder bb) { int startPosition = 0x10; _Header = new SmppHeader(bb); _Body = new BodyPdu(bb, ref startPosition); }
public override void WriteOffsets(ByteBuilder bb) { foreach (ExportRef exp in Exports) { exp?.WriteOffset(bb); } }
private void buttonUpdateTable_Click(object sender, EventArgs e) { m_aChannel = new byte[this.listViewEx1.Items.Count]; for (int i = 0; i < this.listViewEx1.Items.Count; i++) { try { m_aChannel[i] = byte.Parse(this.listViewEx1.Items[i].SubItems[1].Text); } catch { } } ByteBuilder bb = new ByteBuilder(); bb.Clear(); bb.Append((byte)this.GetChannelTable().Length); bb.Append(this.GetChannelTable()); if (!RcpProtocol.Instance.SendBytePkt(RcpProtocol.Instance.BuildCmdPacketByte(RcpProtocol.RCP_MSG_CMD, RcpProtocol.RCP_CMD_SET_HOPPING_TBL, bb.GetByteArray()))) { } bb.Clear(); }
/// <summary> /// Computes the 16-bit checksum of the specified IPv4 packet. /// </summary> /// <param name="packet">The packet to compute the checksum for.</param> /// <param name="withChecksumField">true to include the packet's /// checksum field in the calculation; otherwise false.</param> /// <returns>The checksum of the specified IPv4 packet.</returns> /// <exception cref="ArgumentNullException">Thrown if the packet /// argument is null.</exception> public static ushort ComputeChecksum(IpPacket packet, bool withChecksumField = false) { packet.ThrowIfNull("packet"); // The version and IHL fields are 4 bit wide each. var vi = (byte)(((packet.Ihl & 0x0F) << 4) | (((int)packet.Version) & 0x0F)); // The flags field is 3 bits and the fragment offset 13 bits wide. var ffo = (ushort)(((packet.FragmentOffset & 0x1FFF) << 3) | ((int)packet.Flags & 0x07)); var bytes = new ByteBuilder() .Append(vi) .Append(packet.Dscp) .Append(packet.TotalLength) .Append(packet.Identification) .Append(ffo) .Append(packet.TimeToLive) .Append((byte)packet.Protocol) .Append(withChecksumField ? packet.Checksum : (ushort)0) .Append(packet.Source.Bytes) .Append(packet.Destination.Bytes) .ToArray(); var sum = 0; // Treat the header bytes as a sequence of unsigned 16-bit values and // sum them up. for (var n = 0; n < bytes.Length; n += 2) { sum += BitConverter.ToUInt16(bytes, n); } // Use carries to compute the 1's complement sum. sum = (sum >> 16) + (sum & 0xFFFF); // Return the inverted 16-bit result. return((ushort)(~sum)); }
public void WriteOffset(int rel, ByteBuilder bb) { IsOffsetWrited = true; if (Reference != null) { TargetOffset = Reference.Address; } int val = TargetOffset; if (Relative) { val -= rel; } switch (Size) { case 1: bb.SetByte(Address, (byte)val); break; case 2: bb.SetShortBE(Address, (ushort)val); break; default: throw new NotImplementedException(); } }
/// <summary> /// Waits until the connected client sends a SOCKS5 request. /// </summary> /// <returns>The SOCKS5 request sent by the client.</returns> /// <exception cref="Socks5Exception">The data sent by the client /// is not a valid SOCKS5 request.</exception> private SocksRequest WaitForRequest() { ByteBuilder b = new ByteBuilder(); using (var r = new BinaryReader(stream, Encoding.UTF8, true)) { byte[] bytes = r.ReadBytes(4); b.Append(bytes); ATyp atyp = (ATyp)bytes[3]; switch (atyp) { case ATyp.IPv4: case ATyp.IPv6: b.Append(r.ReadBytes(atyp == ATyp.IPv4 ? 4 : 16)); break; case ATyp.Domain: byte length = r.ReadByte(); b.Append(length).Append(r.ReadBytes(length)); break; } b.Append(r.ReadBytes(2)); } try { return(SocksRequest.Deserialize(b.ToArray())); } catch (Exception e) { throw new Socks5Exception("The request could not be serialized.", e); } }
/*登录 */ public void LogIn() { if (isInLogIn || isInRegister) { return; //若已点击了登陆按钮或注册按钮则不响应 } StopCoroutine("ResetPrompt"); promptText.text = ""; userNameInput.interactable = false; passwordInput.interactable = false; isInLogIn = true; //test // LogInSuccess(); ByteBuilder builder = new ByteBuilder(); builder.Add(System.BitConverter.GetBytes(Network.LOGIN)); builder.Add(System.BitConverter.GetBytes(userNameInput.text.Length)); builder.Add(System.BitConverter.GetBytes(passwordInput.text.Length)); builder.Add(System.Text.Encoding.ASCII.GetBytes(userNameInput.text)); builder.Add(System.Text.Encoding.ASCII.GetBytes(passwordInput.text)); Global.network.Send(builder.GetByes()); // Debug.Log("Set"); LogInOutCor = StartCoroutine(LogInTimeout()); }
/// <summary> /// Computes the server evidence from the given parameters. /// </summary> /// <param name="clientPublicKey">The client's ephemeral public key.</param> /// <param name="clientProof"></param> /// <param name="sharedKey">The shared context key.</param> /// <param name="authId">The authorization identity.</param> /// <param name="options">The raw options string as sent by the /// client.</param> /// <param name="sid">The session id sent by the server.</param> /// <param name="ttl">The time-to-live value for the session id sent /// by the server.</param> /// <param name="hashAlgorithm">The message digest algorithm to use for /// calculating the server proof.</param> /// <returns>The server proof as an array of bytes.</returns> public static byte[] ComputeServerProof(Mpi clientPublicKey, byte[] clientProof, Mpi sharedKey, string authId, string options, string sid, uint ttl, HashAlgorithm hashAlgorithm) { byte[] A = clientPublicKey.ToBytes(), M1 = clientProof, K = sharedKey.ToBytes(), I = Encoding.UTF8.GetBytes(authId), o = Encoding.UTF8.GetBytes(options), _sid = Encoding.UTF8.GetBytes(sid); HashAlgorithm H = hashAlgorithm; // The proof is calculated as follows: // // H( bytes(A) // | bytes(M1) // | bytes(K) // | bytes(H( bytes(I) )) // | bytes(H( bytes(o) )) // | bytes(sid) // | ttl // ) byte[] seq = new ByteBuilder() .Append(A) .Append(M1) .Append(K) .Append(H.ComputeHash(I)) .Append(H.ComputeHash(o)) .Append(_sid) .Append(ttl, true) .ToArray(); return(H.ComputeHash(seq)); }
/// <summary> /// Computes the client evidence from the given parameters. /// </summary> /// <param name="safePrimeModulus">The safe prime modulus sent by the /// server.</param> /// <param name="generator">The generator sent by the server.</param> /// <param name="username">The username to authenticate with.</param> /// <param name="salt">The client's password salt.</param> /// <param name="clientPublicKey">The client's ephemeral public key.</param> /// <param name="serverPublicKey">The server's ephemeral public key.</param> /// <param name="sharedKey">The shared context key.</param> /// <param name="authId">The authorization identity.</param> /// <param name="options">The raw options string as received from the /// server.</param> /// <param name="hashAlgorithm">The message digest algorithm to use for /// calculating the client proof.</param> /// <returns>The client proof as an array of bytes.</returns> public static byte[] ComputeClientProof(Mpi safePrimeModulus, Mpi generator, string username, byte[] salt, Mpi clientPublicKey, Mpi serverPublicKey, Mpi sharedKey, string authId, string options, HashAlgorithm hashAlgorithm) { byte[] N = safePrimeModulus.ToBytes(), g = generator.ToBytes(), U = Encoding.UTF8.GetBytes(username), s = salt, A = clientPublicKey.ToBytes(), B = serverPublicKey.ToBytes(), K = sharedKey.ToBytes(), I = Encoding.UTF8.GetBytes(authId), L = Encoding.UTF8.GetBytes(options); HashAlgorithm H = hashAlgorithm; // The proof is calculated as follows: // // H( bytes(H( bytes(N) )) ^ bytes( H( bytes(g) )) // | bytes(H( bytes(U) )) // | bytes(s) // | bytes(A) // | bytes(B) // | bytes(K) // | bytes(H( bytes(I) )) // | bytes(H( bytes(L) )) // ) byte[] seq = new ByteBuilder() .Append(Xor(H.ComputeHash(N), H.ComputeHash(g))) .Append(H.ComputeHash(U)) .Append(s) .Append(A) .Append(B) .Append(K) .Append(H.ComputeHash(I)) .Append(H.ComputeHash(L)) .ToArray(); return(H.ComputeHash(seq)); }
private static void ReadMessage(ClientInfo ci, uint code, byte[] buf, int len) { Console.WriteLine("Message, code " + code.ToString("X8") + ", content:"); byte[] ba = new byte[len]; Array.Copy(buf, ba, len); Console.WriteLine(" " + ByteBuilder.FormatParameter(new Parameter(ba, ParameterType.Byte))); }
public override void Write(ByteBuilder bb) { Address = (ushort)bb.Position; bb.AddByte(Type); foreach (object arg in Arguments) { switch (arg) { case byte b: bb.AddByte(b); break; case ushort s: bb.AddShortBE(s); break; case RefToElement r: r.Write(bb); break; case LinkToExport l: l.Write(bb); break; default: throw new NotImplementedException(); } } }
/// <summary> /// 转换为ByteRange /// </summary> /// <exception cref="ProtocolException"></exception> /// <returns></returns> public ByteRange ToByteRange() { var apiNameBytes = Encoding.UTF8.GetBytes(this.ApiName); var headLength = apiNameBytes.Length + 15; this.TotalBytes = this.Body == null ? headLength : headLength + this.Body.Length; const int packegMaxSize = 10 * 1204 * 1024; // 10M if (this.TotalBytes > packegMaxSize) { throw new ProtocolException("数据包太大"); } this.ApiNameLength = (byte)apiNameBytes.Length; var builder = new ByteBuilder(Endians.Big); builder.Add(this.TotalBytes); builder.Add(this.ApiNameLength); builder.Add(apiNameBytes); builder.Add(this.Id); builder.Add(this.IsFromClient); builder.Add(this.IsException); builder.Add(this.Body); return(builder.ToByteRange()); }
internal BodyPdu(ByteBuilder bb, ref int StartPosition) { _ServiceType = SmppServiceType.Default; _SourceAddress = string.Empty; _DestinationAddress = string.Empty; _EsmClass = new BitBuilder(); _RegisteredDelivery = new BitBuilder(); _ShortMessage = new SmppString(); _ServiceType = SmppServiceType.FromValue( SmppDataCoding.BaseEncoding.GetString(bb.ReadBytesUntil(ref StartPosition, 0))); _SourceAddressTon = bb.ReadByte(ref StartPosition); _SourceAddressNpi = bb.ReadByte(ref StartPosition); _SourceAddress = SmppDataCoding.BaseEncoding.GetString(bb.ReadBytesUntil(ref StartPosition, 0)); _DestinationAddressTon = bb.ReadByte(ref StartPosition); _DestinationAddressNpi = bb.ReadByte(ref StartPosition); _DestinationAddress = SmppDataCoding.BaseEncoding.GetString(bb.ReadBytesUntil(ref StartPosition, 0)); _EsmClass.Value = bb.ReadByte(ref StartPosition); _ProtocolId = bb.ReadByte(ref StartPosition); _PriorityFlag = bb.ReadByte(ref StartPosition); _ScheduleDeliveryTime = new SmppDateTime(SmppDataCoding.BaseEncoding.GetString(bb.ReadBytesUntil(ref StartPosition, 0))); _ValidityPeriod = new SmppDateTime(SmppDataCoding.BaseEncoding.GetString(bb.ReadBytesUntil(ref StartPosition, 0))); _RegisteredDelivery.Value = bb.ReadByte(ref StartPosition); _ReplaceIfPresent = bb.ReadByte(ref StartPosition); _ShortMessage.DataCoding = SmppDataCoding.FromValue(bb.ReadByte(ref StartPosition)); _SmDefaultMessageId = bb.ReadByte(ref StartPosition); byte length = bb.ReadByte(ref StartPosition); _ShortMessage.Value = bb.ReadBytes(ref StartPosition, length); }
public override void SetTranslate(string[] strings) { var oldStrings = GetStrings(true); if (strings.Length != oldStrings.Length) { throw new Exception("Line count mismatch"); } ByteBuilder bb = new ByteBuilder(); for (int r = 0; r < strings.Length; r++) { var tr = strings[r]; if (tr == null) { tr = oldStrings[r]; } var bytes = GameEncoding.GetBytes(tr); bb.AddBytes(bytes); bb.AddByte(0); } SaveTranslate(bb.GetArray()); }
/// <summary> /// 当接收到远程端的数据时,将触发此方法 /// 此方法用于处理和分析收到的数据 /// 如果得到一个数据包,将触发OnRecvComplete方法 /// [注]这里只需处理一个数据包的流程 /// </summary> /// <param name="client">客户端</param> /// <param name="recvBuilder">接收到的历史数据</param> /// <returns>如果不够一个数据包,则请返回null</returns> protected override Hybi13Packet OnReceive(SocketAsync <Hybi13Packet> client, ByteBuilder recvBuilder) { if (client.IsConnected == false) { return(null); } // 获取处理接收的数据的容器 var resultBuilder = client.TagBag.ResultBuilder as ByteBuilder; // 说明不是第一次握手请求 if (resultBuilder != null) { return(RequestPacket.GetPacket(recvBuilder, resultBuilder)); } // 设置ResultBuilder client.TagBag.ResultBuilder = new ByteBuilder(); // 处理握手请求 var request = HandshakeRequest.Parse(recvBuilder.ToArrayThenClear()); if (request == null || this.CheckHandshake(client, request) == false) { this.CloseClient(client, CloseStatus.ProtocolError); } else { var packet = new ResponsePacket(); packet.SetHandshake(request.ToHandshake()); client.Send(packet); } return(null); }
internal SmppQuerySmRes(ByteBuilder bb) { _Header = new SmppHeader(bb); int lastBytePosition = 0x10; _Body = new BodyPdu(bb, ref lastBytePosition); }
public override void WriteOffsets(ByteBuilder bb) { foreach (Code c in Operators) { c.WriteOffset(bb); } }
// Note: if you use this, make sure to set the builder to have enough bytes // Returns: offset to the data (end of headers), UInt32.MaxValue if end of headers not found yet public static UInt32 ReadHttpHeaders(Socket socket, ByteBuilder builder) { Int32 bytesReceived = socket.Receive(builder.bytes, (int)builder.contentLength, (int)(builder.bytes.Length - builder.contentLength), 0); if (bytesReceived <= 0) { throw new FormatException(String.Format("socket closed before all HTTP headers were received ({0} bytes received)'", bytesReceived)); } UInt32 checkOffset = builder.contentLength; builder.contentLength += (UInt32)bytesReceived; // Search for the ending \r\n\r\n Byte[] checkBuffer = builder.bytes; if (checkOffset >= 3) { checkOffset -= 3; // Reverse 3 chars in case the last request had the partial end of double newline } for (; checkOffset + 3 < builder.contentLength; checkOffset++) { if (checkBuffer[checkOffset] == (Byte)'\r' && checkBuffer[checkOffset + 1] == (Byte)'\n' && checkBuffer[checkOffset + 2] == (Byte)'\r' && checkBuffer[checkOffset + 3] == (Byte)'\n') { return(checkOffset + 4); } } return(UInt32.MaxValue); }
public override void Write(ByteBuilder bb) { foreach (var r in Refs) { bb.AddShortBE(r); } }
private void SetFrequncyHopppingChannelTable(byte[] data) { int size = data[5]; if (size > data.Length - 9) { return; } ByteBuilder ba = new ByteBuilder(); for (int i = 6; i < size + 6; i++) { ba.Append(data[i]); } formChannelTable.SetChannel(ba.GetByteArray()); if (formChannelTable.isDisplayed) { } else { formChannelTable.ShowDialog(); } }
public byte[] GetBytes() { ByteBuilder bb = new ByteBuilder(); WriteExt(bb); return(bb.GetArray()); }
public virtual void Write(ByteBuilder bb) { if (Args != null) { bb.AddBytes(Args); } }
public override void WriteOffsets(ByteBuilder bb) { foreach (StringConst str in Strings) { str.WriteOffset(bb); } }
public override void Write(ByteBuilder bb) { bb.AddShortBE(0x1234); bb.AddShortBE(0); bb.AddShortBE(funcList); bb.AddShortBE((ushort)Selectors.Length); for (int i = 0; i < Selectors.Length; i++) { Selectors[i].Write(bb); } if (Type == SectionType.Class) { foreach (ushort vs in varselectors) { bb.AddShortBE(vs); } } bb.AddShortBE((ushort)FuncNames.Length); foreach (ushort val in FuncNames) { bb.AddShortBE(val); } bb.AddShortBE(0); foreach (RefToElement r in FuncCode) { r.Write(bb); } }
internal SmppHeader(ByteBuilder bb) { _CommandLength = SmppConverter.FromByteArrayToInt32(bb.ToArray(0, 4)); _CommandId = SmppConverter.FromByteArrayToInt32(bb.ToArray(4, 4)); _CommandStatus = SmppConverter.FromByteArrayToInt32(bb.ToArray(8, 4)); _SequenceNumber = SmppConverter.FromByteArrayToInt32(bb.ToArray(12, 4)); }
/// <summary> /// Performs the specified SOCKS5 request. /// </summary> /// <param name="request">The SOCKS5 request to issue to the server.</param> /// <returns>The SOCKS5 reply sent by the server.</returns> /// <exception cref="ArgumentNullException">The request parameter is /// null.</exception> /// <exception cref="ObjectDisposedException">The object has been /// disposed.</exception> /// <exception cref="Socks5Exception">The request could not be performed. /// Consult the InnerException property of the Socks5Exception to learn /// the reason.</exception> public SocksReply Request(SocksRequest request) { AssertValid(); try { byte[] bytes = request.Serialize(); stream.Write(bytes, 0, bytes.Length); ByteBuilder b = new ByteBuilder(); using (var r = new BinaryReader(stream, Encoding.UTF8, true)) { bytes = r.ReadBytes(4); b.Append(bytes); ATyp atyp = (ATyp)bytes[3]; switch (atyp) { case ATyp.IPv4: case ATyp.IPv6: b.Append(r.ReadBytes(atyp == ATyp.IPv4 ? 4 : 16)); break; case ATyp.Domain: byte length = r.ReadByte(); b.Append(length).Append(r.ReadBytes(length)); break; } b.Append(r.ReadBytes(2)); } return(SocksReply.Deserialize(b.ToArray())); } catch (Exception e) { throw new Socks5Exception("The request could not be performed.", e); } }
private void fb_param_set(string[] fb_parm) { ByteBuilder bb = new ByteBuilder(); byte txLPF; byte fb_res1; byte fb_res2; try { txLPF = Convert.ToByte(fb_parm[0]); fb_res1 = Convert.ToByte(fb_parm[1]); fb_res2 = Convert.ToByte(fb_parm[2]); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } bb.Append(txLPF); bb.Append(fb_res1); bb.Append(fb_res2); if (!RcpProtocol.Instance.SendBytePkt(RcpProtocol.Instance.BuildCmdPacketByte(RcpProtocol.RCP_MSG_CMD, RcpProtocol.RCP_CMD_SET_FB_PARAM, bb.GetByteArray()))) { } }
public override void WriteOffsets(ByteBuilder bb) { foreach (var r in Refs) { r.WriteOffset(bb); } }
/// <summary> /// 解析一个数据包 /// 不足一个封包时返回null /// </summary> /// <param name="builder">接收到的历史数据</param> /// <returns></returns> public static FastPacket GetPacket(ByteBuilder builder) { // 包头长度 const int headLength = 12; // 不会少于12 if (builder.Length < headLength) { return(null); } // 包长 int totalLength = builder.ToInt32(0, Endians.Big); // 包长要小于等于数据长度 if (totalLength > builder.Length || totalLength < headLength) { return(null); } // cmd int cmd = builder.ToInt32(4, Endians.Big); // 哈希值 int hashCode = builder.ToInt32(8, Endians.Big); // 实体数据 byte[] body = builder.ToArray(12, totalLength - headLength); // 清空本条数据 builder.Remove(totalLength); return(new FastPacket(cmd, hashCode, body)); }
public override void WriteOffsets(ByteBuilder bb) { foreach (var v in Vars) { (v as RefToElement)?.WriteOffset(bb); } }
/// <summary> /// Serializes the instance into an array of bytes. /// </summary> /// <returns>An array of bytes representing the instance of the /// ClientGreeting class.</returns> public byte[] Serialize() { ByteBuilder b = new ByteBuilder() .Append(version) .Append((byte) methods.Count); foreach (AuthMethod m in Methods) b.Append((byte) m); return b.ToArray(); }
public static byte[] ComputeClientProof(Mpi safePrimeModulus, Mpi generator, string username, byte[] salt, Mpi clientPublicKey, Mpi serverPublicKey, Mpi sharedKey, string authId, string options, HashAlgorithm hashAlgorithm) { byte[] n = safePrimeModulus.ToBytes(), g = generator.ToBytes(), u = Encoding.UTF8.GetBytes(username), s = salt, a = clientPublicKey.ToBytes(), b = serverPublicKey.ToBytes(), k = sharedKey.ToBytes(), i = Encoding.UTF8.GetBytes(authId), l = Encoding.UTF8.GetBytes(options); HashAlgorithm h = hashAlgorithm; byte[] seq = new ByteBuilder() .Append(Xor(h.ComputeHash(n), h.ComputeHash(g))) .Append(h.ComputeHash(u)) .Append(s) .Append(a) .Append(b) .Append(k) .Append(h.ComputeHash(i)) .Append(h.ComputeHash(l)) .ToArray(); return h.ComputeHash(seq); }
/// <summary> /// 转换为ByteRange /// </summary> /// <returns></returns> public override ByteRange ToByteRange() { var builder = new ByteBuilder(Endians.Big); builder.Add((byte)((byte)this.Frame + 128)); if (this.Content.Length > UInt16.MaxValue) { builder.Add((byte)127); builder.Add((ulong)this.Content.Length); } else if (this.Content.Length > 125) { builder.Add((byte)126); builder.Add((ushort)this.Content.Length); } else { builder.Add((byte)this.Content.Length); } builder.Add(this.Content); return builder.ToByteRange(); }
public static byte[] ComputeServerProof(Mpi clientPublicKey, byte[] clientProof, Mpi sharedKey, string authId, string options, string sid, uint ttl, HashAlgorithm hashAlgorithm) { byte[] a = clientPublicKey.ToBytes(), m1 = clientProof, k = sharedKey.ToBytes(), i = Encoding.UTF8.GetBytes(authId), o = Encoding.UTF8.GetBytes(options), sid_ = Encoding.UTF8.GetBytes(sid); HashAlgorithm h = hashAlgorithm; byte[] seq = new ByteBuilder() .Append(a) .Append(m1) .Append(k) .Append(h.ComputeHash(i)) .Append(h.ComputeHash(o)) .Append(sid_) .Append(ttl, true) .ToArray(); return h.ComputeHash(seq); }
/// <summary> /// 将参数序列化并写入为Body /// </summary> /// <param name="serializer">序列化工具</param> /// <param name="parameters">参数</param> /// <exception cref="SerializerException"></exception> public void SetBodyParameters(ISerializer serializer, params object[] parameters) { if (parameters == null || parameters.Length == 0) { return; } var builder = new ByteBuilder(Endians.Big); foreach (var item in parameters) { // 序列化参数为二进制内容 var paramBytes = serializer.Serialize(item); // 添加参数内容长度 builder.Add(paramBytes == null ? 0 : paramBytes.Length); // 添加参数内容 builder.Add(paramBytes); } this.Body = builder.ToArray(); }
/// <summary> /// 转换为ByteRange /// </summary> /// <exception cref="ProtocolException"></exception> /// <returns></returns> public ByteRange ToByteRange() { var apiNameBytes = Encoding.UTF8.GetBytes(this.ApiName); var headLength = apiNameBytes.Length + 15; this.TotalBytes = this.Body == null ? headLength : headLength + this.Body.Length; const int packegMaxSize = 10 * 1204 * 1024; // 10M if (this.TotalBytes > packegMaxSize) { throw new ProtocolException(); } this.ApiNameLength = (byte)apiNameBytes.Length; var builder = new ByteBuilder(Endians.Big); builder.Add(this.TotalBytes); builder.Add(this.ApiNameLength); builder.Add(apiNameBytes); builder.Add(this.Id); builder.Add(this.IsFromClient); builder.Add(this.IsException); builder.Add(this.Body); return builder.ToByteRange(); }
/// <summary> /// 输出文本内容 /// </summary> /// <param name="content">内容</param> public bool Write(string content) { if (content == null) { content = string.Empty; } var buffer = new ByteBuilder(Endians.Little); var contentBytes = this.Charset.GetBytes(content); if (this.wroteHeader == false) { this.wroteHeader = true; var headerByes = this.GetHeaderBytes(contentBytes.Length); buffer.Add(headerByes); } buffer.Add(contentBytes); return this.TrySend(buffer.ToByteRange()); }
/// <summary> /// Converts the notification information into a packet of data to be sent /// to the Growl receiving application. /// </summary> /// <returns>byte array</returns> private byte[] PrepareData() { int flags = ConvertPriorityToFlag(this.priority); if (this.sticky) flags = flags | 1; ByteBuilder bb = new ByteBuilder(); bb.Append((byte)this.protocolVersion); bb.Append((byte)this.packetType); bb.Append((short)flags); bb.Append(ByteBuilder.GetStringLengthAsShort(this.notificationType.Name)); bb.Append(ByteBuilder.GetStringLengthAsShort(this.title)); bb.Append(ByteBuilder.GetStringLengthAsShort(this.description)); bb.Append(ByteBuilder.GetStringLengthAsShort(this.applicationName)); bb.Append(this.notificationType.Name); bb.Append(this.title); bb.Append(this.description); bb.Append(this.applicationName); // handle the password ByteBuilder pb = new ByteBuilder(); pb.Append(this.password); ByteBuilder bpb = new ByteBuilder(); bpb.Append(bb.GetBytes()); bpb.Append(pb.GetBytes()); byte[] checksum = Cryptography.ComputeHash(bpb.GetBytes(), Cryptography.HashAlgorithmType.MD5); ByteBuilder fb = new ByteBuilder(); fb.Append(bb.GetBytes()); fb.Append(checksum); byte[] data = fb.GetBytes(); return data; }
/// <summary> /// Performs the initial greeting. /// </summary> /// <exception cref="Socks5Exception">The client sent invalid data, or /// requires authentication.</exception> /// <exception cref="IOException">The stream could not be read, or the /// operation timed out.</exception> void PerformGreeting() { ByteBuilder b = new ByteBuilder(); using (var r = new BinaryReader(stream, Encoding.UTF8, true)) { byte[] bytes = r.ReadBytes(2); b.Append(bytes); // The number of method-bytes following is contained in the second byte. b.Append(r.ReadBytes(bytes[1])); } ClientGreeting greeting = ClientGreeting.Deserialize(b.ToArray()); // We only accept an authentication method of 'none'. if (!greeting.Methods.Contains(AuthMethod.None)) { Dispose(); throw new Socks5Exception("Client requires authentication."); } // Send back our greeting response. var response = new ServerGreeting(AuthMethod.None).Serialize(); stream.Write(response, 0, response.Length); }
/// <summary> /// Waits until the connected client sends a SOCKS5 request. /// </summary> /// <returns>The SOCKS5 request sent by the client.</returns> /// <exception cref="Socks5Exception">The data sent by the client /// is not a valid SOCKS5 request.</exception> SocksRequest WaitForRequest() { ByteBuilder b = new ByteBuilder(); using (var r = new BinaryReader(stream, Encoding.UTF8, true)) { byte[] bytes = r.ReadBytes(4); b.Append(bytes); ATyp atyp = (ATyp) bytes[3]; switch (atyp) { case ATyp.IPv4: case ATyp.IPv6: b.Append(r.ReadBytes(atyp == ATyp.IPv4 ? 4 : 16)); break; case ATyp.Domain: byte length = r.ReadByte(); b.Append(length).Append(r.ReadBytes(length)); break; } b.Append(r.ReadBytes(2)); } try { return SocksRequest.Deserialize(b.ToArray()); } catch (Exception e) { throw new Socks5Exception("The request could not be serialized.", e); } }
private static byte[] LMv2Response(byte[] hash, byte[] clientData, byte[] challenge) { byte[] data = new ByteBuilder() .Append(challenge) .Append(clientData) .ToArray(); using (var hmac = new HMACMD5(hash)) { return new ByteBuilder() .Append(hmac.ComputeHash(data)) .Append(clientData) .ToArray(); } }
private static object getRealValue(IDataReader datareader, int ordinal, Type t) { if (t == typeof(Int16)) return !datareader.IsDBNull(ordinal) ? (object)datareader.GetInt16(ordinal) : null; if (t == typeof(Int32)) return !datareader.IsDBNull(ordinal) ? (object)datareader.GetInt32(ordinal) : null; if (t == typeof(Int64)) return !datareader.IsDBNull(ordinal) ? (object)datareader.GetInt32(ordinal) : null; if (t == typeof(Byte[])) { if (datareader.IsDBNull(ordinal)) return null; int bufferSize = 1024; int startIndex = 0; byte[] outbyte = new byte[bufferSize]; ByteBuilder bb = new ByteBuilder(); long retval = datareader.GetBytes(ordinal, startIndex, outbyte, 0, bufferSize); while (retval == bufferSize) { bb.Append(outbyte); startIndex += bufferSize; retval = datareader.GetBytes(ordinal, startIndex, outbyte, 0, bufferSize); } if (retval > 0) bb.Append(outbyte); return bb.GetBytes(); } if (t == typeof(String)) return !datareader.IsDBNull(ordinal) ? datareader.GetString(ordinal) : null; if (t == typeof(DateTime)) return !datareader.IsDBNull(ordinal) ? (object)datareader.GetDateTime(ordinal) : null; if (t == typeof(Boolean)) return !datareader.IsDBNull(ordinal) ? (object)datareader.GetBoolean(ordinal) : null; if (t == typeof(Double)) return !datareader.IsDBNull(ordinal) ? (object)datareader.GetDouble(ordinal) : null; if (t == typeof(Single)) return !datareader.IsDBNull(ordinal) ? (object)datareader.GetFloat(ordinal) : null; if (t == typeof(Guid)) return !datareader.IsDBNull(ordinal) ? (object)datareader.GetGuid(ordinal) : null; if (t == typeof(Decimal)) return !datareader.IsDBNull(ordinal) ? (object)datareader.GetDecimal(ordinal) : null; if (t == typeof(Byte)) return !datareader.IsDBNull(ordinal) ? (object)datareader.GetByte(ordinal) : null; return null; }
/// <summary> /// Performs the specified SOCKS5 request. /// </summary> /// <param name="request">The SOCKS5 request to issue to the server.</param> /// <returns>The SOCKS5 reply sent by the server.</returns> /// <exception cref="ArgumentNullException">The request parameter is /// null.</exception> /// <exception cref="ObjectDisposedException">The object has been /// disposed.</exception> /// <exception cref="Socks5Exception">The request could not be performed. /// Consult the InnerException property of the Socks5Exception to learn /// the reason.</exception> public SocksReply Request(SocksRequest request) { request.ThrowIfNull("request"); AssertValid(); try { byte[] bytes = request.Serialize(); stream.Write(bytes, 0, bytes.Length); ByteBuilder b = new ByteBuilder(); using (var r = new BinaryReader(stream, Encoding.UTF8, true)) { bytes = r.ReadBytes(4); b.Append(bytes); ATyp atyp = (ATyp) bytes[3]; switch (atyp) { case ATyp.IPv4: case ATyp.IPv6: b.Append(r.ReadBytes(atyp == ATyp.IPv4 ? 4 : 16)); break; case ATyp.Domain: byte length = r.ReadByte(); b.Append(length).Append(r.ReadBytes(length)); break; } b.Append(r.ReadBytes(2)); } return SocksReply.Deserialize(b.ToArray()); } catch (Exception e) { throw new Socks5Exception("The request could not be performed.", e); } }
/// <summary> /// Computes the client evidence from the given parameters. /// </summary> /// <param name="safePrimeModulus">The safe prime modulus sent by the /// server.</param> /// <param name="generator">The generator sent by the server.</param> /// <param name="username">The username to authenticate with.</param> /// <param name="salt">The client's password salt.</param> /// <param name="clientPublicKey">The client's ephemeral public key.</param> /// <param name="serverPublicKey">The server's ephemeral public key.</param> /// <param name="sharedKey">The shared context key.</param> /// <param name="authId">The authorization identity.</param> /// <param name="options">The raw options string as received from the /// server.</param> /// <param name="hashAlgorithm">The message digest algorithm to use for /// calculating the client proof.</param> /// <returns>The client proof as an array of bytes.</returns> public static byte[] ComputeClientProof(Mpi safePrimeModulus, Mpi generator, string username, byte[] salt, Mpi clientPublicKey, Mpi serverPublicKey, Mpi sharedKey, string authId, string options, HashAlgorithm hashAlgorithm) { byte[] N = safePrimeModulus.ToBytes(), g = generator.ToBytes(), U = Encoding.UTF8.GetBytes(username), s = salt, A = clientPublicKey.ToBytes(), B = serverPublicKey.ToBytes(), K = sharedKey.ToBytes(), I = Encoding.UTF8.GetBytes(authId), L = Encoding.UTF8.GetBytes(options); HashAlgorithm H = hashAlgorithm; // The proof is calculated as follows: // // H( bytes(H( bytes(N) )) ^ bytes( H( bytes(g) )) // | bytes(H( bytes(U) )) // | bytes(s) // | bytes(A) // | bytes(B) // | bytes(K) // | bytes(H( bytes(I) )) // | bytes(H( bytes(L) )) // ) byte[] seq = new ByteBuilder() .Append(Xor(H.ComputeHash(N), H.ComputeHash(g))) .Append(H.ComputeHash(U)) .Append(s) .Append(A) .Append(B) .Append(K) .Append(H.ComputeHash(I)) .Append(H.ComputeHash(L)) .ToArray(); return H.ComputeHash(seq); }
/// <summary> /// Checks to see if a given packets data matches a password /// provided by the receiving client and returns the matching password if found. /// </summary> /// <param name="bytes">The packets data</param> /// <param name="passwordManager">The receiving client's list of passwords</param> /// <param name="passwordRequired">Indicates if the request must supply a valid password</param> /// <param name="password">Returns the matching password if found; null otherwise</param> /// <returns><c>true</c> if the password matches, <c>false</c> otherwise</returns> protected static bool IsPasswordValid(byte[] bytes, PasswordManager passwordManager, bool passwordRequired, out string password) { password = null; byte[] packetWithoutPassword = new byte[bytes.Length - 16]; Array.Copy(bytes, 0, packetWithoutPassword, 0, packetWithoutPassword.Length); byte[] thatChecksum = new byte[16]; Array.Copy(bytes, bytes.Length - 16, thatChecksum, 0, 16); string thatChecksumString = Encoding.UTF8.GetString(thatChecksum); ByteBuilder bpb = new ByteBuilder(); bpb.Append(packetWithoutPassword); Queue<string> validPasswords = new Queue<string>(); foreach (KeyValuePair<string, Password> item in passwordManager.Passwords) { validPasswords.Enqueue(item.Key); } // if the request does not require a password, then // we can also try no (blank) password if (!passwordRequired) validPasswords.Enqueue(String.Empty); while(validPasswords.Count > 0) { string p = validPasswords.Dequeue(); ByteBuilder pb = new ByteBuilder(); pb.Append(bpb.GetBytes()); pb.Append(p); byte[] thisChecksum = Cryptography.ComputeHash(pb.GetBytes(), Cryptography.HashAlgorithmType.MD5); string thisChecksumString = Encoding.UTF8.GetString(thisChecksum); if (thisChecksumString == thatChecksumString) { password = p; return true; } } return false; }
/// <summary> /// Calculates the shared context key K from the given parameters. /// </summary> /// <param name="salt">The user's password salt.</param> /// <param name="username">The username to authenticate with.</param> /// <param name="password">The password to authenticate with.</param> /// <param name="clientPublicKey">The client's ephemeral public key.</param> /// <param name="serverPublicKey">The server's ephemeral public key.</param> /// <param name="clientPrivateKey">The client's private key.</param> /// <param name="generator">The generator sent by the server.</param> /// <param name="safePrimeModulus">The safe prime modulus sent by the /// server.</param> /// <param name="hashAlgorithm">The negotiated hash algorithm to use /// for the calculations.</param> /// <returns>The shared context key K as a "multi-precision /// integer".</returns> /// <remarks> /// A = Client Public Key /// B = Server Public Key /// N = Safe Prime Modulus /// U = Username /// p = Password /// s = User's Password Salt /// a = Client Private Key /// g = Generator /// K = Shared Public Key /// </remarks> public static Mpi ComputeSharedKey(byte[] salt, string username, string password, Mpi clientPublicKey, Mpi serverPublicKey, Mpi clientPrivateKey, Mpi generator, Mpi safePrimeModulus, HashAlgorithm hashAlgorithm) { // u = H(A | B) byte[] u = hashAlgorithm.ComputeHash(new ByteBuilder() .Append(clientPublicKey.ToBytes()) .Append(serverPublicKey.ToBytes()) .ToArray()); // x = H(s | H(U | ":" | p)) byte[] up = hashAlgorithm.ComputeHash( Encoding.UTF8.GetBytes(username + ":" + password)), sup = new ByteBuilder().Append(salt).Append(up).ToArray(), x = hashAlgorithm.ComputeHash(sup); // S = ((B - (3 * g ^ x)) ^ (a + u * x)) % N Mpi _u = new Mpi(u), _x = new Mpi(x); ts.TraceInformation("ComputeSharedKey: _u = " + _u.Value.ToString("X")); ts.TraceInformation("ComputeSharedKey: _x = " + _x.Value.ToString("X")); // base = B - (3 * (g ^ x)) BigInteger _base = BigInteger.Subtract(serverPublicKey.Value, BigInteger.Multiply(new BigInteger(3), BigInteger.ModPow(generator.Value, _x.Value, safePrimeModulus.Value)) % safePrimeModulus.Value); if (_base.Sign < 0) _base = BigInteger.Add(_base, safePrimeModulus.Value); ts.TraceInformation("ComputeSharedKey: _base = " + _base.ToString("X")); // Alternative way to calculate base; This is not being used in actual calculations // but still here to ease debugging. BigInteger gx = BigInteger.ModPow(generator.Value, _x.Value, safePrimeModulus.Value), gx3 = BigInteger.Multiply(new BigInteger(3), gx) % safePrimeModulus.Value; ts.TraceInformation("ComputeSharedKey: gx = " + gx.ToString("X")); BigInteger @base = BigInteger.Subtract(serverPublicKey.Value, gx3) % safePrimeModulus.Value; if (@base.Sign < 0) @base = BigInteger.Add(@base, safePrimeModulus.Value); ts.TraceInformation("ComputeSharedKey: @base = " + @base.ToString("X")); // exp = a + u * x BigInteger exp = BigInteger.Add(clientPrivateKey.Value, BigInteger.Multiply(_u.Value, _x.Value)), S = BigInteger.ModPow(_base, exp, safePrimeModulus.Value); ts.TraceInformation("ComputeSharedKey: exp = " + exp.ToString("X")); ts.TraceInformation("ComputeSharedKey: S = " + S.ToString("X")); // K = H(S) return new Mpi(hashAlgorithm.ComputeHash(new Mpi(S).ToBytes())); }
public static Mpi ComputeSharedKey(byte[] salt, string username, string password, Mpi clientPublicKey, Mpi serverPublicKey, Mpi clientPrivateKey, Mpi generator, Mpi safePrimeModulus, HashAlgorithm hashAlgorithm) { byte[] u = hashAlgorithm.ComputeHash(new ByteBuilder() .Append(clientPublicKey.ToBytes()) .Append(serverPublicKey.ToBytes()) .ToArray()); byte[] up = hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(username + ":" + password)), sup = new ByteBuilder().Append(salt).Append(up).ToArray(), x = hashAlgorithm.ComputeHash(sup); Mpi u_ = new Mpi(u), x_ = new Mpi(x); ts.TraceInformation("ComputeSharedKey: _u = " + u_.Value.ToString("X")); ts.TraceInformation("ComputeSharedKey: _x = " + x_.Value.ToString("X")); BigInteger base_ = BigInteger.Subtract(serverPublicKey.Value, BigInteger.Multiply(new BigInteger(3), BigInteger.ModPow(generator.Value, x_.Value, safePrimeModulus.Value)) % safePrimeModulus.Value); if (base_.Sign < 0) { base_ = BigInteger.Add(base_, safePrimeModulus.Value); } ts.TraceInformation("ComputeSharedKey: _base = " + base_.ToString("X")); BigInteger gx = BigInteger.ModPow(generator.Value, x_.Value, safePrimeModulus.Value), gx3 = BigInteger.Multiply(new BigInteger(3), gx) % safePrimeModulus.Value; ts.TraceInformation("ComputeSharedKey: gx = " + gx.ToString("X")); BigInteger @base = BigInteger.Subtract(serverPublicKey.Value, gx3) % safePrimeModulus.Value; if (@base.Sign < 0) { @base = BigInteger.Add(@base, safePrimeModulus.Value); } ts.TraceInformation("ComputeSharedKey: @base = " + @base.ToString("X")); BigInteger exp = BigInteger.Add(clientPrivateKey.Value, BigInteger.Multiply(u_.Value, x_.Value)), s = BigInteger.ModPow(base_, exp, safePrimeModulus.Value); ts.TraceInformation("ComputeSharedKey: exp = " + exp.ToString("X")); ts.TraceInformation("ComputeSharedKey: S = " + s.ToString("X")); return new Mpi(hashAlgorithm.ComputeHash(new Mpi(s).ToBytes())); }
/// <summary> /// Computes the server evidence from the given parameters. /// </summary> /// <param name="clientPublicKey">The client's ephemeral public key.</param> /// <param name="clientProof"></param> /// <param name="sharedKey">The shared context key.</param> /// <param name="authId">The authorization identity.</param> /// <param name="options">The raw options string as sent by the /// client.</param> /// <param name="sid">The session id sent by the server.</param> /// <param name="ttl">The time-to-live value for the session id sent /// by the server.</param> /// <param name="hashAlgorithm">The message digest algorithm to use for /// calculating the server proof.</param> /// <returns>The server proof as an array of bytes.</returns> public static byte[] ComputeServerProof(Mpi clientPublicKey, byte[] clientProof, Mpi sharedKey, string authId, string options, string sid, uint ttl, HashAlgorithm hashAlgorithm) { byte[] A = clientPublicKey.ToBytes(), M1 = clientProof, K = sharedKey.ToBytes(), I = Encoding.UTF8.GetBytes(authId), o = Encoding.UTF8.GetBytes(options), _sid = Encoding.UTF8.GetBytes(sid); HashAlgorithm H = hashAlgorithm; // The proof is calculated as follows: // // H( bytes(A) // | bytes(M1) // | bytes(K) // | bytes(H( bytes(I) )) // | bytes(H( bytes(o) )) // | bytes(sid) // | ttl // ) byte[] seq = new ByteBuilder() .Append(A) .Append(M1) .Append(K) .Append(H.ComputeHash(I)) .Append(H.ComputeHash(o)) .Append(_sid) .Append(ttl, true) .ToArray(); return H.ComputeHash(seq); }
/// <summary> /// Converts the notification information into a packet of data to be sent /// to the Growl receiving application. /// </summary> /// <returns>byte array</returns> private byte[] PrepareData() { ByteBuilder nb = new ByteBuilder(); ByteBuilder db = new ByteBuilder(); int index = 0; int notificationTypeCount = 0; int notificationTypeEnabledCount = 0; foreach (NotificationType notificationType in this.notificationTypes) { nb.Append(notificationType.Name.Length); nb.Append(notificationType.Name); notificationTypeCount++; if (notificationType.Enabled) { notificationTypeEnabledCount++; db.Append((byte)index); } index++; } ByteBuilder bb = new ByteBuilder(); bb.Append((byte)this.protocolVersion); bb.Append((byte)this.packetType); bb.Append(ByteBuilder.GetStringLengthAsShort(this.applicationName)); bb.Append((byte)notificationTypeCount); bb.Append((byte)notificationTypeEnabledCount); bb.Append(this.applicationName); bb.Append(nb.GetBytes()); bb.Append(db.GetBytes()); // handle the password ByteBuilder pb = new ByteBuilder(); pb.Append(this.password); ByteBuilder bpb = new ByteBuilder(); bpb.Append(bb.GetBytes()); bpb.Append(pb.GetBytes()); byte[] checksum = Cryptography.ComputeHash(bpb.GetBytes(), Cryptography.HashAlgorithmType.MD5); ByteBuilder fb = new ByteBuilder(); fb.Append(bb.GetBytes()); fb.Append(checksum); byte[] data = fb.GetBytes(); return data; }