Esempio n. 1
0
 public SearchSegmentResult()
 {
     AuthKey  = new AuthKey();
     Status   = string.Empty;
     Reason   = string.Empty;
     Segments = new List <Segment.Segment>();
 }
        public override void OnResponse(NetState state, RelayInfo info)
        {
            if (info.ButtonID != 1)
            {
                return;
            }

            string email = AccountManagement.GetEMail(m_Account);

            if (email == null)
            {
                email = "-null-";
            }

            AuthKey ak = AccountManagement.MakeKey(m_Account, AuthType.EMail, null);

            m_Mobile.SendMessage("An e-mail has been dispatched to {0} with detailed instructions on how to finalize your request.", email);
            m_Mobile.SendMessage("Your request will expire in {0} hours.", AuthKey.KeyExpire.Hours);

            //MailMessage mm = new MailMessage( "UOGamers Account Manager <*****@*****.**>", email );
            MailMessage mm = new MailMessage();

            mm.From    = "UOGamers Account Manager <*****@*****.**>";
            mm.To      = email;
            mm.Subject = "UOGamers Account Management";
            mm.Body    = String.Format(
                "{0},\n\tYou have requested to release this e-mail address from your account. To finalize this request, you must enter the following string (while in game) exactly as it appears.\n\n[auth {1}\n\nThis key will expire at {2}. If you have any questions, comments, suggestions, or require assistance, please do not hesitate to page or visit our forums at http://www.uogamers.com/forum\n\n\tThank you,\n\t\tThe UOGamers Administration Team\n\t\thttp://www.uogamers.com\n\n\nThis message is not spam. This request was initiated by {3}. If you feel you received this message in error, please disregard it.", m_Mobile.Name, ak.Key, ak.Expiration, state.ToString());

            Email.AsyncSend(mm);
        }
Esempio n. 3
0
        public static Session Deserialize(BinaryReader br)
        {
            var version = TgMarshal.ReadInt(br);

            if (version != Version)
            {
                throw new TgInternalException($"Invalid session file version, got {version}, expected {Version}.", None);
            }

            var apiId         = TgMarshal.ReadInt(br);
            var id            = TgMarshal.ReadLong(br);
            var sequence      = TgMarshal.ReadInt(br);
            var salt          = TgMarshal.ReadLong(br);
            var lastMessageId = TgMarshal.ReadLong(br);
            var timeOffset    = TgMarshal.ReadInt(br);

            var serverAddress = TgMarshal.ReadBytes(br).ToArrayUnsafe().Apply(bts => new IPAddress(bts));
            var port          = TgMarshal.ReadInt(br);
            var ep            = new IPEndPoint(serverAddress, port);

            var authData     = TgMarshal.ReadBytes(br);
            var isAuthorized = TgMarshal.ReadBool(br);

            return(new Session(
                       apiId: apiId,
                       id: id,
                       salt: salt,
                       sequence: sequence,
                       lastMessageId: lastMessageId,
                       timeOffset: timeOffset,
                       endpoint: ep,
                       authKey: AuthKey.Deserialize(authData),
                       isAuthorized: isAuthorized
                       ));
        }
