Example #1
0
    public int InsertUserToDatabase()
    {
        registrationDate = DateTime.Now;
        salt             = SHA2.GenerateSALT();
        hash             = SHA2.GenerateSHA256String(password, salt);
        if (id > 0)
        {
            LogManager.Report("trying to insert a user with a valid ID", this);
        }
        DateTime sqlMinDate = new DateTime(1800, 1, 1);

        if (BirthDate < sqlMinDate)
        {
            bdate = sqlMinDate;
        }
        if (RegistrationDate < sqlMinDate)
        {
            registrationDate = DateTime.Now;
        }
        int rowsEffected = db.InsertUser(this);

        foreach (var item in Articles)
        {
            db.FullArticleInsert(item);
        }
        return(rowsEffected);
    }
Example #2
0
        public User GetUser(string email, string password)
        {
            User accountUser = null;

            try
            {
                password = DES.Encrypt(
                    this.settings.SecurityKey,
                    SHA2.GetSHA256Hash(password)
                    );

                accountUser =
                    this.accountUserRepository.Find(email, password);
            }
            catch (DataAccessLayerException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new ServiceLayerException(ex);
            }

            return(accountUser);
        }
Example #3
0
        private void CryptoClientForm_Load(object sender, EventArgs e)
        {
            // add algoritams in drop down
            ToolStripMenuItem menu = new ToolStripMenuItem("Algorithams");

            ToolStripMenuItem item = new ToolStripMenuItem("Substitution");
            ICryptoLibrary    alg  = new SimpleSubstitution();

            item.Tag       = alg;
            this.algorithm = alg;
            menu.DropDownItems.Add(item);

            alg      = new XXTEA();
            item     = new ToolStripMenuItem("XXTEA");
            item.Tag = alg;
            menu.DropDownItems.Add(item);

            alg      = new SHA2();
            item     = new ToolStripMenuItem("SHA2");
            item.Tag = alg;
            menu.DropDownItems.Add(item);
            // TODO: add Knapsack

            menu.DropDownItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.OnClickedItem);
            this.msOptions.Items.Add(menu);


            this.Init();
        }
Example #4
0
        public static void HandleAccountCreate(Session session, params string[] parameters)
        {
            uint        accountId   = DatabaseManager.Authentication.GetMaxId() + 1;
            string      account     = parameters[0].ToLower();
            string      salt        = SHA2.Hash(SHA2Type.SHA256, Path.GetRandomFileName());
            string      password    = SHA2.Hash(SHA2Type.SHA256, parameters[1]);
            AccessLevel accessLevel = AccessLevel.Player;

            if (parameters.Length > 2)
            {
                if (Enum.TryParse(parameters[2], true, out accessLevel))
                {
                    if (!Enum.IsDefined(typeof(AccessLevel), accessLevel))
                    {
                        accessLevel = AccessLevel.Player;
                    }
                }
            }

            string articleAorAN = "a";

            if (accessLevel == AccessLevel.Advocate || accessLevel == AccessLevel.Admin || accessLevel == AccessLevel.Envoy)
            {
                articleAorAN = "an";
            }

            Account acc = new Account(accountId, account, accessLevel, salt, password);

            DatabaseManager.Authentication.CreateAccount(acc);

            Console.WriteLine("Account successfully created for " + account + " with access rights as " + articleAorAN + " " + Enum.GetName(typeof(AccessLevel), accessLevel) + ".");
        }
Example #5
0
 public Account(uint accountId, string name, string salt, string password)
 {
     AccountId = accountId;
     Name      = name;
     Salt      = salt;
     Password  = password;
     Digest    = SHA2.Hash(SHA2Type.SHA256, password + salt);
 }
