Exemple #1
0
        private string generateKeyParama(string email)
        {
            DateTime now = DateTime.UtcNow;
            string   key = email + now.ToShortDateString() + SECRET;

            return(SHA.ComputeSHA256Hash(key));
        }
Exemple #2
0
        }                                           //  TODO rename to TransactionId

        public TransactionOutput(Key reciepient, decimal value, string parentTransactionId)
        {
            Reciepient          = reciepient;
            Value               = value;
            ParentTransactionId = parentTransactionId;
            Id = SHA.ComputeSHA256Hash(reciepient.ToString() + Value + parentTransactionId);
        }
Exemple #3
0
 private String CalulateHash() // TODO replace to GetHashCode()
 {
     return(SHA.ComputeSHA256Hash
            (
                SenderPublicKey.ToString() + ReciepientPublicKey.ToString() + Value
            ));
 }
Exemple #4
0
        public static string CalculateHash(ICollection <Transaction> transactions)
        {
            int           count             = transactions.Count;
            List <string> previousTreeLayer = new List <string>();

            foreach (Transaction transaction in transactions)
            {
                previousTreeLayer.Add(transaction.TransactionId);
            }

            List <string> treeLayer = previousTreeLayer;

            while (count > 1)
            {
                treeLayer = new List <string>();
                for (int i = 1; i < previousTreeLayer.Count; i++)
                {
                    treeLayer.Add(SHA.ComputeSHA256Hash
                                  (
                                      previousTreeLayer[i - 1] + previousTreeLayer[i]
                                  ));
                }
                count             = treeLayer.Count;
                previousTreeLayer = treeLayer;
            }

            string merkleRoot = treeLayer.Count == 1 ? treeLayer[0] : "";

            return(merkleRoot);
        }
        public async Task UpdatePasswordAsync(UserRequestModels.UpdatePassword rq)
        {
            //check token
            await _keyResetPasswordService.VerifyKeyAsync(rq.Username, rq.KeyParam);

            //get update password user
            User user = await _userRepo.GetUserByUsernameAsync(rq.Username);

            user.PasswordHash = SHA.ComputeSHA256Hash(rq.Password);
            _userRepo.Update(user);
            await _userRepo.UnitOfWork.SaveChangesAsync();
        }
        public async Task <UserReturnModels.User> GetValidUserAsync(string username, string password)
        {
            var user = await _userRepo.GetUserByUsernameAsync(username);

            if (user == null)
            {
                return(null);
            }
            // TODO: need to encrypt password and compare with PasswordHash

            if (user.PasswordHash == SHA.ComputeSHA256Hash(password))
            {
                return(_mapper.Map <UserReturnModels.User>(user));
            }

            return(null);
        }
        public int AddUser(Adduser user)
        {
            if (user.Username == "")
            {
                return(-2);
            }
            if (user.Username == _adminUsername)
            {
                return(-3);
            }

            using (var connection = new SqlConnection(_connectionString))
            {
                try
                {
                    user.Password = SHA.ComputeSHA256Hash(user.Password);
                    var parameter = new { username = user.Username, password = user.Password, firstname = user.FirstName, lastname = user.LastName };
                    var sql       = "INSERT INTO Users (username, password, firstname, lastname) VALUES (@username, @password, @firstname, @lastname)";
                    connection.Execute(sql, parameter);

                    // If this fails then the user will still be added with no permissions
                    var GetUserId = "SELECT Id FROM Users WHERE Username = @username";
                    var UserId    = connection.QuerySingle <int>(GetUserId, parameter);

                    for (int i = 0; i < user.PermissionsArray.Length; i++)
                    {
                        var parameterPermId = new { PermissionId = user.PermissionsArray[i] };
                        var GetPermissionId = "SELECT Id FROM Permissions WHERE PermissionId = @PermissionId";
                        var PermId          = connection.QuerySingle <int>(GetPermissionId, parameterPermId);

                        var parameter2 = new { UserId, PermissionId = PermId };
                        var sql2       = "INSERT INTO UsersPermissions (UserId, PermissionId) VALUES (@UserId, @PermissionId)";
                        connection.Execute(sql2, parameter2);
                    }
                    return(1);
                }
                catch
                {
                    return(-1);
                }
            }
        }
        private void CheckPersone(object obj)
        {
            //Window win = obj as Window;
            var passwordBox = obj as PasswordBox;

            User.Pass = SHA.ComputeSHA256Hash(passwordBox.Password);
            passwordBox.Clear();

            //check for exist eny user data in Users
            switch (FirstUserCheck())
            {
            case CheckUser.Yes:
                //here we have user i identification and authorezation
                User = Identification(User);
                if (User != null)
                {
                    //here we call main window fo work with application
                    CallFirstWindow(User.UserId);
                    showWindow.CloseWindow(win);
                }

                else
                {
                    dialogService.ShowMessage("Не верная пара логин-пароль");
                }
                User = new User();
                break;

            case CheckUser.No:
                dialogService.ShowMessage("В БД нет ни одного пользователя. Нужно зарегистрироваться.");
                //here we call user registration window
                //this is relevat only at the first application start
                //UserRegistration usver;
                //usver = new UserRegistration();
                //showWindow.ShowWindow(usver);
                break;

            case CheckUser.DB_trabl:
                dialogService.ShowMessage("Проблемы установки связи с базой данных...");
                break;
            }
        }
 public bool IsValidUser(UserModel user)
 {
     try
     {
         using (var connection = new SqlConnection(_connectionString))
         {
             var parameter   = new { Username = user.Username };
             var sql         = "SELECT Users.Password FROM Users WHERE Username = @Username";
             var comparePass = connection.QuerySingle <String>(sql, parameter);
             if (comparePass == SHA.ComputeSHA256Hash(user.Password))
             {
                 return(true);
             }
             else
             {
                 return(false);
             }
         }
     }
     catch
     {
         return(false);
     }
 }