Esempio n. 4
0
        private static Tuple <byte[], ulong, int> DecodeMessage(byte[] body, AuthKey authkey)
        {
            byte[] message;
            ulong  remoteMessageId;
            int    remoteSequence;

            using (var inputStream = new MemoryStream(body))
                using (var inputReader = new BinaryReader(inputStream))
                {
                    if (inputReader.BaseStream.Length < 8)
                    {
                        throw new InvalidOperationException($"Can't decode packet");
                    }

                    ulong      remoteAuthKeyId = inputReader.ReadUInt64();  // TODO: check auth key id
                    byte[]     msgKey          = inputReader.ReadBytes(16); // TODO: check msg_key correctness
                    AESKeyData keyData         = Helpers.CalcKey(authkey.Data, msgKey, true);
                    //TODO: return to decryption
                    var    cipherText = inputReader.ReadBytes((int)(inputStream.Length - inputStream.Position));
                    byte[] plaintext  = AES.DecryptAES(keyData, cipherText);
                    //byte[] plaintext = inputReader.ReadBytes((int)(inputStream.Length - inputStream.Position));

                    using (MemoryStream plaintextStream = new MemoryStream(plaintext))
                        using (BinaryReader plaintextReader = new BinaryReader(plaintextStream))
                        {
                            var remoteSalt      = plaintextReader.ReadUInt64();
                            var remoteSessionId = plaintextReader.ReadUInt64();
                            remoteMessageId = plaintextReader.ReadUInt64();
                            remoteSequence  = plaintextReader.ReadInt32();
                            int msgLen = plaintextReader.ReadInt32();
                            message = plaintextReader.ReadBytes(msgLen);
                        }
                }
            return(new Tuple <byte[], ulong, int>(message, remoteMessageId, remoteSequence));
        }
Esempio n. 5
0
        public AuthResponse Auth(AuthRequest request)
        {
            AuthResponse response = new AuthResponse();

            response.Errors     = new List <string>();
            response.StatusCode = 200;
            User user = _userRepository.GetUserByEmail(request.Email);

            if (user == null)
            {
                response.StatusCode = 400;
                response.Errors.Add("Account does not exist");
                return(response);
            }
            if (SHAHasher.ComputeSha256Hash(user.PasswordHash + request.Password) != user.PasswordHashed)
            {
                response.StatusCode = 400;
                response.Errors.Add("Passwords do not match");
            }
            if (response.StatusCode != 200)
            {
                return(response);
            }

            AuthKey authkey = _authKeyRepository.GenerateAuthKey(request.Email, request.Password);

            response.StatusCode = 200;
            response.AuthKey    = authkey.Key;
            response.UserId     = authkey.UserId;
            return(response);
        }
Esempio n. 6
0
            public override bool Equals(object obj)
            {
                if (this == obj)
                {
                    return(true);
                }
                AuthKey authKey = obj as AuthKey;

                if (authKey == null)
                {
                    return(false);
                }
                if (!Equals(_username, authKey._username))
                {
                    return(false);
                }
                if (!Equals(_password, authKey._password))
                {
                    return(false);
                }
                if (!Equals(_service, authKey._service))
                {
                    return(false);
                }
                return(true);
            }
Esempio n. 7
0
        public ActionResult PostData(ClientVendorModel model)
        {
            string  clientName = model.client;
            string  vendorName = model.vendor;
            AuthKey authKey    = new AuthKey();

            //WordDoc wordDoc = new WordDoc();
            //wordDoc.CreateSampleDocument();

            if (vendorName != null)
            {
                Client client = new Client();
                Vendor vendor = new Vendor();

                ClientVendor clientVendor = new ClientVendor();
                client.FindClient(clientName);
                vendor.FindVendor(vendorName);
                clientVendor.CreateClientVendorRel(client, vendor, authKey);
                model.vendor       = vendorName;
                model.client       = clientName;
                model.authKey      = authKey.UniqueIdentifier;
                Session["Client"]  = clientName;
                Session["Vendor"]  = vendorName;
                Session["AuthKey"] = authKey.UniqueIdentifier;

                return(new JsonResult()
                {
                    Data = new { Success = true }
                });
            }

            return(View());
        }
Esempio n. 8
0
        public AuthResponse Auth(AuthRequest request)
        {
            AuthResponse response = new AuthResponse();

            response.Errors  = new List <string>();
            response.Success = true;
            Account account = _accountRepository.GetAccountByEmail(request.Email);

            if (account == null)
            {
                response.Success = false;
                response.Errors.Add("Account does not exist");
                return(response);
            }
            if (SHAHasher.ComputeSha256Hash(account.PasswordHash + request.Password) != account.PasswordHashed)
            {
                response.Success = false;
                response.Errors.Add("Passwords do not match");
            }
            if (!response.Success)
            {
                return(response);
            }

            AuthKey authkey = _authKeyRepository.GenerateAuthKey(request.Email, request.Password);

            response.Success   = true;
            response.AuthKey   = authkey.Key;
            response.AccountId = authkey.AccountId;
            return(response);
        }
