Ejemplo n.º 1
0
        /// <summary>
        /// Create a Login resource.
        /// </summary>
        /// <param name="user">the user to log in</param>
        /// <param name="baseAddress">the host to log into</param>
        /// <param name="lang">the culture to retrieve login info into (fr-FR or en-US)</param>
        /// <returns>a login object with credential headers and a User with its Clients</returns>
        public async static Task <object> Login(User user, string baseAddress, string lang)
        {
            if (user == null || user.Password == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            CulturalEnumStringConverter.Culture = new CultureInfo(lang);

            string hashedPassword = HashManager.GetHash(user.Password);

            user.Password = hashedPassword;
            User seekedUser = await _findUser(user.Login);

            if (seekedUser == null || hashedPassword != seekedUser.Password)
            {
                throw new HttpResponseException(HttpStatusCode.Unauthorized);
            }

            await _removeLogout(seekedUser.Login);

            Random r1 = new Random(159736545);
            Random r2 = new Random(1892344171);

            seekedUser.Password = null;
            return(new
            {
                a2un = string.Format("{0}.{1}.{2}", string.Format("{0:X12}", r1.Next(0x5F4A2C3)), string.Format("{0:X18}", r1.Next(0x5FDA6C1)), string.Format("{0:X22}", r1.Next(0x5F1C2C3))),
                az4s = JsonWebTokenManager.CreateToken(user.Login, "user", baseAddress),
                e7gu = string.Format("{0}.{1}.{2}", string.Format("{0:X12}", r2.Next(0x5F4A2C3)), string.Format("{0:X18}", r2.Next(0x5FDA6C1)), string.Format("{0:X22}", r2.Next(0x5F1C2C3))),
                user = seekedUser,
                ranges = await RangeService.GetAllRanges(lang)
            });
        }
Ejemplo n.º 2
0
 public ProfileDef()
 {
     HashManager.AddVLT("ai_skill");
     HashManager.AddVLT("ai_track_times");
     HashManager.AddVLT("car_bool");
     HashManager.AddVLT("car_common");
     HashManager.AddVLT("car_common_steering");
     HashManager.AddVLT("car_enum");
     HashManager.AddVLT("car_float");
     HashManager.AddVLT("car_info");
     HashManager.AddVLT("car_int");
     HashManager.AddVLT("car_ref");
     HashManager.AddVLT("car_text");
     HashManager.AddVLT("car_tuning");
     HashManager.AddVLT("demo");
     HashManager.AddVLT("dyno");
     HashManager.AddVLT("dyno_tuning");
     HashManager.AddVLT("forced_induction");
     HashManager.AddVLT("level_info");
     HashManager.AddVLT("physics_curves");
     HashManager.AddVLT("route_bool");
     HashManager.AddVLT("route_enum");
     HashManager.AddVLT("route_float");
     HashManager.AddVLT("route_info");
     HashManager.AddVLT("route_int");
     HashManager.AddVLT("route_ref");
     HashManager.AddVLT("route_text");
 }
Ejemplo n.º 3
0
        public override void ReadPointerData(Vault vault, BinaryReader br)
        {
            br.BaseStream.Position = _definitionsPtr;

            for (int i = 0; i < NumDefinitions; i++)
            {
                AttribDefinition definition = new AttribDefinition();
                definition.Read(vault, br);

                if ((definition.Flags & DefinitionFlags.IsStatic) != 0)
                {
                    throw new Exception("Legacy format does not support static fields");
                }

                VltClassField field = new VltClassField(
                    definition.Key,
                    HashManager.ResolveVLT((uint)definition.Key),
                    HashManager.ResolveVLT((uint)definition.Type),
                    definition.Flags,
                    definition.Alignment,
                    definition.Size,
                    definition.MaxCount,
                    definition.Offset);

                Class.Fields.Add(definition.Key, field);
            }

            vault.Database.AddClass(Class);
        }
Ejemplo n.º 4
0
        public User(string name, string cpf, string email, string username, string password,
                    string role, UserRole userRole)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("Nome é inválido");
            }

            if (string.IsNullOrEmpty(cpf) || ValidDocIds.ValidCpf(cpf) == false)
            {
                throw new ArgumentException("Cpf é inválido");
            }

            if (string.IsNullOrEmpty(email))
            {
                throw new ArgumentException("E-mail é inválido");
            }

            if (string.IsNullOrEmpty(username))
            {
                throw new ArgumentException("Nome de usuário é inválido");
            }


            Name     = name;
            Cpf      = cpf;
            Email    = email;
            Username = username;
            Role     = role;
            UserRole = userRole;
            Password = HashManager.GetSha1HashData(password);
        }
