Exemplo n.º 1
0
        private async void GetContactsBT_Click(object sender, EventArgs e)
        {
            Loading(GetContactsBT, true);
            TLRequestContactsGetContacts req = new TLRequestContactsGetContacts();

            req.setHash("");
            //var res = NewApi.Api().doRpcCall(req);
            var res = await WTask.Task.Run(() => NewApi.Api().doRpcCall(req));

            if (res == null)
            {
                NotifyBar.Text      = "درخواست نتیجه ای نداشت!";
                NotifyBar.ForeColor = Color.Orange;
            }
            else
            {
                ContactsDGV.Rows.Clear();
                TLContacts Contacts = (TLContacts)res;
                foreach (TLUser contact in Contacts.getUsers())
                {
                    ContactsDGV.Rows.Add(contact.getFirstName() + " " + contact.getLastName(), contact.getUserName(), contact.getPhone(), contact.getId(), contact.getAccessHash());
                }
            }
            GetContactsBT.Enabled = true;
        }
Exemplo n.º 2
0
        private async Task <TLUser> GetUserAsync(string userNumber)
        {
            if (string.IsNullOrWhiteSpace(userNumber))
            {
                throw new ArgumentException("Login can't be empty.");
            }

            if (!Regex.Match(userNumber, phoneNumberPattern).Success)
            {
                throw new ArgumentException("Login is not a valid phone number: " + userNumber);
            }

            // this is because the contacts in the address come without the "+" prefix
            var normalizedNumber = userNumber.StartsWith("+") ?
                                   userNumber.Substring(1, userNumber.Length - 1) :
                                   userNumber;

            // get available contacts
            if (Contacts == null)
            {
                Contacts = await client.GetContactsAsync();
            }

            var user = Contacts.Users
                       .OfType <TLUser>()
                       .FirstOrDefault(x => x.Phone == normalizedNumber);

            if (user == null)
            {
                throw new Exception("Number '" + userNumber + "' was not found in Contacts List.");
            }

            return(user);
        }
Exemplo n.º 3
0
        private async WTask.Task <TLContacts> GetAllContacts()
        {
            try
            {
                TLRequestContactsGetContacts req = new TLRequestContactsGetContacts();
                req.setHash("");
                //var res = NewApi.Api().doRpcCall(req);
                var res = await WTask.Task.Run(() => NewApi.Api().doRpcCall(req));

                if (res == null)
                {
                    NotifyBar.Text      = "درخواست نتیجه ای نداشت!";
                    NotifyBar.ForeColor = Color.Orange;
                    return(null);
                }
                else
                {
                    TLContacts Contacts = (TLContacts)res;
                    return(Contacts);
                }
            }
            catch (Exception ex)
            {
                NotifyBar.Text      = "خطا: " + ex.Message;
                NotifyBar.ForeColor = Color.Red;
                return(null);
            }
        }
Exemplo n.º 4
0
        private async Task <TLUser> GetUserByPhoneNumber(string phoneNumber)
        {
            TLContacts result = await telegramClient?.GetContactsAsync();

            return(result.Users
                   .Where(x => x.GetType() == typeof(TLUser))
                   .Cast <TLUser>()
                   .FirstOrDefault(x => x.Phone == phoneNumber.Trim().Replace("+", "")));
        }