Esempio n. 9
0
        protected string AuthKeySignature(byte[] authKey)
        {
            if (authKey == null || authKey.Length == 0)
            {
                return("null");
            }

            return(string.Join(" ", AuthKey.Take(7).ToArray()));
        }
Esempio n. 10
0
 public void ResetAuth()
 {
     lock (generateSyncRoot)
     {
         authKey        = null;
         user           = null;
         sessionExpires = 0;
     }
 }
Esempio n. 11
0
        public static async Task <Step3Res> Do(
            ServerDhParams.OkTag dhParams,
            Int256 newNonce,
            MtProtoPlainTransport transport
            )
        {
            var key             = Aes.GenerateKeyDataFromNonces(dhParams.ServerNonce.ToBytes(true), newNonce.ToBytes(true));
            var plaintextAnswer = Aes.DecryptAES(key, dhParams.EncryptedAnswer.ToArrayUnsafe());
            var dh = plaintextAnswer.Apply(Deserialize(WithHashSumCheck(ServerDhInnerData.Deserialize)));

            Helpers.Assert(dh.Nonce == dhParams.Nonce, "auth step3: invalid nonce in encrypted answer");
            Helpers.Assert(dh.ServerNonce == dhParams.ServerNonce, "auth step3: invalid server nonce in encrypted answer");

            var currentEpochTime = Helpers.GetCurrentEpochTime();
            var timeOffset       = dh.ServerTime - currentEpochTime;

            var g       = dh.G;
            var dhPrime = new BigInteger(1, dh.DhPrime.ToArrayUnsafe());
            var ga      = new BigInteger(1, dh.Ga.ToArrayUnsafe());

            var b   = new BigInteger(Rnd.NextBytes(2048));
            var gb  = BigInteger.ValueOf(g).ModPow(b, dhPrime);
            var gab = ga.ModPow(b, dhPrime);

            var dhInnerData = new ClientDhInnerData(
                nonce: dh.Nonce,
                serverNonce: dh.ServerNonce,
                retryId: 0,
                gb: gb.ToByteArrayUnsigned().ToBytesUnsafe()
                );
            var dhInnerDataBts = Serialize(dhInnerData);

            var dhInnerDataHashedBts            = WithHashAndPadding(dhInnerDataBts);
            var dhInnerDataHashedEncryptedBytes = Aes.EncryptAES(key, dhInnerDataHashedBts);

            var resp = await transport.Call(new SetClientDhParams(
                                                nonce : dh.Nonce,
                                                serverNonce : dh.ServerNonce,
                                                encryptedData : dhInnerDataHashedEncryptedBytes.ToBytesUnsafe()
                                                )).ConfigureAwait(false);

            var res = resp.Match(
                dhGenOkTag: x => x,
                dhGenFailTag: _ => throw Helpers.FailedAssertion("auth step3: dh_gen_fail"),
                dhGenRetryTag: _ => throw Helpers.FailedAssertion("auth step3: dh_gen_retry")
                );

            var authKey      = AuthKey.FromGab(gab);
            var newNonceHash = authKey.CalcNewNonceHash(newNonce.ToBytes(true), 1).ToInt128();

            Helpers.Assert(res.Nonce == dh.Nonce, "auth step3: invalid nonce");
            Helpers.Assert(res.ServerNonce == dh.ServerNonce, "auth step3: invalid server nonce");
            Helpers.Assert(res.NewNonceHash1 == newNonceHash, "auth step3: invalid new nonce hash");

            return(new Step3Res(authKey, timeOffset));
        }