Example #6
0
        private void CryptoClientForm_Load(object sender, EventArgs e)
        {
            this.tbSrcPath.Text = ".\\" + this.defaultSrcPath;
            this.tbDstPath.Text = ".\\" + this.defaultDstPath;
            this.defaultSrcPath = AppDomain.CurrentDomain.BaseDirectory.ToString() + this.defaultSrcPath;
            this.defaultDstPath = AppDomain.CurrentDomain.BaseDirectory.ToString() + this.defaultDstPath;

            string[] srcDicFiles = Directory.GetFiles(this.defaultSrcPath);

            foreach (string f in srcDicFiles)
            {
                this.lbFilesToEncrypt.Items.Add(f);
            }

            string[] dstDicFiles = Directory.GetFiles(this.defaultDstPath);

            foreach (string f in dstDicFiles)
            {
                this.lbEncryptedFiles.Items.Add(f);
            }

            this.CreateNewFileWatcher();


            ICryptoLibrary[] algorithams = new ICryptoLibrary[4];
            algorithams[0] = new SimpleSubstitution();
            algorithams[1] = new XXTEA();
            algorithams[2] = new SHA2();
            algorithams[3] = new Knapsack();

            specs = new Dictionary <string, byte[]>();

            // add algoritams in drop down
            ToolStripMenuItem menu = new ToolStripMenuItem("Algorithams");
            ToolStripMenuItem item;

            for (int i = 0; i < algorithams.Length; i++)
            {
                item     = new ToolStripMenuItem(algorithams[i].ToString());
                item.Tag = algorithams[i];
                menu.DropDownItems.Add(item);
                if (i == 0)
                {
                    this.algoritham = algorithams[i];
                }
            }

            menu.DropDownItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.OnClickedItem);
            this.msOptions.Items.Add(menu);

            this.Init();
            tbN.KeyPress  += this.tbKey_KeyPress;
            tbM.KeyPress  += this.tbKey_KeyPress;
            tbIM.KeyPress += this.tbKey_KeyPress;
            lbHint.Visible = false;
        }
Example #7
0
        public static void HandleAccountCreate(Session session, params string[] parameters)
        {
            uint    accountId = DatabaseManager.Authentication.GetMaxId() + 1;
            string  account   = parameters[0].ToLower();
            string  salt      = SHA2.Hash(SHA2Type.SHA256, Path.GetRandomFileName());
            string  password  = SHA2.Hash(SHA2Type.SHA256, parameters[1]);
            Account acc       = new Account(accountId, account, salt, password);

            DatabaseManager.Authentication.CreateAccount(acc);
        }
Example #8
0
        public static void HandleAccountCreate(Session session, params string[] parameters)
        {
            var result = DatabaseManager.Authentication.SelectPreparedStatement(AuthenticationPreparedStatement.AccountMaxIndex);

            Debug.Assert(result != null);

            uint   accountId = result.Read <uint>(0, "MAX(`id`)") + 1;
            string salt      = SHA2.Hash(SHA2Type.SHA256, Path.GetRandomFileName());
            string password  = SHA2.Hash(SHA2Type.SHA256, parameters[1]);
            string digest    = SHA2.Hash(SHA2Type.SHA256, password + salt);

            DatabaseManager.Authentication.ExecutePreparedStatement(AuthenticationPreparedStatement.AccountInsert, accountId, parameters[0], digest, salt);
        }
Example #9
0
 public void UpdateUserPasswords()
 {
     foreach (var item in db.GetAllUsers())
     {
         if (item.Id >= 6) //All users that are not soccerDB
         {
             string email    = item.FirstName.ToLower() + "@ruppin.ac.il";
             string salt     = SHA2.GenerateSALT();
             string password = "******";
             string hash     = SHA2.GenerateSHA256String(password, salt);
             db.UpdateEmail(item.Id, email);
             db.UpdatePassword(item.Id, salt, hash);
         }
     }
 }