Ejemplo n.º 5
0
        public void TestBasicSigningAndVerification()
        {
            var encryptionManager = new EncryptionManager(new KeyStore(new KeyStoreRepository(new DataContext())));
            var hashManager       = new HashManager();

            var cryptoService        = new CryptographyService.CryptographyService(encryptionManager, hashManager);
            var wrappedCryptoService = new CryptoServiceWrapper <FabricSigning>(cryptoService, null);

            var signingContent = GenerateSampleFabricSignContent();
            var signingOutcome = wrappedCryptoService.SignContent(signingContent);

            var signature = new DigitalSignature <FabricSigning>()
            {
                OriginalContent    = signingContent,
                SignedContent      = signingOutcome.Signature,
                SignatoryReference = signingOutcome.SignatoryReference
            };

            var signOutcome = wrappedCryptoService.VerifySignature(signature);

            Assert.IsTrue(signOutcome.SignatoryMatchedToSignature);
            Assert.IsTrue(signOutcome.SignedContentMatchesToSignature);

            // This represents application side verification of signed content. Helpful to identify what in content has changed
            Assert.IsTrue(signOutcome.ExpectedContent?.Agreements?.FirstOrDefault().Description == signOutcome.SignedContent?.Agreements?.FirstOrDefault().Description);
        }