Exemplo n.º 5
0
        public async Task <Respuestas> VerificarSesion(string pathArchivo)
        {
            Respuestas respuesta = new Respuestas();

            try
            {
                contexto = Iniciar();
                TLContacts contactos = new TLContacts();
                info = CargarDeArchivo <Informacion_sesion>(pathArchivo);
                if (info == null)
                {
                    info = new Informacion_sesion();
                }
                TLUser usuario = new TLUser();
                await contexto.ConnectAsync();

                if (contexto.IsUserAuthorized())
                {
                    contactos = await contexto.GetContactsAsync();

                    List <Usuarios> lista = new List <Usuarios>();
                    foreach (var item in contactos.Users.OfType <TLUser>())
                    {
                        var contacto = new Usuarios
                        {
                            Nombre   = item.FirstName + item.LastName,
                            Telefono = "+" + item.Phone
                        };
                        lista.Add(contacto);
                    }
                    info.contactos    = lista.OrderBy(x => x.Nombre).ToList();
                    respuesta.STATUS  = true;
                    respuesta.MESSAGE = "Reconexion exitosa exitosa...";
                    respuesta.data    = info;
                }
                else
                {
                    respuesta.STATUS  = false;
                    respuesta.data    = info;
                    respuesta.MESSAGE = "Reconexion fallida, intente autenticar de nuevo...";
                }
                JObject objeto = JObject.Parse(File.ReadAllText(pathArchivo.Replace("Registros.txt", "Sesion.txt")));
                info.Expiracion.Add(DateTime.Now.AddMilliseconds(objeto.Value <double>("SessionExpires")).ToString("MM/dd/yy H:mm:ss"));
                GuardarArchivo(pathArchivo, info);
                return(respuesta);
            }
            catch (Exception e)
            {
                respuesta.MESSAGE = "No se pudo hacer la verificacion..." + ((string.IsNullOrEmpty(e.InnerException.Message)) ? e.Message : e.InnerException.Message);
                if (respuesta.MESSAGE.ToUpper().Contains("AUTH_KEY_UNREGISTERED"))
                {
                    respuesta.MESSAGE = "Debe Autenticarse solicitando su código";
                }
                respuesta.STATUS = false;
                return(respuesta);
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Necesarios: NumeroDestino, Imagen, DescripcionImagen si se quiere
        /// </summary>
        /// <param name="nuevo"></param>
        /// <returns></returns>
        public async Task <Respuestas> EnviarImagen(Mensaje nuevo)
        {
            Respuestas respuesta = new Respuestas();

            try
            {
                var numeroformateado = nuevo.NumeroDestino.StartsWith("+") ?
                                       nuevo.NumeroDestino.Substring(1) :
                                       nuevo.NumeroDestino;
                contexto = Iniciar();
                await contexto.ConnectAsync();

                var contactos = new TLContacts();
                contactos = await contexto.GetContactsAsync();

                var usuariodestino = contactos.Users.OfType <TLUser>().FirstOrDefault(x => x.Phone == numeroformateado);
                if (usuariodestino == null)
                {
                    respuesta.MESSAGE = "El numero" + numeroformateado + " no esta en la lista de sus contactos";
                    respuesta.STATUS  = false;
                    return(respuesta);
                }
                MemoryStream imagen = new MemoryStream(Convert.FromBase64String(nuevo.Imagen));
                //var im = Image.FromStream(imagen);
                //Image imagen_redimensionada = ResizeImage(im, 300, 60);
                //args.Image = imagen_redimensionada;
                StreamReader imageStream = new StreamReader(imagen); //verificar encoding

                var archivo = new TLInputFile();
                archivo = (TLInputFile)await contexto.UploadFile("Image" + (new Random().Next()) + ".jpg", imageStream);

                if (archivo != null)
                {
                    await contexto.SendUploadedPhoto(new TLInputPeerUser()
                    {
                        UserId = usuariodestino.Id
                    }, archivo, nuevo.DescripcionImagen);

                    respuesta.MESSAGE = "Imagen enviada a: " + numeroformateado;
                    respuesta.STATUS  = true;
                    return(respuesta);
                }
                else
                {
                    respuesta.MESSAGE = "No se pudo enviar imagen, ERROR INTERNO...";
                    respuesta.STATUS  = false;
                    return(respuesta);
                }
            }
            catch (Exception e)
            {
                respuesta.MESSAGE = " no se pudo enviar imagen..." + e.Message;
                respuesta.STATUS  = false;
                return(respuesta);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Sending a message using the recipient's nickname and message text
        /// </summary>
        /// <param name="recepientUserName"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public async static Task SendMessage(string recepientUserName, string message)
        {
            //get user contacts
            TLContacts constacts = await _client.GetContactsAsync();

            //find recipient in contacts
            TLUser user = constacts.Users
                          .Where(x => x.GetType() == typeof(TLUser))
                          .Cast <TLUser>()
                          .FirstOrDefault(x => x.Username == recepientUserName);

            //send message
            _client.SendMessageAsync(new TLInputPeerUser()
            {
                UserId = user.Id
            }, message);
        }
Exemplo n.º 8
0
        /// <summary>
        /// This method requests an Authoritzation code to telegram, the user must input then.
        /// </summary>
        /// <param name="phoneNumber">Phone To send the code</param>
        /// <returns></returns>
        public async Task Authenticate(String phoneNumber)
        {
            var hash = await client.SendCodeRequestAsync(phoneNumber);

            //Request Code

            var code = await Console.In.ReadLineAsync();

            //Input code

            var user = await client.MakeAuthAsync(phoneNumber, hash, code);

            //Request Authoritzation with the code


            //get available contacts
            Contacts = await client.GetContactsAsync();
        }
Exemplo n.º 9
0
        public async Task AddUserToContactsAsync(UserInfoDto model)
        {
            if (string.IsNullOrWhiteSpace(model.Login))
            {
                throw new ArgumentException("Login can't be empty");
            }

            if (!Regex.Match(model.Login, phoneNumberPattern).Success)
            {
                throw new ArgumentException("Login is not a valid phone number: " + model.Login);
            }

            // this is because the contacts in the address come without the "+" prefix
            var normalizedNumber = model.Login.StartsWith("+") ?
                                   model.Login.Substring(1, model.Login.Length - 1) :
                                   model.Login;

            if (string.IsNullOrWhiteSpace(model.FirstName))
            {
                throw new ArgumentException("First name can't be empty");
            }

            if (string.IsNullOrWhiteSpace(model.LastName))
            {
                throw new ArgumentException("Last name can't be empty");
            }

            TLVector <TLInputPhoneContact> contacts = new TLVector <TLInputPhoneContact>
            {
                new TLInputPhoneContact()
                {
                    Phone = normalizedNumber, FirstName = model.FirstName, LastName = model.LastName
                }
            };

            var request = new TLRequestImportContacts()
            {
                Contacts = contacts
            };

            await client.SendRequestAsync <TLImportedContacts>(request);

            Contacts = await client.GetContactsAsync(); // Updating saved contacts
        }
Exemplo n.º 10
0
        public async Task <MTObject> Handle(IMessageContext <TLGetContacts> context)
        {
            var result = new TLContacts();

            result.Users    = new TLVector <TLAbsUser>();
            result.Contacts = new TLVector <TLContact>();
            try
            {
                var session = manager.GetSession(context.AuthKey());
                if (session == null)
                {
                    throw new Exception("Seesion not found.");
                }
                var userId   = session.GetUserId();
                var request  = context.Body;
                var contacts = await contactService.GetContacts(userId);

                contacts.ToList().ForEach(x => {
                    result.Contacts.Add(new TLContact {
                        UserId = x.ImportedContactId,
                    });
                    result.Users.Add(new MTProto.NET.Schema.Layer72.TLUser {
                        Id         = x.ImportedContactId,
                        FirstName  = x.FirstName,
                        LastName   = x.LastName,
                        Phone      = x.Phone,
                        AccessHash = 5
                    });
                });
            }
            catch (Exception err)
            {
                this.logger.LogError(
                    "An error occured while trying to handle 'ImportContacts': \r\n{0}", err.GetBaseException().Message);
                throw;
            }
            return(result);
        }
Exemplo n.º 11
0
        private async WTask.Task <TLUser> SearchContact(string UsernamePhone)
        {
            try
            {
                TLRequestContactsGetContacts req = new TLRequestContactsGetContacts();
                req.setHash("");
                //var res = NewApi.Api().doRpcCall(req);
                var res = await WTask.Task.Run(() => NewApi.Api().doRpcCall(req));

                if (res == null)
                {
                    NotifyBar.Text      = "درخواست نتیجه ای نداشت!";
                    NotifyBar.ForeColor = Color.Orange;
                    return(null);
                }
                else
                {
                    TLContacts Contacts = (TLContacts)res;
                    foreach (TLUser contact in Contacts.getUsers())
                    {
                        if (contact.getUserName().ToLower() == UsernamePhone.Trim() || contact.getPhone() == UsernamePhone.Trim())
                        {
                            return(contact);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                NotifyBar.Text      = "خطا: " + ex.Message;
                NotifyBar.ForeColor = Color.Red;
                return(null);
            }

            return(null);
        }
Exemplo n.º 12
0
        public async Task <Respuestas> AutenticarUsuario(string codigo, string filepath)
        {
            try
            {
                Respuestas respuesta = new Respuestas();
                contexto = Iniciar();
                TLContacts contactos = new TLContacts();
                info = CargarDeArchivo <Informacion_sesion>(filepath);
                info.Codigo_autenticacion = codigo;
                TLUser usuario = null;
                await contexto.ConnectAsync();

                if (contexto.IsConnected)
                {
                    usuario = await contexto.MakeAuthAsync(info.NumeroPropietario, info.Codigo_solicitud, info.Codigo_autenticacion);

                    if (usuario != null)
                    {
                        info.NombreUsuario = usuario.FirstName;
                        contactos          = await contexto.GetContactsAsync();

                        List <Usuarios> lista = new List <Usuarios>();
                        foreach (var item in contactos.Users.OfType <TLUser>())
                        {
                            var contacto = new Usuarios
                            {
                                Nombre   = item.FirstName + " " + item.LastName,
                                Telefono = "+" + item.Phone
                            };
                            lista.Add(contacto);
                        }
                        info.contactos = lista.OrderBy(x => x.Nombre).ToList();
                        JObject objeto = JObject.Parse(File.ReadAllText(filepath.Replace("Registros.txt", "Sesion.txt")));
                        info.Expiracion.Add(DateTime.Now.AddMilliseconds(objeto.Value <double>("SessionExpires")).ToString("MM/dd/yy H:mm:ss"));
                        GuardarArchivo(filepath, info);
                        respuesta.STATUS  = true;
                        respuesta.MESSAGE = "Autenticación exitosa...";
                        respuesta.data    = info;
                        return(respuesta);
                    }
                    else
                    {
                        respuesta.MESSAGE = "no se pudo obtener datos de usuario...";
                        respuesta.STATUS  = false;
                        return(respuesta);
                    }
                }
                else
                {
                    respuesta.MESSAGE = "ya se encuentra autenticado...";
                    respuesta.STATUS  = false;
                    contexto.Dispose();
                    return(respuesta);
                }
            }
            catch (Exception e)
            {
                return(new Respuestas()
                {
                    STATUS = false, MESSAGE = "No se pudo autenticar usuario" + e.InnerException.Message
                });
            }
        }
Exemplo n.º 13
0
        public async Task <Respuestas> EnviarMensaje(Mensaje nuevo, string pathArchivo)
        {
            Respuestas respuesta = new Respuestas();

            try
            {
                contexto = Iniciar();
                TLContacts contactos = new TLContacts();
                await contexto.ConnectAsync();

                contactos = await contexto.GetContactsAsync();

                List <Usuarios> lista = new List <Usuarios>();
                foreach (var item in contactos.Users.OfType <TLUser>())
                {
                    var contacto = new Usuarios
                    {
                        Nombre   = item.FirstName + " " + item.LastName,
                        Telefono = "+" + item.Phone
                    };
                    lista.Add(contacto);
                }
                info.contactos = lista.OrderBy(x => x.Nombre).ToList();
                var numeroformateado = nuevo.NumeroDestino.StartsWith("+") ?
                                       nuevo.NumeroDestino.Substring(1) :
                                       nuevo.NumeroDestino;
                var usuariodestino = contactos.Users.OfType <TLUser>().FirstOrDefault(x => x.Phone == numeroformateado);
                if (usuariodestino == null)
                {
                    respuesta.STATUS  = false;
                    respuesta.MESSAGE = "No se pudo encontrar a usuario...";
                    return(respuesta);
                }
                bool completado = await contexto.SendTypingAsync(new TLInputPeerUser()
                {
                    UserId = usuariodestino.Id
                });

                await Task.Delay(3000);

                if (completado)
                {
                    await contexto.SendMessageAsync(new TLInputPeerUser()
                    {
                        UserId = usuariodestino.Id
                    }, nuevo.TextoContenido);
                }
                else
                {
                    respuesta.STATUS  = false;
                    respuesta.MESSAGE = "No se pudo sincronizar conexion con Telegram...";
                    return(respuesta);
                }
                respuesta.STATUS  = true;
                respuesta.MESSAGE = "Mensaje enviado a: " + usuariodestino.FirstName;
                return(respuesta);
            }
            catch (Exception e)
            {
                respuesta.MESSAGE = "no se pudo enviar mensaje: " + e.Message;
                respuesta.STATUS  = false;
                return(respuesta);
            }
        }
Exemplo n.º 14
0
        private static void ProcessRequest(TcpListener tcpListener)
        {
            Console.WriteLine("Processing...");
            var        tcpClient = tcpListener.AcceptTcpClient();
            var        netStream = tcpClient.GetStream();
            BigInteger ga        = null;

            byte[]     newNonce       = new byte[32];
            BigInteger a              = new BigInteger(2048, new Random());
            var        dhPrime        = new BigInteger("00C150023E2F70DB7985DED064759CFECF0AF328E69A41DAF4D6F01B538135A6F91F8F8B2A0EC9BA9720CE352EFCF6C5680FFC424BD634864902DE0B4BD6D49F4E580230E3AE97D95C8B19442B3C0A10D8F5633FECEDD6926A7F6DAB0DDB7D457F9EA81B8465FCD6FFFEED114011DF91C059CAEDAF97625F6C96ECC74725556934EF781D866B34F011FCE4D835A090196E9A5F0E4449AF7EB697DDB9076494CA5F81104A305B6DD27665722C46B60E5DF680FB16B210607EF217652E60236C255F6A28315F4083A96791D7214BF64C1DF4FD0DB1944FB26A2A57031B32EEE64AD15A8BA68885CDE74A5BFC920F6ABF59BA5C75506373E7130F9042DA922179251F", 16);
            BigInteger gb             = null;
            var        sequenceNumber = 1;
            ulong?     messageId      = null;
            var        privateKey     = new BigInteger("582A4D5EE3A45C1AEEBDECD549D1FD4E12337B05C4C0A03FA8FF4A0A7B2861BAB86E8B58A70AAB9CF173FA313348239E28B17D34C7CEC8B68544BAD8623A306D747B7DC1D3D064FA73CE96893E8AFC36F7CDF58A383F48BDEC284D30BFFBC3F1A413DC869B3692EDD26004EE661C021BDA32F124D6631C67891E3E35EEDEAA08BFED8DBB7A6CC1D550CF16C67703BBDFFF0500FD81A55F98D92ECD67CE3CC31B766EA0DFBA284E18677E46036D9ED04105AAD11E97FD675F49A3B54D5AD395AA3C5B8343CDFF70C2E2A9243A47FBC5F541BBAE910B5DD1BF574B1E732A105C2B8F5239A4DFA0BCE0559F18BA0C44D31A279FA7CDCA612BD8F9796EBD114F7FA9", 16);
            AuthKey    authKey        = null;

            //var getingCounter = 0;
            //while (true)
            //{
            //    if (!netStream.DataAvailable)
            //        continue;
            //    Console.WriteLine("Get data " + ++getingCounter);
            //}

            while (tcpClient.Connected)
            {
                System.Threading.Thread.Sleep(100);
                if (!netStream.DataAvailable)
                {
                    continue;
                }

                byte[] nonceFromClient = new byte[16];
                byte[] servernonce     = new byte[16];

                uint responseCode  = 0;
                int  innerCode     = 0;
                long authkeysample = 123456789;

                const long step1Constructor = 0x60469778;
                const long step2Constructor = 0xd712e4be;
                const long step3Constructor = 0xf5045f1f;

                if (netStream.CanRead)
                {
                    var bytes = new byte[tcpClient.ReceiveBufferSize];
                    netStream.Read(bytes, 0, (int)tcpClient.ReceiveBufferSize);
                    var tcpMessage   = TcpMessage.Decode(bytes);
                    var binaryReader = new BinaryReader(new MemoryStream(tcpMessage.Body, false));


                    var authKeyId = binaryReader.ReadInt64();
                    if (authKeyId == 0)
                    {
                        var msgId      = binaryReader.ReadInt64();
                        var datalength = binaryReader.ReadInt32();
                        var data       = binaryReader.ReadBytes(datalength);

                        var binaryReader2 = new BinaryReader(new MemoryStream(data, false));

                        responseCode = binaryReader2.ReadUInt32();
                        Console.WriteLine("Request code: " + responseCode);
                        if (responseCode == step1Constructor) //---Step1_PQRequest
                        {
                            nonceFromClient = binaryReader2.ReadBytes(16);
                        }
                        else if (responseCode == step2Constructor) //---Step1_PQRequest
                        {
                            nonceFromClient = binaryReader2.ReadBytes(16);
                            servernonce     = binaryReader2.ReadBytes(16);
                            var p = binaryReader2.ReadBytes(4);
                            var q = binaryReader2.ReadBytes(8);
                            var targetFingerprint = BitConverter.ToString(binaryReader2.ReadBytes(8)).Replace("-", string.Empty);

                            //TODO: need to decryption
                            var ciphertext = Bytes.read(binaryReader2);
                            ciphertext = RSA.Decrypt(targetFingerprint, ciphertext, privateKey, 0, ciphertext.Length);
                            var cipherReader    = new BinaryReader(new MemoryStream(ciphertext, false));
                            var hashsum         = cipherReader.ReadBytes(20);
                            var innercode       = cipherReader.ReadUInt32();//0x83c95aec
                            var pq              = cipherReader.ReadBytes(20);
                            var noncetemp       = cipherReader.ReadBytes(16);
                            var servernoncetemp = cipherReader.ReadBytes(16);
                            newNonce = cipherReader.ReadBytes(32);
                            //Array.Copy(ciphertext, ciphertext.Length - 32, newNonce, 0, 32);
                            //ciphertext.CopyTo(newnoncetemp, ciphertext.Length - 32);
                        }
                        else if (responseCode == step3Constructor) //---Step1_PQRequest
                        {
                            nonceFromClient = binaryReader2.ReadBytes(16);
                            servernonce     = binaryReader2.ReadBytes(16);

                            //TODO: need to decryption
                            var        ciphertext                = Bytes.read(binaryReader2);
                            AESKeyData key                       = AES.GenerateKeyDataFromNonces(servernonce, newNonce);
                            var        cleartext                 = AES.DecryptAES(key, ciphertext);
                            var        binaryReadernner          = new BinaryReader(new MemoryStream(cleartext, false));
                            var        hasheddata                = binaryReadernner.ReadBytes(20);
                            var        client_dh_inner_data_code = binaryReadernner.ReadUInt32();
                            if (client_dh_inner_data_code != 0x6643b654)
                            {
                                throw new Exception("We have a complex story");
                            }
                            var nonceFromClient_temp = binaryReadernner.ReadBytes(16);
                            var servernonce_temp     = binaryReadernner.ReadBytes(16);
                            var zero = binaryReadernner.ReadUInt64();
                            gb = new BigInteger(Bytes.read(binaryReadernner));
                        }
                    }
                    else
                    {
                        var _gba = gb.ModPow(a, dhPrime);
                        authKey = new AuthKey(_gba);
                        var decodeMessage = DecodeMessage(tcpMessage.Body, authKey);
                        var objrawReader  = new BinaryReader(new MemoryStream(decodeMessage.Item1, false));
                        messageId = decodeMessage.Item2;
                        innerCode = objrawReader.ReadInt32();


                        if (innerCode == 0x62d6b459)//acknowledged
                        {
                            var vector   = objrawReader.ReadInt32();
                            var msgCount = objrawReader.ReadInt32();
                            continue;
                        }
                        else //if (responseCode == -627372787)
                        {
                            objrawReader.BaseStream.Position += -4;
                            var obj = ObjectUtils.DeserializeObject(objrawReader);
                            if (obj is TLRequestInvokeWithLayer)
                            {
                                var invokewithlayer = (TLRequestInvokeWithLayer)obj;
                                if (invokewithlayer.Query is TLRequestInitConnection)
                                {
                                    var requestInitConnection = (TLRequestInitConnection)invokewithlayer.Query;
                                }
                                else if (invokewithlayer.Query is TLRequestSendCode)
                                {
                                    var requestSendCode = (TLRequestSendCode)invokewithlayer.Query;
                                }
                            }
                            else if (obj is TLRequestSendCode)
                            {
                                var requestSendCode = (TLRequestSendCode)obj;
                            }
                            else if (obj is TLRequestSignIn)
                            {
                                var requestSignIn = (TLRequestSignIn)obj;
                            }
                            else if (obj is TLRequestGetContacts)
                            {
                                var requestGetContacts = (TLRequestGetContacts)obj;
                            }
                        }

                        //var keyData = Helpers.CalcKey(buffer, messageKey, false);
                        //var data = AES.DecryptAES(keyData, buffer);
                    }
                }

                if (netStream.CanWrite)
                {
                    var fingerprint = StringToByteArray("216be86c022bb4c3");

                    byte[] outputdata = null;
                    if (responseCode == step1Constructor)
                    {
                        var nonce = new byte[16];
                        new Random().NextBytes(nonce);
                        outputdata = new Step1_Response()
                        {
                            Pq           = new BigInteger(1, BitConverter.GetBytes(880)),
                            ServerNonce  = nonceFromClient,
                            Nonce        = nonce,
                            Fingerprints = new List <byte[]>()
                            {
                                fingerprint
                            }
                        }.ToBytes();
                    }
                    else if (responseCode == step2Constructor)
                    {
                        //var nonce = new byte[16];
                        //new Random().NextBytes(nonce);

                        byte[]     answer;
                        var        hashsum       = Encoding.UTF8.GetBytes("asdfghjklmnbvcxzasdf");
                        const uint innerCodetemp = 0xb5890dba;
                        AESKeyData key           = AES.GenerateKeyDataFromNonces(servernonce, newNonce);

                        var g = 47;
                        ga = BigInteger.ValueOf(g).ModPow(a, dhPrime);

                        using (var memoryStream = new MemoryStream())
                        {
                            using (var binaryWriter = new BinaryWriter(memoryStream))
                            {
                                binaryWriter.Write(hashsum);
                                binaryWriter.Write(innerCodetemp);
                                binaryWriter.Write(nonceFromClient);
                                binaryWriter.Write(servernonce);
                                binaryWriter.Write(g);
                                Bytes.write(binaryWriter, dhPrime.ToByteArrayUnsigned());
                                Bytes.write(binaryWriter, ga.ToByteArrayUnsigned());
                                Bytes.write(binaryWriter, BitConverter.GetBytes((int)(Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds) / 1000)));//server datetime
                                answer = memoryStream.ToArray();
                            }
                        }

                        outputdata = new Step2_Response()
                        {
                            ServerNonce     = nonceFromClient,
                            Nonce           = servernonce,
                            NewNonce        = newNonce,
                            EncryptedAnswer = AES.EncryptAES(key, answer)
                        }.ToBytes();
                    }
                    else if (responseCode == step3Constructor)
                    {
                        var _gba = gb.ModPow(a, dhPrime);
                        authKey = new AuthKey(_gba);
                        var        newNonceHash  = authKey.CalcNewNonceHash(newNonce, 1);
                        const uint innerCodeTemp = 0x3bcbf734;
                        using (var memoryStream = new MemoryStream())
                        {
                            using (var binaryWriter = new BinaryWriter(memoryStream))
                            {
                                binaryWriter.Write(innerCodeTemp);
                                binaryWriter.Write(servernonce);
                                binaryWriter.Write(nonceFromClient);
                                binaryWriter.Write(newNonceHash);//hashnewnonce
                                outputdata = memoryStream.ToArray();
                            }
                        }
                    }
                    else if (innerCode == -2035355412)//TLRequestSendCode
                    {
                        #region Generate TLSentCode

                        var sentCode = new TLSentCode();
                        sentCode.PhoneRegistered = false;
                        sentCode.Timeout         = 7777;
                        sentCode.PhoneCodeHash   = "asdfghjklmnbvcxzasdf";
                        sentCode.Flags           = 3;
                        sentCode.NextType        = new TLCodeTypeSms();
                        sentCode.Type            = new TLSentCodeTypeApp()
                        {
                            Length = 20
                        };

                        #endregion

                        using (var memoryStream = new MemoryStream())
                        {
                            using (var binaryWriter = new BinaryWriter(memoryStream))
                            {
                                binaryWriter.Write(0xf35c6d01);      //main code
                                binaryWriter.Write(messageId.Value); //requestId -- ulong -- from mesage id
                                sentCode.SerializeBody(binaryWriter);
                                outputdata = memoryStream.ToArray();
                            }
                        }
                    }
                    else if (innerCode == -627372787)
                    {
                        #region Generate TLConfig
                        //---Genrate mock tlconfig
                        var config = new TLConfig();
                        config.CallConnectTimeoutMs = 7777;
                        config.CallPacketTimeoutMs  = 7777;
                        config.CallReceiveTimeoutMs = 7777;
                        config.CallRingTimeoutMs    = 7777;
                        config.ChatBigSize          = 7777;
                        config.ChatSizeMax          = 777;
                        config.Date      = Convert.ToInt32((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds);
                        config.DcOptions = new TLVector <TLDcOption>()
                        {
                            new TLDcOption()
                            {
                                Flags = 0, Id = 1, IpAddress = "127.0.0.1", Port = 5000
                            }
                        };
                        config.DisabledFeatures      = new TLVector <TLDisabledFeature>();
                        config.ForwardedCountMax     = 777;
                        config.MegagroupSizeMax      = 777;
                        config.NotifyCloudDelayMs    = 7777;
                        config.NotifyDefaultDelayMs  = 7777;
                        config.OfflineBlurTimeoutMs  = 7777;
                        config.OfflineIdleTimeoutMs  = 7777;
                        config.OnlineCloudTimeoutMs  = 7777;
                        config.OnlineUpdatePeriodMs  = 7777;
                        config.PhonecallsEnabled     = false;
                        config.PinnedDialogsCountMax = 7;
                        config.PushChatLimit         = 7;
                        config.PushChatPeriodMs      = 777;
                        config.RatingEDecay          = 777;
                        config.SavedGifsLimit        = 777;
                        config.StickersRecentLimit   = 777;
                        config.ThisDc      = 1;//TODO: ---what's this?!---
                        config.MeUrlPrefix = "https://t.me/";
                        config.TestMode    = false;
                        #endregion

                        using (var memoryStream = new MemoryStream())
                        {
                            using (var binaryWriter = new BinaryWriter(memoryStream))
                            {
                                binaryWriter.Write(0xf35c6d01);      //main code
                                                                     //binaryWriter.Write(0xf35c6d02);//code
                                binaryWriter.Write(messageId.Value); //requestId -- ulong -- from mesage id
                                                                     //binaryWriter.Write(0x2144ca17);//innercode -- int
                                                                     //binaryWriter.Write(1123456789);//sample code
                                                                     //Serializers.Bytes.write(binaryWriter, config.Serialize());
                                config.SerializeBody(binaryWriter);
                                outputdata = memoryStream.ToArray();
                            }
                        }
                    }
                    else if (innerCode == -1126886015)
                    {
                        #region Generate TLAuthorization

                        var auth = new TeleSharp.TL.Auth.TLAuthorization();
                        auth.Flags = 3;
                        auth.User  = new TLUser()
                        {
                            FirstName = "Meysami"
                        };

                        #endregion

                        using (var memoryStream = new MemoryStream())
                        {
                            using (var binaryWriter = new BinaryWriter(memoryStream))
                            {
                                binaryWriter.Write(0xf35c6d01);      //main code
                                binaryWriter.Write(messageId.Value); //requestId -- ulong -- from mesage id
                                auth.SerializeBody(binaryWriter);
                                outputdata = memoryStream.ToArray();
                            }
                        }
                    }
                    else if (innerCode == 583445000)//GetContacts
                    {
                        #region Generate TLAbsContacts

                        var contacts = new TLContacts();
                        contacts.Contacts = new TLVector <TLContact>()
                        {
                            new TLContact()
                            {
                                UserId = 11
                            },
                            new TLContact()
                            {
                                UserId = 12
                            }
                        };
                        contacts.Users = new TLVector <TLAbsUser>()
                        {
                            new TLUser()
                            {
                                Bot = false, FirstName = "Mary", Id = 11
                            },
                            new TLUser()
                            {
                                Bot = false, FirstName = "Mary 2", Id = 12
                            }
                        };

                        #endregion

                        using (var memoryStream = new MemoryStream())
                        {
                            using (var binaryWriter = new BinaryWriter(memoryStream))
                            {
                                binaryWriter.Write(0xf35c6d01);      //main code
                                binaryWriter.Write(messageId.Value); //requestId -- ulong -- from mesage id
                                contacts.SerializeBody(binaryWriter);
                                outputdata = memoryStream.ToArray();
                            }
                        }
                    }
                    else
                    {
                        continue;
                    }

                    if (innerCode != 0)
                    {
                        outputdata = PrepareToSend2(outputdata, authKey.Id, 0, 0, 0, servernonce, sequenceNumber, authKey);
                    }
                    else
                    {
                        outputdata = PrepareToSend(outputdata);
                    }

                    outputdata = Encode(outputdata, sequenceNumber++);
                    netStream.Write(outputdata, 0, outputdata.Length);
                }
                else
                {
                    Console.WriteLine("You cannot write data to this stream.");
                    tcpClient.Close();
                    netStream.Close();
                }
            }
        }
Exemplo n.º 15
0
 public TLSharpMessenger(TelegramClient client)
 {
     _client   = client;
     _contacts = _client.GetContactsAsync().Sync();
 }