Example #10
0
        private void button1_Click(object sender, EventArgs e)
        {
            var password = SHA2.Hash(textBox2.Text);

            if (_client.Login(textBox1.Text, password))
            {
                var formMain = new MyCloudStoreClientForm(textBox1.Text);
                formMain.Show();
                this.Hide();
            }
            else
            {
                MessageBox.Show("Wrong username or password!!! Try again!!!", "Wrong credentials", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    //Encryption demo
    private void GenerateHashDemo()
    {
        string messi   = SHA2.GenerateSHA256String("messi123", "20E6494B4207A90D");
        string neymar  = SHA2.GenerateSHA256String("neymar123", "3C3C58961451D04");
        string hazan   = SHA2.GenerateSHA256String("hazan123", "66C26C8D58996B8F");
        string ronaldo = SHA2.GenerateSHA256String("ronaldo123", "7EE9BB521CE704BA");
        string bale    = SHA2.GenerateSHA256String("bale123", "2813B5F0BA1E74");

        string res = "messi: " + messi + "\r\n";

        res += "neymar: " + neymar + "\r\n";
        res += "hazan: " + hazan + "\r\n";
        res += "ronaldo: " + ronaldo + "\r\n";
        res += "bale: " + bale + "\r\n";
        Response.Write(res);
    }
Example #12
0
        private static void AccountSelectCallback(MySqlResult result, Session session)
        {
            var connectResponse = new ServerPacket(0x0B, PacketHeaderFlags.ConnectRequest);

            connectResponse.Payload.Write(0u);
            connectResponse.Payload.Write(0u);
            connectResponse.Payload.Write(13626398284849559039ul); // some sort of check value?
            connectResponse.Payload.Write((ushort)0);
            connectResponse.Payload.Write((ushort)0);
            connectResponse.Payload.Write(ISAAC.ServerSeed);
            connectResponse.Payload.Write(ISAAC.ClientSeed);
            connectResponse.Payload.Write(0u);

            NetworkManager.SendPacket(ConnectionType.Login, connectResponse, session);

            if (result.Count == 0)
            {
                session.SendCharacterError(CharacterError.AccountDoesntExist);
                return;
            }

            uint   accountId = result.Read <uint>(0, "id");
            string account   = result.Read <string>(0, "account");

            if (WorldManager.Find(account) != null)
            {
                session.SendCharacterError(CharacterError.AccountInUse);
                return;
            }

            string digest = SHA2.Hash(SHA2Type.SHA256, result.Read <string>(0, "password") + result.Read <string>(0, "salt"));

            /*if (glsTicket != digest)
             * {
             * }*/

            /*if (WorldManager.ServerIsFull())
             * {
             *  session.SendCharacterError(CharacterError.LogonServerFull);
             *  return;
             * }*/

            // TODO: check for account bans

            session.SetAccount(accountId, account);
        }
Example #13
0
        public void UpdatePassword(ObjectId userId, string password)
        {
            try
            {
                password = DES.Encrypt(
                    this.settings.SecurityKey,
                    SHA2.GetSHA256Hash(password)
                    );

                this.accountUserRepository.UpdatePassword(userId, password);
            }
            catch (DataAccessLayerException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new ServiceLayerException(ex);
            }
        }
Example #14
0
    public int InsertUserToDatabase()
    {
        registrationDate = DateTime.Now;
        salt             = SHA2.GenerateSALT();
        hash             = SHA2.GenerateSHA256String(password, salt);
        if (id > 0)
        {
            LogManager.Report("trying to insert a user with a valid ID", this);
        }
        DateTime sqlMinDate = new DateTime(1800, 1, 1);

        if (BirthDate < sqlMinDate)
        {
            bdate = sqlMinDate;
        }
        if (RegistrationDate < sqlMinDate)
        {
            registrationDate = DateTime.Now;
        }
        return(db.InsertUser(this));
    }
Example #15
0
    /// <summary>
    /// Validates users credentials based on email and password
    /// </summary>
    /// <param name="email">Users login string, usually the email address</param>
    /// <param name="password">Users password</param>
    /// <returns>User if true, null if false</returns>
    public User Login(string email, string password)
    {
        string cmdStr = "select * from users where email=@email";

        con = new SqlConnection(connectionString);
        cmd = new SqlCommand(cmdStr, con);
        cmd.Parameters.AddWithValue("@email", email.ToLower());
        //cmd.Parameters.AddWithValue("@hash", hash);

        try
        {
            cmd.Connection.Open();
            reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                string hash = SHA2.GenerateSHA256String(password, reader["uSALT"].ToString());
                if (hash != reader["uHash"].ToString())
                {
                    continue;
                }
                else
                {
                    return(CurrentLineUser(reader));
                }
            }
            return(null);
        }
        catch (Exception ex)
        {
            LogManager.Report(ex);
            return(null);
        }
        finally
        {
            cmd.Connection.Close();
        }
    }
Example #16
0
        public void Save(User accountUser)
        {
            try
            {
                accountUser.Password = DES.Encrypt
                                       (
                    this.settings.SecurityKey,
                    SHA2.GetSHA256Hash(accountUser.Password)
                                       );

                accountUser.Name = accountUser.Name.Substring(0, 1).ToUpper() +
                                   accountUser.Name.Substring(1, accountUser.Name.Length - 1);

                this.accountUserRepository.Save(accountUser);
            }
            catch (DataAccessLayerException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new ServiceLayerException(ex);
            }
        }
Example #17
0
 private void btnOK_Click(object sender, EventArgs e)
 {
     _redisClient.Hashes[txtUsername.Text]["password"] = SHA2.Hash(txtPassword.Text);
     DialogResult = DialogResult.OK;
     this.Close();
 }
Example #18
0
 private string GetHash(byte[] file)
 {
     return(SHA2.Hash(file));
 }
Example #19
0
        private async Task Decode()
        {
            _cancelling = false; // this has to be reset. if CheckCancel doesn't get called after the user clicked cancel (or maybe if they spam the button) it will auto cancel the next time they encode or decode

            var password = GetSteganographyPassword();

            var passwordBytes = SHA2.GetHash(password);
            var carrierImage  = GetSteganographyBitmap();

            // TODO: minimum size limit of image. ...like it has to have an area of x otherwise we can't even get message length (even though there wouldn't be a message)
            var encryptedMessageLengthBytesEncrypted = await Codec.Take(carrierImage, password, StaticVariables.LENGTH_OF_THE_MESSAGE_THAT_CONTAINS_THE_LENGTH_OF_THE_PAYLOAD_IN_BITS);

            byte[] message = null;
            try
            {
                var encryptedMessageLengthBytes = AES.Decrypt(encryptedMessageLengthBytesEncrypted, password);
                var encryptedMessageLength      = BitConverter.ToInt64(encryptedMessageLengthBytes, 0);
                message = await Codec.Take(carrierImage, password, StaticVariables.LENGTH_OF_THE_MESSAGE_THAT_CONTAINS_THE_LENGTH_OF_THE_PAYLOAD_IN_BITS, encryptedMessageLength, CheckCancel);
            }
            catch
            {
                // one possible reason it failed is because the image was never encoded
                // which would cause the message length preamble to be random
                // which would likely cause an out of range error when trying to read bytes out of the image
                message = null;
            }

            if (message != null)
            {
                try
                {
                    message = AES.Decrypt(message, password);

                    // seperate the candidate bytes from the message (if there is one)
                    var steganographyIdentifierBytes = StaticVariables.SteganographyIdentifier.ConvertToByteArray();
                    (byte[] candidateBytes, byte[] tmp) = message.Shift(steganographyIdentifierBytes.Length);
                    message = tmp;

                    if (steganographyIdentifierBytes.SequenceEqual(candidateBytes) == false)
                    {
                        message = null; // no message was found.
                    }
                }
                catch
                {
                    // again, we could have made it this far by luck.
                    // if there are not enough bytes in the message or if for some reason AES.Decrypt throws an error
                    // consider it to not contain message since that's probably what went wrong.
                    message = null;
                }
            }

            if (message != null)
            {
                ExecutionProgress = 1;
                await Task.Delay(100);
                await RouteDecodedMessage(message);
            }
            else
            {
                SendErrorMessage("No message found. Are you using the right password?");
                return;
            }

            ExecutionProgress = 0;
        }