Esempio n. 12
0
        public async Task <IActionResult> Handle(HttpRequest request, EnterSsRequest data)
        {
            AuthByKeyResult authResult = this.GetAuthenticationKey(request);

            if (!authResult.Result)
            {
                return(new JsonErrorResult(authResult.ErrorResponse));
            }

            ErrorResponse validationError = this.ValidateRequest(data);

            if (validationError != null)
            {
                return(new JsonErrorResult(validationError));
            }

            byte[] securedKey = Guid.NewGuid().ToByteArray();

            try
            {
                using (SqlConnection conn = sqlServer.GetConnection())
                {
                    await conn.OpenAsync();

                    using (SqlCommand cmd = sqlServer.GetSpCommand("dbo.Employee_EnterSecuredSession", conn))
                    {
                        cmd.AddBinaryParam("@PermanentKey", 16, authResult.Key.ToArray());
                        cmd.AddBinaryParam("@SecuredKey", 16, securedKey);
                        cmd.AddCharParam("@Phone", 10, data.Phone);
                        cmd.AddCharParam("@PinCode", 4, data.PinCode);

                        SqlParameter retValParam = cmd.AddReturnValue();

                        await cmd.ExecuteNonQueryAsync();

                        int retVal = retValParam.GetInt32OrDefault();
                        if (retVal < 0)
                        {
                            ErrorResponse errorResponse = this.GetErrorResponse(retVal);
                            return(new JsonErrorResult(errorResponse));
                        }

                        EnterSsResponse response = new EnterSsResponse();
                        response.SecuredKey = AuthKey.Create(securedKey).ToString() + authResult.Key.ToString();
                        return(new JsonResult(response));
                    }
                }
            }
            catch (Exception ex)
            {
                return(new JsonErrorResult(this.GetExceptionResponse(ex)));
            }
        }
Esempio n. 13
0
 internal Session(ulong id, AuthKey authKey, int sequence, ulong salt, int timeOffset, long lastMessageId, int expires, TLUser user, DataCenter dc)
 {
     this.Id        = id;
     AuthKey        = authKey;
     Sequence       = sequence;
     Salt           = salt;
     TimeOffset     = timeOffset;
     LastMessageId  = lastMessageId;
     SessionExpires = expires;
     TLUser         = user;
     DataCenter     = dc;
 }
Esempio n. 14
0
 public override bool Equals(object obj)
 {
     if (obj == this) return true;
     RecommandKey key = obj as RecommandKey;
     if (key == null) return false;
     AuthKey authkey = new AuthKey() { Auth = key.Auth, PlatForm = key.PlatForm };
     if (PlatFormCache.Instance.AuthItems.ContainsKey(authkey))
         return key.PlatForm == PlatForm && key.Mode == Mode && key.NavId == NavId && PlatFormCache.Instance.AuthItems[authkey] == Auth;
     key.Auth = null;
     key.PlatForm = authkey.PlatForm;
     return key.PlatForm == PlatForm && key.Mode == Mode && key.NavId == NavId && key.Auth == Auth;
 }