Ejemplo n.º 6
0
        public override Task Download()
        {
            return(Task.Run(async() =>
            {
                var patch = await FetchPatch();

                var fileList = await FetchPatchManifest(patch.PatchId);
                var rootUrl = string.Format(PatchRootFormat, patch.PatchId);

                await _downloader.StartDownload(rootUrl, fileList.Files);

                fileList.Files.GroupBy(f => f.HashGroup)
                .ForEach(group =>
                {
                    var hm = new HashManager(group.Key);

                    hm.CreateIfMissing();
                    hm.Load();

                    foreach (var file in group)
                    {
                        hm.Put(file.FullFile, file.Hash);
                    }

                    hm.Save();
                });
            }));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Creates the user to the database
        /// </summary>
        /// <param name="viewModel">The form of the model that was used</param>
        /// <returns>True if successful save, false if not.</returns>
        public bool Create(AccountViewModel viewModel)
        {
            if (viewModel != null)
            {
                ApplyChanges(viewModel);

                // Verify we can create the user
                Model.Salt       = HashManager.GetSalt();
                Model.Password   = HashManager.HashPassword(viewModel.Password, Model.Salt);
                Model.CreatedOn  = DateTime.Now;
                Model.InviteCode = Codes.GenerateInviteCode();

                bool usernameExists = services.Account.AccountEmailExists(viewModel.Username);
                bool emailExists    = services.Account.AccountEmailExists(viewModel.Email);
                bool passwordsMatch = viewModel.Password == viewModel.PasswordVerify;


                if (!usernameExists && !emailExists && passwordsMatch)
                {
                    services.Account.AddAccount(Model);
                    return(services.Save());
                }
                else
                {
                    return(false);
                }
            }

            return(false);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Authenticate User Login
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task <ResultModel> Authenticate(LoginModel model)
        {
            var user = await _dbContext.Users.FirstOrDefaultAsync(i => i.Username == model.Username);

            if (user == null)
            {
                return(new ResultModel
                {
                    IsSuccessful = false,
                    Message = "Your username or password is invalid!",
                    Code = (int)HttpStatusCode.Unauthorized
                });
            }

            if (!HashManager.VerifyPassword(model.Password, user.Password))
            {
                return(new ResultModel
                {
                    IsSuccessful = false,
                    Message = "Your username or password is invalid!",
                    Code = (int)HttpStatusCode.Unauthorized
                });
            }

            return(new ResultModel
            {
                IsSuccessful = true,
                Data = user,
                Message = "User logged in successfully!",
                Code = (int)HttpStatusCode.OK
            });
        }
Ejemplo n.º 9
0
        public void Test_IsValidUser_MultipleUsers()
        {
            IHashManager manager  = new HashManager();
            string       email    = "*****@*****.**";
            string       password = "******";
            Guid         pwdSalt  = new Guid();
            User         user     = new User
            {
                Id          = new Guid(),
                Credentials = new UserCredentials
                {
                    PwdHash = manager.GetHash(pwdSalt.ToString(), password, 0),
                    PwdSalt = pwdSalt
                },
                Email    = email,
                Username = "******",
                Projects = new List <Guid>()
            };
            List <User> users = new List <User>();

            users.Add(user);
            users.Add(user);

            var mockDbClient = new MockDBClient()
                               .MockContains <User, string>("users", "Email", email, true)
                               .MockFindByField <User, string>("users", "Email", email, users);

            var mockResource = new MockResource().GetDefaultConfig();

            AuthService authService = new AuthService(mockDbClient.Object, mockResource.Object);

            Assert.Throws <InvalidDataException>(() =>
                                                 authService.IsValidUser(email, password)
                                                 );
        }
Ejemplo n.º 10
0
        public IActionResult Get()
        {
            string salt = HashManager.CreateSalt();
            string hash = HashManager.CreateHash("123123", salt);

            return(Ok(new { salt = salt, hash = hash }));
        }
Ejemplo n.º 11
0
        public void Test_IsValidUser_InvalidPassword()
        {
            HashManager manager = new HashManager();

            string      email    = "*****@*****.**";
            string      password = "******";
            Guid        pwdSalt  = new Guid();
            List <User> users    = new List <User>
            {
                new User {
                    Id          = new Guid(),
                    Credentials = new UserCredentials
                    {
                        PwdHash = manager.GetHash(pwdSalt.ToString(), "Dope123", 0),
                        PwdSalt = pwdSalt
                    },
                    Email    = email,
                    Username = "******",
                    Projects = new List <Guid>()
                }
            };

            var mockDbClient = new MockDBClient()
                               .MockContains <User, string>("users", "Email", email, true)
                               .MockFindByField <User, string>("users", "Email", email, users);

            var mockResource = new MockResource().GetDefaultConfig();

            AuthService authService = new AuthService(mockDbClient.Object, mockResource.Object);
            bool        result      = authService.IsValidUser(email, password);

            Assert.True(result == false);
        }
Ejemplo n.º 12
0
        public HashManagerTest()
        {
            _reqValidation = new Mock <IRequestValidation>(MockBehavior.Strict);
            _funcService   = new Mock <IFunctionService>(MockBehavior.Strict);

            _hashManager = new HashManager(_reqValidation.Object, _funcService.Object);
        }
Ejemplo n.º 13
0
        public async Task <BaseResponse> Login(LoginInfo loginInfo)
        {
            var userResult = await _userRepository.Get(x => x.Username == loginInfo.Username);

            if (userResult.State != State.Success)
            {
                return(userResult);
            }

            var users = (List <User>)userResult.Result;

            if (!users.Any())
            {
                return(new ErrorResponse(State.NotFound, "Not Found", "Invalid username"));
            }

            var user = users.First();

            if (user.Password != HashManager.GetHash(loginInfo.Password))
            {
                return(new ErrorResponse(State.ProcessError, "Password Error", "Password is incorrect"));
            }

            var loginResponse = new LoginResponse();

            loginResponse.Token = BuildToken(user.Id);
            return(new SuccessResponse(loginResponse));
        }
 private static byte[] GenerateValidKey(byte[] keyBytes)
 {
     byte[] ret  = new byte[MAX_KEY_LENGTH];
     byte[] hash = HashManager.ToRawHash(keyBytes, HashAlgorithm.SHA256);
     Array.Copy(hash, ret, MAX_KEY_LENGTH);
     return(ret);
 }
Ejemplo n.º 15
0
        public void Hash_SaltInvalid(string salt)
        {
            var config      = Storage.CreateConfiguration();
            var hashManager = new HashManager(config);

            Assert.Throws <ArgumentException>(() => hashManager.Hash("text", salt));
        }
Ejemplo n.º 16
0
        public void Hash_MustFail(string plainText, string salt)
        {
            var config      = Storage.CreateConfiguration();
            var hashManager = new HashManager(config);

            Assert.Throws <ArgumentException>(() => hashManager.Hash(plainText, salt));
        }
        /// <summary>
        /// Member function that checks if an
        /// email exists in the database.
        /// The stored procedure will return
        /// a 0 or 1 to determine if it exists.
        /// </summary>

        public bool CheckEmailExists(string email)
        {
            try {
                if (SystemSettings.IsInternetAvailable() == true)
                {
                    this.Connection.Open();

                    HashManager encrypter = new HashManager();

                    SqlCommand checkAccount = new SqlCommand("SELECT * FROM [USER] where Email=@Email", this.Connection);
                    email = encrypter.HashTextSHA256(email.ToUpper().Trim());

                    checkAccount.Parameters.AddWithValue("@Email", email);
                    checkAccount.ExecuteNonQuery();

                    SqlDataAdapter adapter = new SqlDataAdapter(checkAccount);
                    DataSet        ds      = new DataSet();
                    adapter.Fill(ds);

                    int count = ds.Tables[0].Rows.Count;

                    if (count == 1)
                    {
                        this.Connection.Close();
                        return(true);
                    }
                }
            } catch { }

            this.Connection.Close();
            return(false);
        }
Ejemplo n.º 18
0
        private object OnAddPassword(object message)
        {
            var packet = ( AddPasswordMessage )message;
            var ret    = new OperationResult();

            PasswordManager passwordManager = new PasswordManager();

            bool hasPasswords = passwordManager.HasPasswords();

            if (!this.CheckSession(packet.SessionKey) && hasPasswords)
            {
                ret.Value = false;
                return(ret);
            }

            if (!this.IsPasswordCorrect(packet.NewPassword))
            {
                ret.Value = false;
                return(ret);
            }

            string newPassword = HashManager.Sha256(packet.NewPassword);

            passwordManager.InsertPassword(newPassword);

            ret.Value = true;
            return(ret);
        }
Ejemplo n.º 19
0
        private object OnDeletePassword(object message)
        {
            var packet = ( DeletePasswordMessage )message;
            var ret    = new OperationResult();

            if (!this.CheckSession(packet.SessionKey))
            {
                ret.Value = false;
                return(ret);
            }

            PasswordManager passwordManager = new PasswordManager();

            string password = HashManager.Sha256(packet.Password);

            bool result = passwordManager.CheckPassword(password);

            if (result)
            {
                result = passwordManager.DeletePassword(password);
                this.DeleteSession(packet.SessionKey);
            }

            ret.Value = result;
            return(ret);
        }
Ejemplo n.º 20
0
        public Match(string title, int rounds, int maxPlayers, int roundLength)
        {
            MatchUid = HashManager.GenerateSecureRandomToken();

            Title       = title;
            Rounds      = rounds;
            MaxPlayers  = maxPlayers;
            RoundLength = roundLength;

            Players                 = new ObservableCollection <Player>();
            PlayedPlayers           = new List <Player>();
            PickedWords             = new ObservableCollection <Word>();
            RemainingTime           = RoundLength;
            CurrentRound            = 1;
            _currentPreparationTime = PreparationTime;

            _preparationTimer          = new Timer(1000);
            _preparationTimer.Elapsed += PreparationTimerTicked;

            _subRoundTimer          = new Timer(1000);
            _subRoundTimer.Elapsed += SubRoundTimerTicked;

            PreparationTimeFinished += Match_PreparationTimeFinished;
            SubRoundFinished        += Match_SubRoundFinished;
        }
Ejemplo n.º 21
0
        static void HashManagerTests()
        {
            string str = "A";

            str = HashManager.ToBase64(str, 0, false);
            Console.WriteLine(str);
            Console.WriteLine(HashManager.ToString(HashManager.FromBase64(str)));
        }
Ejemplo n.º 22
0
 public override void Read(Vault vault, BinaryReader br)
 {
     while (br.BaseStream.Position < EndOffset)
     {
         string str = NullTerminatedString.Read(br);
         HashManager.AddVLT(str);
     }
 }
        public void HashManager_HashPassword_HashesPassword()
        {
            String pass = "******";
            String salt = HashManager.GetSalt();
            String hash = HashManager.HashPassword(pass, salt);

            Assert.IsNotNull(hash);
        }
Ejemplo n.º 24
0
        public AttribService(ILogger <AttribService> logger,
                             GameplayVault gameplayVault)
        {
            _logger        = logger;
            _gameplayVault = gameplayVault;

            HashManager.LoadDictionary(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"data\hashes.txt"));
        }
Ejemplo n.º 25
0
        public void InitReceiver(FileDescription fd)
        {
            this.fd = fd;
            hm      = new HashManager(-1, Sizes.GetChunksNumber(fd.FileSize), fd.FileId, this);
            DataMessageProvider dmp = new DataMessageProvider(SocketResourcesManager.srm.ProvideBuffer());
            OutputMessage       om  = dmp.ProvideFileHashTransferRequestMessage(fd.FileId);

            ClientCommunicationCenter.commCenter.SendMessageToServer(om);
        }
Ejemplo n.º 26
0
        public static string ToPassword(this string str)
        {
            if (str is null)
            {
                throw new ArgumentNullException(nameof(str));
            }

            return(HashManager.GetMd5(HashManager.GetMd5(str + "Rye")));
        }
Ejemplo n.º 27
0
    /// <summary>
    /// Metodo que se ejecuta al presionar enviar codigo (envia el codigo de activacion para registrarse)
    /// </summary>
    public void ClickSendConfirmation()
    {
        InputField username = GameObject.Find("/Canvas/SignUpPanel/TFUsername").GetComponent <InputField>();

        Debug.Log(username);
        InputField correo           = GameObject.Find("/Canvas/SignUpPanel/TFEmail").GetComponent <InputField>();
        InputField password         = GameObject.Find("/Canvas/SignUpPanel/TFPassword").GetComponent <InputField>();
        InputField confirmationPass = GameObject.Find("/Canvas/SignUpPanel/TFConfirmation").GetComponent <InputField>();

        Debug.Log("Comparando contraseñas");
        string hashPass             = HashManager.GeneratePasswordHash(password.text);
        string hashPassConfirmation = HashManager.GeneratePasswordHash(confirmationPass.text);

        if (username.text == null || correo.text == null || password.text == null || confirmationPass == null)
        {
            Debug.Log("Hay campos vacios");
            SSTools.ShowMessage(LocalizationManager.instance.GetLocalizedValue("message_empty_fields"),
                                SSTools.Position.bottom, SSTools.Time.oneSecond);
        }
        else
        {
            if (hashPassConfirmation.Equals(hashPass))
            {
                GameObject.Find("/Canvas/SignUpPanel").SetActive(false);
                GameObject VerificationSignUpPanel = BuscarObjetoInactivo("VerificationSignUpPanel");
                VerificationSignUpPanel.SetActive(true);

                string nombre = username.text;
                string email  = correo.text;

                Jugador.instance.Username        = nombre;
                Jugador.instance.Pass            = hashPass;
                Jugador.instance.Correo          = email;
                Jugador.instance.PartidasGanadas = 0;
                Jugador.instance.PartidasJugadas = 0;

                Debug.Log("Datos antes de clase mail = " + nombre + ", " + email);
                MailMessage mail     = new MailMessage(nombre, email);
                string      mailData = JsonConvert.SerializeObject(mail);
                Debug.Log("JSON = " + mailData);

                Debug.Log("Enviando codigo de activacion a " + correo.text);
                ConnectionManager.instance.socket.Emit("sendActivationCode", mailData);

                username.text         = "";
                correo.text           = "";
                password.text         = "";
                confirmationPass.text = "";
            }
            else
            {
                Debug.Log("La contraseña y la confirmacion de la contraseñ son diferentes");
                SSTools.ShowMessage(LocalizationManager.instance.GetLocalizedValue("passwords_diferent"),
                                    SSTools.Position.bottom, SSTools.Time.oneSecond);
            }
        }
    }
Ejemplo n.º 28
0
        protected string CleanHashString(string hashString)
        {
            if (hashString.StartsWith("0x"))
            {
                hashString = HashManager.ResolveVLT(uint.Parse(hashString.Substring(2), NumberStyles.AllowHexSpecifier));
            }

            return(hashString);
        }
Ejemplo n.º 29
0
        public override void Read(Vault vault, BinaryReader br)
        {
            var mKey          = br.ReadUInt64();
            var mClass        = br.ReadUInt64();
            var mParent       = br.ReadUInt64();
            var mTableReserve = br.ReadUInt32();

            br.ReadUInt32();
            var mNumEntries = br.ReadUInt32();
            var mNumTypes   = br.ReadUInt16();
            var mTypesLen   = br.ReadUInt16();

            _layoutPointer = br.ReadPointer();
            br.ReadUInt32();

            Debug.Assert(mTableReserve == mNumEntries);

            Collection = new VltCollection(vault, vault.Database.FindClass(HashManager.ResolveVLT(mClass)), HashManager.ResolveVLT(mKey));

            Debug.Assert(mTypesLen >= mNumTypes);

            _types = new ulong[mNumTypes];
            for (var i = 0; i < mNumTypes; i++)
            {
                _types[i] = (br.ReadUInt64());
            }

            for (var i = 0; i < mTypesLen - mNumTypes; i++)
            {
                br.ReadUInt64();
            }

            _entries = new List <AttribEntry64>();

            for (var i = 0; i < mNumEntries; i++)
            {
                var attribEntry = new AttribEntry64(Collection);

                attribEntry.Read(vault, br);

                // save pos
                long pos      = br.BaseStream.Position;
                var  readData = attribEntry.ReadData(vault, br);
                br.BaseStream.Position = pos;

                if (!readData)
                {
                    continue;
                }

                _entries.Add(attribEntry);
            }

            // TODO: ParentKey
            //Collection.ParentKey = mParent;
            vault.Database.RowManager.AddCollection(Collection);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Instantiates the instance variables.
        /// </summary>

        private void Instantiate()
        {
            this.count             = 3;
            this.encryption        = new HashManager();
            this.codePopup         = new Popup();
            this.popupContent      = new TextBlock();
            this.networkConnection = new SystemSettings();
            this.connectionString  = DatabaseConnection.GetConnectionString();
        }