using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Utils
{
    public class PasswordHash
    {
        private static Random random = new Random();

        public static byte[] getNextSalt()
        {
            byte[] salt = new byte[20];
            random.NextBytes(salt);
            return salt;
        }

        public static byte[] Hash(string password, byte[] salt)
        {
            HashAlgorithm algorithm = new SHA256Managed();

            byte[] bytePassword = Encoding.UTF8.GetBytes(password);
            byte[] plainTextWithSaltBytes = new byte[bytePassword.Length + salt.Length];

            for (int i = 0; i < bytePassword.Length; i++)
            {
                plainTextWithSaltBytes[i] = bytePassword[i];
            }

            for (int i = 0; i < salt.Length; i++)
            {
                plainTextWithSaltBytes[bytePassword.Length + i] = salt[i];
            }

            return algorithm.ComputeHash(plainTextWithSaltBytes);
        }

        public static bool Compare(string password, byte[] salt, byte[] hashed)
        {
            if (password == null) return false;
            if (hashed == null) return false;

            byte[] hashedNew = Hash(password, salt);

            if (hashedNew.Length != hashed.Length)
            {
                return false;
            }

            for (int i = 0; i < hashedNew.Length; i++)
            {
                if (hashedNew[i] != hashed[i])
                {
                    return false;
                }
            }

            return true;
        }
    }
}