Exemple #10
0
 public string CalculateHash()
 {
     return(SHA.ComputeSHA256Hash(PreviousHash + TransactionsHash + createdOn + nonce.ToString()));
 }
        public int EditUser(EditUser user)
        {
            if (user.Username == "")
            {
                return(-2);
            }
            if (user.Username == _adminUsername || user.NewUsername == _adminUsername)
            {
                return(-3);
            }
            using (var connection = new SqlConnection(_connectionString))
            {
                // Delete all user perms first
                var parameter = new { UserId = user.Id };
                var sql       = "DELETE FROM UsersPermissions WHERE UserId = @UserId";
                connection.Execute(sql, parameter);

                for (int i = 0; i < user.PermissionsArray.Length; i++)
                {
                    var parameterPermId = new { PermissionId = user.PermissionsArray[i] };
                    var GetPermissionId = "SELECT Id FROM Permissions WHERE PermissionId = @PermissionId";
                    var PermId          = connection.QuerySingle <int>(GetPermissionId, parameterPermId);

                    var parameter2 = new { UserId = user.Id, PermissionId = PermId };
                    var sql2       = "INSERT INTO UsersPermissions (UserId, PermissionId) VALUES (@UserId, @PermissionId)";
                    connection.Execute(sql2, parameter2);
                }

                if (user.Password != null) //Change password
                {
                    user.Password = SHA.ComputeSHA256Hash(user.Password);
                    var parameter3 = new { username = user.Username, password = user.Password };
                    var sql3       = "UPDATE Users SET Password = @password WHERE Username = @username";
                    connection.Execute(sql3, parameter3);
                }
                try
                {
                    var updateNamesParam = new { username = user.Username, firstname = user.FirstName, lastname = user.LastName };
                    if (user.FirstName != null)
                    {
                        var updateFirstname = "UPDATE Users SET FirstName = @firstname WHERE Username = @Username";
                        connection.Execute(updateFirstname, updateNamesParam);
                    }
                    if (user.LastName != null)
                    {
                        var updateLastname = "UPDATE Users SET LastName = @lastname WHERE Username = @Username";
                        connection.Execute(updateLastname, updateNamesParam);
                    }
                    if (user.NewUsername != null) //Change username
                    {
                        var updateUsernameParam = new { username = user.Username, NewUsername = user.NewUsername };
                        var updateUsername      = "******";
                        connection.Execute(updateUsername, updateUsernameParam);
                    }


                    return(1);
                }
                catch
                {
                    return(-1);
                }
            }
        }
Exemple #12
0
 private static string HashPassword(string input)
 {                                         // Create a function to easily hash passwords
     return(SHA.ComputeSHA256Hash(input)); // One function to hash using SHA256 with EasyEncryption library, returns a string.
 }
Exemple #13
0
        public Router()
        {
            Get["/"] = parameters => View["index"];

            Get["/{longId}"] = parameters =>
            {
                using (var db = new LiteDatabase(Config.DBPATH))
                {
                    var collection = db.GetCollection <Paste>("pastes");
                    var paste      = collection.FindOne(Query.EQ("LongId", parameters.longId.ToString()));
                    if (paste == null)
                    {
                        return(HttpStatusCode.NotFound);
                    }
                    return(View["paste", paste]);
                }
            };

            Get["/json/{longId}"] = parameters =>
            {
                using (var db = new LiteDatabase(Config.DBPATH))
                {
                    var collection = db.GetCollection <Paste>("pastes");
                    var paste      = collection.FindOne(Query.EQ("LongId", parameters.longId.ToString()));
                    if (paste == null)
                    {
                        return(HttpStatusCode.NotFound);
                    }
                    return(JsonConvert.SerializeObject(paste));
                }
            };

            Get["/raw/{longId}"] = parameters =>
            {
                string longId = parameters.longId;

                using (var db = new LiteDatabase(Config.DBPATH))
                {
                    var result = db.GetCollection <Paste>("pastes").FindOne(Query.EQ("LongId", longId));

                    return(result.Body);
                }
            };

            Post["/upload"] = parameters =>
            {
                var body   = Request.Body;
                var length = (int)body.Length;
                var data   = new byte[length];

                body.Read(data, 0, length);

                var jsonPaste = JsonConvert.DeserializeObject <Paste>(Encoding.Default.GetString(data));

                if (HexUtils.isHex(jsonPaste.Title) && HexUtils.isHex(jsonPaste.Body))
                {
                    using (var db = new LiteDatabase(Config.DBPATH))
                    {
                        var pastes = db.GetCollection <Paste>("pastes");

                        string hashSeed = pastes.Count().ToString() + jsonPaste.Date.ToString() + jsonPaste.Title + jsonPaste.Body + jsonPaste.Language;
                        string longId   = Multibase.Base64.Encode(HexUtils.toByteArray(SHA.ComputeSHA256Hash(hashSeed)), false, true);

                        var newPaste = new Paste
                        {
                            LongId   = longId,
                            Date     = DateTime.Now,
                            Title    = jsonPaste.Title,
                            Body     = jsonPaste.Body,
                            Language = jsonPaste.Language
                        };

                        pastes.Insert(newPaste);

                        var res = new UploadResponse
                        {
                            Status = "success",
                            LongId = longId
                        };
                        return(JsonConvert.SerializeObject(res));
                    }
                }
                else
                {
                    var res = new UploadResponse
                    {
                        Status = "error",
                        ErrMsg = "Error: the paste is not encrypted with AES-256."
                    };
                    return(JsonConvert.SerializeObject(res));
                }
            };
        }