Esempio n. 15
0
        public override void OnResponse(NetState state, RelayInfo info)
        {
            if (info.ButtonID != 1)
            {
                return;
            }

            TextRelay emailEntry   = info.GetTextEntry(0);
            TextRelay confirmEntry = info.GetTextEntry(1);

            string email   = (emailEntry == null ? null : emailEntry.Text.Trim());
            string confirm = (confirmEntry == null ? null : confirmEntry.Text.Trim());

            if (email == null || email.Length == 0)
            {
                m_Mobile.SendMessage("Registration cancelled.");
            }
            else if (email != confirm)
            {
                m_Mobile.SendMessage("You must confirm your e-mail address entry. Both fields must match exactly. Try again.");
                m_Mobile.SendGump(new LinkAddressGump(m_Mobile, m_Account));
            }

            /*else if ( !Email..IsValid( email ) )
             * {
             *      m_Mobile.SendMessage( "You have specified an invalid e-mail address. Verify the address and try again." );
             *      m_Mobile.SendGump( new LinkAddressGump( m_Mobile, m_Account ) );
             * }*/
            else
            {
                try
                {
                    AuthKey ak = AccountManagement.MakeKey(m_Account, AuthType.Register, email);
                    m_Mobile.SendMessage("An e-mail has been dispatched to {0} with detailed instructions on how to finalize your registration.", email);
                    m_Mobile.SendMessage("Your registration request will expire in {0} hours.", AuthKey.KeyExpire.Hours);

                    //MailMessage mm = new MailMessage( "UOGamers Account Manager <*****@*****.**>", email );
                    MailMessage mm = new MailMessage();
                    mm.From    = "UOGamers Account Manager <*****@*****.**>";
                    mm.To      = email;
                    mm.Subject = "UOGamers Account Management";
                    mm.Body    = String.Format(
                        "{0},\n\tThank you for registering this e-mail address with your UOGamers account. This will allow you to change your password (among other things) securely without Game Master assistance. To finalize your registration, you must enter the following string (while in game) exactly as it appears.\n\n[auth {1}\n\nThis key will expire at {2}. If you have any questions, comments, suggestions, or require assistance, please do not hesitate to page or visit our forums at http://www.uogamers.com/forum\n\n\tThank you,\n\t\tThe UOGamers Administration Team\n\t\thttp://www.uogamers.com\n\n\nThis message is not spam. This registration request was initiated by {3}. If you feel you received this message in error, please disregard it.", m_Mobile.Name, ak.Key, ak.Expiration, state.ToString());

                    Email.AsyncSend(mm);
                }
                catch
                {
                    m_Mobile.SendMessage("There was an error, please try again in a few hours.");
                }
            }
        }
Esempio n. 16
0
            public override bool Equals(object obj)
            {
                if (obj == null)
                {
                    return(false);
                }

                if (this.GetType() != obj.GetType())
                {
                    return(false);
                }

                // safe because of the GetType check
                AuthKey key = (AuthKey)obj;

                // use this pattern to compare reference members
                if (!Object.Equals(_role, key._role))
                {
                    return(false);
                }
                if (!Object.Equals(_right, key._right))
                {
                    return(false);
                }

                // use this pattern to compare value members
                if (!_role.Equals(key._role))
                {
                    return(false);
                }
                if (!_right.Equals(key._right))
                {
                    return(false);
                }

                // '*' allow all action
                if (_action.Equals("*"))
                {
                    return(true);
                }

                if (!Object.Equals(_action, key._action))
                {
                    return(false);
                }
                if (!_action.Equals(key._action))
                {
                    return(false);
                }

                return(true);
            }
Esempio n. 17
0
 public HttpConnector()
 {
     try
     {
         string sr = File.ReadAllText(_authFile);
         Console.WriteLine(sr);
         authKey = JsonConvert.DeserializeObject <AuthKey>(File.ReadAllText(_authFile));
     }
     catch
     {
         Console.WriteLine("Misslyckades läsa in {0} filen korrekt", _authFile);
     }
 }
Esempio n. 18
0
        public static void AddKey(string name, string seed)
        {
            // sha the user input string
            SHA256Managed signit  = new SHA256Managed();
            var           shauser = signit.ComputeHash(Encoding.UTF8.GetBytes(seed));

            Array.Resize(ref shauser, 32);

            Keys[name] = new AuthKey()
            {
                Key = shauser, Name = name
            };
        }
Esempio n. 19
0
        public static void AddKey(string name, string seed)
        {
            // sha the user input string
            using (SHA256CryptoServiceProvider signit = new SHA256CryptoServiceProvider())
            {
                var shauser = signit.ComputeHash(Encoding.UTF8.GetBytes(seed));
                Array.Resize(ref shauser, 32);

                Keys[name] = new AuthKey()
                {
                    Key = shauser, Name = name
                };
            }
        }
Esempio n. 20
0
        public async Task <IActionResult> Handle(RegisterRequest data)
        {
            ErrorResponse validationError = this.ValidateRequest(data);

            if (validationError != null)
            {
                return(new JsonErrorResult(validationError));
            }

            try
            {
                byte[] permanentKey = Guid.NewGuid().ToByteArray();

                using (SqlConnection conn = sqlServer.GetConnection())
                {
                    await conn.OpenAsync();

                    using (SqlCommand cmd = sqlServer.GetSpCommand("Employee_Register", conn))
                    {
                        cmd.AddNVarCharParam("@FirstName", 50, data.FirstName);
                        cmd.AddNVarCharParam("@LastName", 50, data.LastName);
                        cmd.AddCharParam("@Phone", 10, data.Phone);
                        cmd.AddCharParam("@PinCode", 4, data.PinCode);
                        cmd.AddUniqueIdentifierParam("@LinkParameter", data.LinkParameter);
                        cmd.AddIntParam("@PlaceId", data.PlaceToJoinId);
                        cmd.AddBinaryParam("@PermanentKey", 16, permanentKey);
                        SqlParameter retValParam = cmd.AddReturnValue();

                        await cmd.ExecuteNonQueryAsync();

                        int retVal = retValParam.GetInt32OrDefault();
                        if (retVal < 0)
                        {
                            ErrorResponse errorResponse = this.GetErrorResponse(retVal);
                            return(new JsonErrorResult(errorResponse));
                        }
                    }
                }

                RegisterResponse response = new RegisterResponse();
                response.PermanentKey = AuthKey.Create(permanentKey).ToString();
                return(new JsonResult(response));
            }
            catch (Exception ex)
            {
                return(new JsonErrorResult(this.GetExceptionResponse(ex)));
            }
        }
        private static AuthKey ReadAuthKey(XmlReader xmlReader)
        {
            var authKey = new AuthKey();

            while (xmlReader.Read())
            {
                switch (xmlReader.NodeType)
                {
                case XmlNodeType.Element:
                    if (string.Compare(xmlReader.Name, "id", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        var readSubtree = xmlReader.ReadSubtree();
                        authKey.Id = ReadText(readSubtree);
                        readSubtree.Close();
                    }
                    else if (string.Compare(xmlReader.Name, "manage_url", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        var readSubtree = xmlReader.ReadSubtree();
                        authKey.ManageUrl = ReadText(readSubtree);
                        readSubtree.Close();
                    }
                    break;

                case XmlNodeType.Whitespace:
                    //not required for this implementation
                    break;

                case XmlNodeType.Text:
                    //not required for this implementation
                    break;

                case XmlNodeType.CDATA:
                    //not required for this implementation
                    break;

                case XmlNodeType.EntityReference:
                    //not required for this implementation
                    break;

                case XmlNodeType.EndElement:
                    //not required for this implementation
                    break;
                }
            }
            return(authKey);
        }
Esempio n. 22
0
        public override void OnResponse(NetState state, RelayInfo info)
        {
            if (info.ButtonID != 1)
            {
                return;
            }

            TextRelay pwEntry      = info.GetTextEntry(0);
            TextRelay confirmEntry = info.GetTextEntry(1);

            string pw      = (pwEntry == null ? null : pwEntry.Text.Trim());
            string confirm = (confirmEntry == null ? null : confirmEntry.Text.Trim());

            if (pw == null || pw.Length == 0)
            {
                m_Mobile.SendMessage("Password change cancelled.");
            }
            else if (pw != confirm)
            {
                m_Mobile.SendMessage("You must confirm your password entry. Both fields must match exactly. Try again.");
                m_Mobile.SendGump(new ChangePasswordGump(m_Mobile, m_Account));
            }
            else
            {
                string email = AccountManagement.GetEMail(m_Account);
                if (email == null)
                {
                    email = "-null-";
                }

                AuthKey ak = AccountManagement.MakeKey(m_Account, AuthType.Password, pw);
                m_Mobile.SendMessage("An e-mail has been dispatched to {0} with detailed instructions on how to finalize your request.", email);
                m_Mobile.SendMessage("Your request will expire in {0} hours.", AuthKey.KeyExpire.Hours);

                //MailMessage mm = new MailMessage( "UOGamers Account Manager <*****@*****.**>", email );
                MailMessage mm = new MailMessage();
                mm.From    = "UOGamers Account Manager <*****@*****.**>";
                mm.To      = email;
                mm.Subject = "UOGamers Account Management";
                mm.Body    = String.Format(
                    "{0},\n\tYou have requested to change the password for account '{1}' to '{2}'. To finalize your request, you must enter the following string (while in game) exactly as it appears.\n\n[auth {3}\n\nThis key will expire at {4}. If you have any questions, comments, suggestions, or require assistance, please do not hesitate to page or visit our forums at http://www.uogamers.com/forum\n\n\tThank you,\n\t\tThe UOGamers Administration Team\n\t\thttp://www.uogamers.com\n\n\nThis message is not spam. This request was initiated by {5}. If you feel you received this message in error, please disregard it.", m_Mobile.Name, m_Account, pw, ak.Key, ak.Expiration, state.ToString());

                Email.AsyncSend(mm);
            }
        }
        public AuthKey GenerateAuthKey(string email, string password)
        {
            User user = _userRepository.GetUserByEmail(email);

            if (user == null)
            {
                return(null);
            }

            string  hash    = SHAHasher.ComputeSha256Hash(RandomStringGenerator.CreateString(256));
            AuthKey authKey = new AuthKey()
            {
                UserId = user.Id,
                Key    = hash
            };

            _appDbContext.AuthKeys.Add(authKey);
            _appDbContext.SaveChanges();
            return(authKey);
        }
Esempio n. 24
0
        public AuthKey GenerateAuthKey(string email, string password)
        {
            Account account = _accountRepository.GetAccountByEmail(email);

            if (account == null)
            {
                return(null);
            }

            string  hash    = SHAHasher.ComputeSha256Hash(RandomStringGenerator.CreateString(256));
            AuthKey authKey = new AuthKey()
            {
                AccountId = account.AccountId,
                Key       = hash
            };

            _appDbContext.AuthKeys.Add(authKey);
            _appDbContext.SaveChanges();
            return(authKey);
        }
Esempio n. 25
0
 public Session With(
     int?apiId           = null,
     long?id             = null,
     AuthKey authKey     = null,
     bool?isAuthorized   = null,
     int?sequence        = null,
     long?salt           = null,
     int?timeOffset      = null,
     long?lastMessageId  = null,
     IPEndPoint endpoint = null
     ) => new Session(
     apiId ?? ApiId,
     id ?? Id,
     authKey ?? AuthKey,
     isAuthorized ?? IsAuthorized,
     sequence ?? Sequence,
     salt ?? Salt,
     timeOffset ?? TimeOffset,
     lastMessageId ?? LastMessageId,
     endpoint ?? Endpoint
     );
Esempio n. 26
0
        public void read(BinaryReader reader)
        {
            int endpointCount = reader.ReadInt32();

            endpoints = new List <TelegramEndpoint>(endpointCount);
            for (int i = 0; i < endpointCount; i++)
            {
                endpoints.Add(new TelegramEndpoint(reader));
            }

            int keyExists = reader.ReadInt32();

            if (keyExists == 0)
            {
                authKey = null;
            }
            else
            {
                authKey = new AuthKey(Serializers.Bytes.read(reader));
            }

            //int fileSessionExists = reader.ReadInt32();
            //if(fileSessionExists == 0) {
            //    fileSession = null;
            //} else {
            //    fileSession = new TelegramFileSession(reader);
            //}

            int fileAuthExists = reader.ReadInt32();

            if (fileAuthExists == 0)
            {
                fileAuthorization = null;
            }
            else
            {
                fileAuthorization = (Auth_authorizationConstructor)TL.Parse <auth_Authorization>(reader);
            }
        }
Esempio n. 27
0
 public Session(
     int apiId,
     long id,
     AuthKey authKey,
     bool isAuthorized,
     int sequence,
     long salt,
     int timeOffset,
     long lastMessageId,
     IPEndPoint endpoint
     )
 {
     ApiId         = apiId;
     Id            = id;
     AuthKey       = authKey;
     IsAuthorized  = isAuthorized;
     Sequence      = sequence;
     Salt          = salt;
     TimeOffset    = timeOffset;
     LastMessageId = lastMessageId;
     Endpoint      = endpoint;
 }
Esempio n. 28
0
        public Step3_Response FromBytes(byte[] response)
        {
            using (MemoryStream responseStream = new MemoryStream(response))
            {
                using (BinaryReader responseReader = new BinaryReader(responseStream))
                {
                    uint code = responseReader.ReadUInt32();
                    if (code == 0x3bcbf734)
                    { // dh_gen_ok
                      //logger.debug("dh_gen_ok");


                        byte[] nonceFromServer = responseReader.ReadBytes(16);
                        // TODO

                        /*
                         *                      if (!nonceFromServer.SequenceEqual(nonce))
                         *                      {
                         *                              logger.error("invalid nonce");
                         *                              return null;
                         *                      }
                         */

                        byte[] serverNonceFromServer = responseReader.ReadBytes(16);

                        // TODO:

                        /*
                         *                      if (!serverNonceFromServer.SequenceEqual(serverNonce))
                         *                      {
                         *                              logger.error("invalid server nonce");
                         *                              return null;
                         *                      }
                         */

                        byte[] newNonceHash1 = responseReader.ReadBytes(16);
                        //logger.debug("new nonce hash 1: {0}", BitConverter.ToString(newNonceHash1));

                        AuthKey authKey = new AuthKey(_gab);

                        byte[] newNonceHashCalculated = authKey.CalcNewNonceHash(newNonce, 1);

                        if (!newNonceHash1.SequenceEqual(newNonceHashCalculated))
                        {
                            throw new InvalidOperationException("invalid new nonce hash");
                        }

                        //logger.info("generated new auth key: {0}", gab);
                        //logger.info("saving time offset: {0}", timeOffset);
                        //TelegramSession.Instance.TimeOffset = timeOffset;

                        return(new Step3_Response()
                        {
                            AuthKey = authKey,
                            TimeOffset = timeOffset
                        });
                    }
                    else if (code == 0x46dc1fb9)
                    { // dh_gen_retry
                        throw new NotImplementedException("dh_gen_retry");
                    }
                    else if (code == 0xa69dae02)
                    {
                        // dh_gen_fail
                        throw new NotImplementedException("dh_gen_fail");
                    }
                    else
                    {
                        throw new InvalidOperationException($"dh_gen unknown: {code}");
                    }
                }
            }
        }
 public AuthenticationMiddleware(IOptions <AuthKey> authKey, RequestDelegate next)
 {
     _authKey = authKey.Value;
     _next    = next;
 }
Esempio n. 30
0
        public FileReadDescriptor ReadEncryptedFile(string name, FilePath options, AuthKey key)
        {
            FileReadDescriptor file = ReadFile(name, options);

            if (!key.TryDecryptLocal(file.DataStream.ReadByteArray(), out byte[] decrypted))
Esempio n. 31
0
 public bool Equals(PokeHashAuthKey other)
 {
     return(AuthKey.Equals(other.AuthKey));
 }