/// <summary>
        /// Register new user
        /// </summary>
        /// <returns>new user Id</returns>
        public int SignUp(UserModel userModel)
        {
            int userId = 0;

            using (HandshakerEntities handshakerEntityContainer = new HandshakerEntities())
            {
                if (handshakerEntityContainer.UserSet.Count(u => u.Username.Equals(userModel.Username)) > 0)
                    throw new Exception("Sistemde " + userModel.Username + " adıyla bir kullanıcı bulunmaktadır");

                #region hash password
                byte[] passwordAsByte = System.Text.Encoding.ASCII.GetBytes(userModel.Password);
                passwordAsByte = new System.Security.Cryptography.SHA256Managed().ComputeHash(passwordAsByte);
                String hashedPassword = System.Text.Encoding.ASCII.GetString(passwordAsByte);
                #endregion

                User newUser = new User()
                {
                    FirstName = userModel.FirstName,
                    LastName = userModel.LastName,
                    Username = userModel.Username,
                    Email = userModel.Email,
                    Password = hashedPassword
                };

                handshakerEntityContainer.UserSet.AddObject(newUser);
                handshakerEntityContainer.SaveChanges();

                userId = newUser.Id;
            }

            return userId;
        }
 public static byte[] encriptar(string password)
 {
     byte[] data = new byte[32];
     System.Security.Cryptography.SHA256 sha = new System.Security.Cryptography.SHA256Managed();
     data = StringToBytes(password);
     return sha.ComputeHash(data);
 }
 public static string Sha256encrypt(string phrase)
 {
     UTF8Encoding encoder = new UTF8Encoding();
     System.Security.Cryptography.SHA256Managed sha256hasher = new System.Security.Cryptography.SHA256Managed();
     byte[] hashedDataBytes = sha256hasher.ComputeHash(encoder.GetBytes(phrase));
     return Convert.ToBase64String(hashedDataBytes);
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="password"></param>
 /// <returns></returns>
 /// <![CDATA[Taken from http://stackoverflow.com/questions/212510/what-is-the-easiest-way-to-encrypt-a-password-when-i-save-it-to-the-registry]]>
 public static string EncrypPassword(string password)
 {
     string saltedPassword = password /*+ Salt*/;
     byte[] data = Encoding.ASCII.GetBytes(saltedPassword);
     data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data);
     return Encoding.ASCII.GetString(data);
 }
示例#5
0
		private string getHash(string s)
		{
			var csp = new System.Security.Cryptography.SHA256Managed();
			var utf8Encoding = new System.Text.UTF8Encoding();
			byte[] result = csp.ComputeHash(utf8Encoding.GetBytes(s));
			return Convert.ToBase64String(result)+"\n";
		}
        public World Generate()
        {
            Console.WriteLine("Generating new World...");
            world.Day = 1;
            world.Width = 50;
            world.Height = 50;
            world.Tiles = GenerateMap(world.Width, world.Height);
            world.Registrations = new List<Registration>();
            world.Players = new List<Player>();
            world.Villages = new List<Village>();
            world.IPBans = new List<IPBan>();

            #if DEBUG
            System.Security.Cryptography.SHA256Managed sha256 = new System.Security.Cryptography.SHA256Managed();
            UTF8Encoding utf8Encoder = new UTF8Encoding();
            Player player = new Player();
            player.Name = "Majzlík";
            player.Login = "******";
            player.Password = sha256.ComputeHash(utf8Encoder.GetBytes("majzlik"));
            world.Players.Add(player);
            player = new Player();
            player.Name = "Setal";
            player.Login = "******";
            player.Password = sha256.ComputeHash(utf8Encoder.GetBytes("setal"));
            world.Players.Add(player);
            #endif
            Console.WriteLine("New World Generated");
            return world;
        }
示例#7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DerivedValue" /> class.
        /// </summary>
        /// <param name="passphrase">The encryption key or passphrase represented in a SecureString. This is the preferred method of instantiating this class because it protects the key in memory.</param>
        public DerivedValue(SecureString passphrase)
        {
            int length = passphrase.Length;
            byte[] clearbytes = new byte[length];
            IntPtr pointer = IntPtr.Zero;

            // Marshal the preshared key as a byte array
            try
            {
                pointer = Marshal.SecureStringToGlobalAllocAnsi(passphrase);
                Marshal.Copy(pointer, clearbytes, 0, length);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (pointer != IntPtr.Zero) Marshal.ZeroFreeGlobalAllocAnsi(pointer);
            }

            System.Security.Cryptography.SHA256 sha = new System.Security.Cryptography.SHA256Managed();
            this.hashed = sha.ComputeHash(clearbytes);

            // Nulling the byte marks the byte for garbage collection but does not remove it from memory.
            // Therefore, we zero the clear text byte to reduce the likelihood of data leakage.
            for (int i = 0; i < length; i++)
            {
                clearbytes[i] = 0;
            }
        }
示例#8
0
 //Encrypting the password
 public string HashPassword(string pw, string salt)
 {
     byte[] bytes = System.Text.Encoding.UTF8.GetBytes(pw + salt);
     System.Security.Cryptography.SHA256Managed hashstring = new System.Security.Cryptography.SHA256Managed();
     byte[] hash = hashstring.ComputeHash(bytes);
     
     return ByteArrayToHexString(hash);
 }
 /// <summary>Create hash using SHA-256 cryptography.</summary>
 public static string CreateHashSha256(string s)
 {
     using(var sha = new System.Security.Cryptography.SHA256Managed()) {
     byte[] originalBytes = System.Text.Encoding.Unicode.GetBytes(s);
     byte[] hashBytes = sha.ComputeHash(originalBytes);
     return hashBytes.ToStringFromBytes();
     }
 }
示例#10
0
 protected String hashPassword(String origPwd)
 {
     byte[] bytes = System.Text.Encoding.UTF8.GetBytes(origPwd);
     System.Security.Cryptography.SHA256Managed sha256HashString = new System.Security.Cryptography.SHA256Managed();
     byte[] hash = sha256HashString.ComputeHash(bytes);
     String hex = BitConverter.ToString(hash);
     return hex.Replace("-", "");
 }
示例#11
0
        protected string CreateHash(string input, string salt)
        {
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(input.Trim() + salt.Trim());
            System.Security.Cryptography.SHA256Managed hashString = new System.Security.Cryptography.SHA256Managed();
            byte[] hash = hashString.ComputeHash(bytes);

            return ByteArrayToString(hash);
        }
        /*public method used to encrypt passwords*/
        public string encryptPassword(string input)
        {
            byte[] data = System.Text.Encoding.ASCII.GetBytes(input); //passing input to a bite code
            data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data); //compute hash of the bite code
            String hash = System.Text.Encoding.ASCII.GetString(data); //encrypt byte code

            return hash; //return encrypted string
        }
示例#13
0
        public static string EncryptPassword(string password)
        {
            string salt = "be6eacd9-b231-4bcf-91ff-c3cbfd640d07";            

            byte[] passwordAndSaltBytes = System.Text.Encoding.UTF8.GetBytes(password + salt);
            byte[] hashBytes = new System.Security.Cryptography.SHA256Managed().ComputeHash(passwordAndSaltBytes);
            string hashString = Convert.ToBase64String(hashBytes);
            return hashString;
        } 
示例#14
0
        public static string EncryptPassword(string password)
        {
            string salt = Guid.NewGuid().ToString();

            byte[] passwordAndSaltBytes = System.Text.Encoding.UTF8.GetBytes(password + salt);
            byte[] hashBytes = new System.Security.Cryptography.SHA256Managed().ComputeHash(passwordAndSaltBytes);
            string hashString = Convert.ToBase64String(hashBytes);
            return hashString;
        }
 public static string GenerateHashWithSalt(string password, string salt)
 {
     string sHashWithSalt = password + salt;
     byte[] saltedHashBytes = Encoding.UTF8.GetBytes(sHashWithSalt);
     // use hash algorithm to compute the hash
     System.Security.Cryptography.HashAlgorithm algorithm = new System.Security.Cryptography.SHA256Managed();
     // convert merged bytes to a hash as byte array
     byte[] hash = algorithm.ComputeHash(saltedHashBytes);
     return Convert.ToBase64String(hash);
 }
示例#16
0
 static string sha256(string password)
 {
     System.Security.Cryptography.SHA256Managed crypt = new System.Security.Cryptography.SHA256Managed();
     System.Text.StringBuilder hash = new System.Text.StringBuilder();
     byte[] crypto = crypt.ComputeHash(Encoding.UTF8.GetBytes(password), 0, Encoding.UTF8.GetByteCount(password));
     foreach (byte theByte in crypto) {
         hash.Append(theByte.ToString("x2"));
     }
     return hash.ToString();
 }
        public static string Encrypt(string password)
        {
            byte[] data = System.Text.Encoding.ASCII.GetBytes(password);
            data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data);
            string hash = System.Text.Encoding.ASCII.GetString(data);

            hash = hash.Replace('\'', 'g');

            return hash;
        }
示例#18
0
		public static string GetSHA256Hash(Stream data)
		{
			if (data != null && data.Length > 0)
			{
				System.Security.Cryptography.SHA256Managed sha = new System.Security.Cryptography.SHA256Managed();
				byte[] hash = sha.ComputeHash(data);

				return Convert.ToBase64String(hash);
			}
			return null;
		}
  /// Verschlüsselung der Passwort-Informationen vor der Übertragung
 private string encrypt(string input)
 {
     System.Security.Cryptography.SHA256 sha256 = new System.Security.Cryptography.SHA256Managed();
     byte[] sha256Bytes = System.Text.Encoding.UTF8.GetBytes(input);
     byte[] cryString = sha256.ComputeHash(sha256Bytes);
     string sha256Str = string.Empty;
     for (int i = 0; i < cryString.Length; i++)
     {
         sha256Str += cryString[i].ToString("X").PadLeft(2, '0');
     }
     return sha256Str;
 }
示例#20
0
 public static string encriptar(string input)
 {
     System.Security.Cryptography.SHA256 sha256 = new System.Security.Cryptography.SHA256Managed();
     byte[] sha256Bytes = System.Text.Encoding.Default.GetBytes(input);
     byte[] cryString = sha256.ComputeHash(sha256Bytes);
     string sha256Str = string.Empty;
     for (int i = 0; i < cryString.Length; i++)
     {
         sha256Str += cryString[i].ToString("x2").ToLower();
     }
     return sha256Str;
 }
示例#21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DerivedValue" /> class.
        /// </summary>
        /// <param name="encryptionKey">The encryption key represented in a byte array. Important note: such a byte array can be read in memory. Dispose of it quickly.</param>
        public DerivedValue(byte[] encryptionKey)
        {
            System.Security.Cryptography.SHA256 sha = new System.Security.Cryptography.SHA256Managed();
            this.hashed = sha.ComputeHash(encryptionKey);

            // Nulling the byte marks the byte for garbage collection but does not remove it from memory.
            // Therefore, we zero the clear text byte to reduce the likelihood of data leakage.
            for (int i = 0; i < encryptionKey.Length; i++)
            {
                encryptionKey[i] = 0;
            }
        }
示例#22
0
        public static string dameHash(string clave)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(clave);

            System.Security.Cryptography.SHA256Managed sha256hashstring = new System.Security.Cryptography.SHA256Managed();
            byte[] hash = sha256hashstring.ComputeHash(bytes);
            string hashstring = string.Empty;
            foreach(byte x in hash)
            {
                hashstring += String.Format("{0:x2}",x);
            }
            return hashstring;
        }
示例#23
0
        public static string HashPassword(string plainMessage)
        {
            if (string.IsNullOrEmpty(plainMessage))
            {
                return string.Empty;
            }

            var data = System.Text.Encoding.UTF8.GetBytes(plainMessage);
            using (System.Security.Cryptography.HashAlgorithm sha = new System.Security.Cryptography.SHA256Managed())
            {
                sha.TransformFinalBlock(data, 0, data.Length);
                return Convert.ToBase64String(sha.Hash);
            }
        }
示例#24
0
        // Adds new customer to database if user input is correct (passes the tests function)
        protected void submitBtn_Click(object sender, EventArgs e)
        {
            DataSet1TableAdapters.CustomersTableAdapter adapter = new DataSet1TableAdapters.CustomersTableAdapter();
            if (tests())
            {
                Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                //emailHandler email_handler = new emailHandler();
                //email_handler.SendVerificationEmail(email.Text, "*****@*****.**");
                byte[] data = System.Text.Encoding.ASCII.GetBytes(password.Text);
                data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data);
                String hash = System.Text.Encoding.ASCII.GetString(data);
                adapter.CreateCustomer(fName.Text, sName.Text, "08/02/1995", email.Text, hash, "123 street"); //, "" + unixTimestamp);
                Page.ClientScript.RegisterStartupScript(GetType(), "MyKey", "successfulRegistration();", true);

                Response.Redirect("/login.aspx");
            }
        }
示例#25
0
        public void timer8_Tick(object sender, EventArgs e)
        {
            // 2 birds, 1 timer :D
            FetchMemorySignatures.Request();

            if (CommonData.publicSSready)
            {

                // delete old upload file
                File.Delete(CommonData.DataFolder + "public_ss_upload.png");

                if (System.IO.File.Exists(CommonData.DataFolder + "public_ss.png") == true)
                {
                    using (System.IO.FileStream stream = System.IO.File.OpenRead(CommonData.DataFolder + "public_ss.png"))
                    {
                        System.Security.Cryptography.SHA256Managed sha = new System.Security.Cryptography.SHA256Managed();
                        byte[] bytes = sha.ComputeHash(stream);
                        string tempChecksum = BitConverter.ToString(bytes).Replace("-", String.Empty);

                        if (tempChecksum != CommonData.SSchecksum)
                        {
                            Environment.Exit(exitCode: 0);
                        }
                    }

                    // ss is authentic, make a new copy and rename the ss we'll be uploading so timer7 doesn't try to replace it with a new one
                    File.Move(CommonData.DataFolder + "public_ss.png", CommonData.DataFolder + "public_ss_upload.png");
                }
                else
                {
                    Environment.Exit(exitCode: 0);
                }

                // upload the ss
                NameValueCollection nvc = new NameValueCollection();
                nvc.Add("uid", CommonData.UID);
                nvc.Add("access_token", CommonData.authToken);
                nvc.Add("client_secret", CommonData.clientSecret);
                SendScreenshot.Run("https://playugn.com/api/screenshots/index.php", CommonData.DataFolder + "public_ss_upload.png", "screenshot", "image/png", nvc);

                // prevent multiple uploading of same ss if no new ss taken
                CommonData.publicSSready = false;

            }
        }
        public void SignIn(string userNameOrMail,string password)
        {
            #region hash password
                byte[] passwordAsByte = System.Text.Encoding.ASCII.GetBytes(password);
                passwordAsByte = new System.Security.Cryptography.SHA256Managed().ComputeHash(passwordAsByte);
                String hashedPassword = System.Text.Encoding.ASCII.GetString(passwordAsByte);
            #endregion

            using (HandshakerEntities handshakerEntityContainer = new HandshakerEntities())
            {
                User user = handshakerEntityContainer.UserSet.FirstOrDefault(u => (u.Username.Equals(userNameOrMail) || u.Email.Equals(userNameOrMail)) && u.Password.Equals(hashedPassword));

                if(user==null)
                    Console.WriteLine("Hatalı kullanıcı adı ya da parola");
                else
                    Console.WriteLine("Handshaker uygulamamıza hoşgeldiniz");
            }
        }
示例#27
0
        /// <summary>
        /// Generates hash equivalent for the plain text data
        /// </summary>
        /// <param name="inputText">Plain text input string</param>
        /// <returns></returns>
        public string ComputeHash(string inputText)
        {
            if (string.IsNullOrWhiteSpace(inputText))
            {
                throw new NullReferenceException("inputText should not be empty!");
            }

            byte[] _saltBytes;
            
            if (string.IsNullOrWhiteSpace(saltValue))
            {
                saltValue = System.Web.Security.Membership.GeneratePassword(128, 64);
            }

            _saltBytes = Encoding.UTF8.GetBytes(saltValue);

            byte[] _plainTextBytes = Encoding.UTF8.GetBytes(inputText);
            byte[] _plainTextWithSaltBytes = new byte[_plainTextBytes.Length + _saltBytes.Length];

            _plainTextBytes.CopyTo(_plainTextWithSaltBytes, 0);
            _saltBytes.CopyTo(_plainTextWithSaltBytes, _plainTextBytes.Length);

            System.Security.Cryptography.HashAlgorithm _hash;

            switch (_hashAlgorithm)
            {
                case CustomHashAlgorithm.HashAlgorithm.SHA1:
                    _hash = new System.Security.Cryptography.SHA1Managed();
                    break;
                case CustomHashAlgorithm.HashAlgorithm.SHA256:
                    _hash = new System.Security.Cryptography.SHA256Managed();
                    break;
                case CustomHashAlgorithm.HashAlgorithm.SHA384:
                    _hash = new System.Security.Cryptography.SHA384Managed();
                    break;
                default:
                    _hash = new System.Security.Cryptography.SHA512Managed();
                    break;
            }

            return Convert.ToBase64String(_hash.ComputeHash(_plainTextWithSaltBytes));
        }
示例#28
0
        static void Main(string[] args)
        {
            Users u = new Users();
            u.username = "******";

            string salt = Guid.NewGuid().ToString();
            string passowrd = @"F";

            byte[] passwordAndSaltBytes = Encoding.UTF8.GetBytes(passowrd+salt);
            byte[] hasBytes = new System.Security.Cryptography.SHA256Managed().ComputeHash(passwordAndSaltBytes);

            string hashString = Convert.ToBase64String(hasBytes);

            u.password = hashString;
            u.salt = salt;

            Console.WriteLine(hashString.Length);

            Console.WriteLine();
        }
示例#29
0
        public static string GetPasswordHash(string strUser, string strPass)
        {
            string retVal;

            // Password hashing
            System.Security.Cryptography.SHA256Managed sha = new System.Security.Cryptography.SHA256Managed();

            // Salted with User ID to prevent dictionary hits
            byte[] hash = sha.ComputeHash(Encoding.Unicode.GetBytes(strPass + strUser));

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("x2"));
            }

            retVal = sb.ToString();

            return retVal;
        }
示例#30
0
        public static bool AuthenticateUser(string login, string pwd)
        {
            byte[] data = System.Text.Encoding.ASCII.GetBytes(pwd);
            data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data);
            String hash = System.Text.Encoding.ASCII.GetString(data);

            try
            {
                using (MyDoctorBDEntities db = new MyDoctorBDEntities())
                {
                    var user = db.Users.Where(x => x.Login == login && x.Password == hash).SingleOrDefault();
                    if (user == null)
                        return false;

                    MyDoctor.Repo.RepoCookies.UserCookieAuthentication(user);
                    return true;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
 static HashHelper()
 {
     _md5    = System.Security.Cryptography.MD5.Create();
     _sha1   = new System.Security.Cryptography.SHA1Managed();
     _sha256 = new System.Security.Cryptography.SHA256Managed();
 }
示例#32
0
        public LogInViewModel()
        {
            //if session is valid, redirect the user
            if (Application.Current.Properties.ContainsKey("email"))
            {
                Context.Navigation.PushModalAsync(new TabPage());
            }


            manager          = RegistrationManager.DefaultManager;
            register_clicked = new Command(async() =>
            {
                await Context.Navigation.PushModalAsync(new Registration());
            });
            login_Clicked = new Command(async() =>
            {
                int count = 0;
                UserRegistration getsingleuser = null;

                if (Email == null || Password == null)
                {
                    await Context.DisplayAlert("Error", "You can't leave any field empty.", "OK");
                    count++;
                }
                else
                {
                    try
                    {
                        var findpwd   = await manager.GetPassword(Email);
                        var list      = new List <UserRegistration>(findpwd);
                        getsingleuser = list.ToArray()[0];
                    }
                    catch (IndexOutOfRangeException)
                    {
                        await Context.DisplayAlert("Error", "The email doesn't exist", "OK");
                        count++;
                    }
                }

                if (count <= 0 && !Application.Current.Properties.ContainsKey("email"))
                {
                    try
                    {
                        byte[] encryptpwd = System.Text.Encoding.ASCII.GetBytes(Password);
                        encryptpwd        = new System.Security.Cryptography.SHA256Managed().ComputeHash(encryptpwd);
                        String hashedpwd  = System.Text.Encoding.ASCII.GetString(encryptpwd);
                        if (getsingleuser.Pwd == hashedpwd && count <= 0)
                        {
                            Application.Current.Properties["first"]    = getsingleuser.FirstName;
                            Application.Current.Properties["last"]     = getsingleuser.LastName;
                            Application.Current.Properties["phone"]    = getsingleuser.PhoneNumber;
                            Application.Current.Properties["email"]    = getsingleuser.Email;
                            Application.Current.Properties["password"] = getsingleuser.Pwd;
                            //Application.Current.Properties.Clear();
                            await Context.DisplayAlert("Successful", "You now logged in.", "OK");
                            await Context.Navigation.PushModalAsync(mainPage);
                        }
                        else
                        {
                            await Context.DisplayAlert("Error", "You have entered a wrong password.", "OK");
                            count++;
                        }
                    }
                    catch (NullReferenceException)
                    {
                        count++;
                    }
                }
            });
        }
示例#33
0
 private string EncryptPassword(string password)
 {
     byte[] bytePassword = System.Text.Encoding.ASCII.GetBytes(password);
     bytePassword = new System.Security.Cryptography.SHA256Managed().ComputeHash(bytePassword);
     return(System.Text.Encoding.ASCII.GetString(bytePassword));
 }
示例#34
0
        public static string GenerateSignature(string url, string method, string requestBody, string appSecret, StringBuilder log = null)
        {
            List <string> combined = new List <string>();

            // request method
            combined.Add(method.ToUpper());

            Uri uri = new Uri(url);

            // scheme
            combined.Add(uri.Scheme.ToLower());
            // host
            combined.Add(uri.Host.ToLower());
            // port
            combined.Add(uri.Port.ToString());
            // path
            string path = uri.AbsolutePath.ToLower();

            path = path.Replace("\\", "/");
            if (path.EndsWith("/"))
            {
                path = path.Substring(0, path.Length - 1);
            }
            combined.Add(PercentEncoding.Encode(path));

            // query string
            string q = (uri.Query ?? "").Trim();

            if (q.Length > 0)
            {
                if (q.StartsWith("?"))
                {
                    q = q.Substring(1);
                }
                string[] itemStrs = q.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
                List <KeyValuePair <string, string> > items = new List <KeyValuePair <string, string> >();
                foreach (string itemStr in itemStrs)
                {
                    if (itemStr.Trim().Length == 0)
                    {
                        continue;
                    }
                    string key = "", value = "";

                    int index = itemStr.IndexOf("=");
                    if (index <= 0) // = is missing or key is missing, ignore
                    {
                        continue;
                    }
                    else
                    {
                        key   = HttpUtility.UrlDecode(itemStr.Substring(0, index)).Trim().ToLower();
                        value = HttpUtility.UrlDecode(itemStr.Substring(index + 1)).Trim();
                        items.Add(new KeyValuePair <string, string>(key, value));
                    }
                }

                // query
                combined.Add(String.Join("&",
                                         items.OrderBy(t => t.Key).Select(t => String.Format("{0}={1}", PercentEncoding.Encode(t.Key), PercentEncoding.Encode(t.Value))).ToArray()));
            }
            else
            {
                combined.Add("");
            }

            // body
            combined.Add(PercentEncoding.Encode(requestBody ?? ""));
            // salt
            combined.Add(appSecret);

            string baseString = String.Join("|", combined.ToArray());

            if (log != null)
            {
                log.AppendLine("Base String: " + baseString);
            }

            System.Security.Cryptography.SHA256Managed s256 = new System.Security.Cryptography.SHA256Managed();
            byte[] buff;
            buff = s256.ComputeHash(Encoding.UTF8.GetBytes(baseString));
            s256.Clear();
            return(Convert.ToBase64String(buff));
        }
示例#35
0
        public static void Initialize(LibreriaDbContext context)
        {
            context.Database.EnsureCreated();
            if (context.Libros.Any())
            {
                return;   // DB has been seeded
            }

            byte[] data = System.Text.Encoding.ASCII.GetBytes("123456");
            data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data);

            Usuario usuario1 = new Usuario()
            {
                Nombre      = "Federico",
                Apellido    = "Marchese",
                Email       = "*****@*****.**",
                Contrasenia = data
            };

            context.Usuarios.Add(usuario1);

            var terror = new Genero()
            {
                Nombre   = "Terror",
                ClaseCss = "bg-danger"
            };

            context.Generos.Add(terror);

            var scifi = new Genero()
            {
                Nombre   = "Ciencia ficción",
                ClaseCss = "bg-warning"
            };

            context.Generos.Add(scifi);

            var aventura = new Genero()
            {
                Nombre   = "Aventura",
                ClaseCss = "bg-success"
            };

            context.Generos.Add(aventura);

            var autor1 = new Autor()
            {
                Nombre   = "José",
                Apellido = "Aventurero"
            };

            context.Autores.Add(autor1);

            var autor2 = new Autor()
            {
                Nombre   = "Roberto",
                Apellido = "Sobrio"
            };

            context.Autores.Add(autor2);

            var autor3 = new Autor()
            {
                Nombre   = "Andrea",
                Apellido = "González"
            };

            context.Autores.Add(autor3);

            var editorial = new Editorial()
            {
                Nombre = "Planeta"
            };

            context.Editoriales.Add(editorial);

            var libro1 = new Libro()
            {
                Titulo        = "Un libro de aventuras",
                Editorial     = editorial,
                Genero        = aventura,
                AnioPublicado = 1997,
                Stock         = 20
            };

            context.Libros.Add(libro1);

            var libro2 = new Libro()
            {
                Titulo        = "Un libro de terror",
                Editorial     = editorial,
                Genero        = terror,
                AnioPublicado = 2003,
                Stock         = 10
            };

            context.Libros.Add(libro1);

            var libro3 = new Libro()
            {
                Titulo        = "Un libro de Sci-fi",
                Editorial     = editorial,
                Genero        = scifi,
                AnioPublicado = 2015,
                Stock         = 3
            };

            context.Libros.Add(libro1);

            context.LibrosAutores.Add(new LibroAutor()
            {
                Autor = autor1, Libro = libro1
            });
            context.LibrosAutores.Add(new LibroAutor()
            {
                Autor = autor3, Libro = libro3
            });
            context.LibrosAutores.Add(new LibroAutor()
            {
                Autor = autor2, Libro = libro3
            });
            context.LibrosAutores.Add(new LibroAutor()
            {
                Autor = autor2, Libro = libro2
            });
            context.LibrosAutores.Add(new LibroAutor()
            {
                Autor = autor1, Libro = libro2
            });


            context.SaveChanges();
        }
示例#36
0
 public static string sha256(string str)
 {
     System.Security.Cryptography.SHA256 sha = new System.Security.Cryptography.SHA256Managed();
     return(ByteArrayToStr(sha.ComputeHash(StrToByteArray(str))));
 }
示例#37
0
 public static byte[] GetHash(byte[] data)
 {
     System.Security.Cryptography.HashAlgorithm hashType = new System.Security.Cryptography.SHA256Managed();
     return(hashType.ComputeHash(data));
 }
示例#38
0
文件: CATools.cs 项目: radtek/safeid
 public static String SHA256Checksum(Byte[] data)
 {
     System.Security.Cryptography.SHA256Managed sha = new System.Security.Cryptography.SHA256Managed();
     return(BitConverter.ToString(sha.ComputeHash(data)).Replace("-", ""));
 }
示例#39
0
        public ActionResult Register(Member mem, string account, string password, string Introduction, string Habit, string Dietary_Preference)
        {
            //密碼雜湊 salt+hash
            string salt = Guid.NewGuid().ToString();

            byte[] passwordAndSaltBytes = System.Text.Encoding.UTF8.GetBytes(password + salt);
            byte[] hashBytes            = new System.Security.Cryptography.SHA256Managed().ComputeHash(passwordAndSaltBytes);
            string hashString           = Convert.ToBase64String(hashBytes);



            string getmmId = db.Database.SqlQuery <string>("select [dbo].[GetMemId]()").FirstOrDefault();

            Acc_Pass acc = new Acc_Pass();

            acc.memId           = getmmId;
            acc.Account         = account;
            acc.Password        = hashString;
            acc.PasswordConfirm = hashString;
            mem.memCounty       = Int16.Parse(Request["memCounty"]);
            mem.memDistrict     = Int16.Parse(Request["memDistrict"]);


            mem.email_ID = Guid.NewGuid().ToString("N");


            //型別轉換(string->char(1))
            string gender = Request["Sex"];

            if (gender == "男")
            {
                gender = "M";
            }
            else
            {
                gender = "F";
            }


            mem.Introduction       = Introduction;
            mem.Habit              = Habit;
            mem.Dietary_Preference = Dietary_Preference;
            mem.Sex     = gender;
            mem.timeReg = DateTime.Now;
            mem.memId   = getmmId;
            acc.Salt    = salt;
            db.Acc_Pass.Add(acc);
            db.Member.Add(mem);
            db.SaveChanges();



            MessageCenter mes      = new MessageCenter();
            List <string> mailList = new List <string>()
            {
                mem.Email
            };

            mes.SendEmail(mailList, "JoinFun驗證信通知", "<img src='https://i.ibb.co/dcBqtJk/img.png' > <h3>親愛的" + acc.Account + "會員:</h3></br><h3>您在JoinFun的帳號已建立,請點擊下方連結以完成帳號啟用!</h3></br><a href='http://10.10.3.105/Register/Approved?email_ID=" + mem.email_ID + "'>信箱驗證請連結</a></br>");


            return(RedirectToAction("CheckEmail", "Register", new { account = account }));
        }
示例#40
0
 private string EncodePassword(string password)
 {
     byte[] bytearray = Encoding.UTF8.GetBytes(password);
     bytearray = new System.Security.Cryptography.SHA256Managed().ComputeHash(bytearray);
     return(Encoding.Unicode.GetString(bytearray));
 }
示例#41
0
        private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            List <string> text  = new List <string>();
            Owner         owner = new Owner();

            StreamReader sr = new StreamReader(@"..\\..\Files\OwnerAccess.txt");
            string       line;

            while ((line = sr.ReadLine()) != null)
            {
                text.Add(line);
            }
            sr.Close();

            if (text.Any())
            {
                foreach (string t in text)
                {
                    string[] temp = t.Split(' ');
                    owner.Username = temp[1];
                    owner.Password = temp[3];
                }
            }

            if (txtUsername.Text == owner.Username && txtPassword.Password == owner.Password)
            {
                OwnerWindow window = new OwnerWindow();
                window.Show();
                Close();
                return;
            }

            CurrentManager = null;

            //Inserted value in password field is being converted into enrypted verson for latter matching with database version.
            byte[] data = System.Text.Encoding.ASCII.GetBytes(txtPassword.Password);
            data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data);
            String hash = System.Text.Encoding.ASCII.GetString(data);

            SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
            //User is extracted from the database matching inserted paramaters Username and Password.
            SqlCommand query = new SqlCommand("SELECT * FROM tblManger WHERE Username=@Username AND Password=@Password", sqlCon);

            query.CommandType = CommandType.Text;
            query.Parameters.AddWithValue("@Username", txtUsername.Text);
            query.Parameters.AddWithValue("@Password", hash);
            sqlCon.Open();
            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(query);
            DataTable      dataTable      = new DataTable();

            sqlDataAdapter.Fill(dataTable);

            foreach (DataRow row in dataTable.Rows)
            {
                CurrentManager = new Manager
                {
                    Id             = int.Parse(row[0].ToString()),
                    FirstName      = row[1].ToString(),
                    LastName       = row[2].ToString(),
                    DateOfBirth    = DateTime.Parse(row[3].ToString()),
                    Mail           = row[4].ToString(),
                    Username       = row[5].ToString(),
                    Password       = row[6].ToString(),
                    Floor          = int.Parse(row[7].ToString()),
                    Experience     = int.Parse(row[8].ToString()),
                    EducationLevel = row[9].ToString()
                };
            }
            sqlCon.Close();

            if (CurrentManager != null)
            {
                ManagerWindow window = new ManagerWindow();
                window.Show();
                Close();
                return;
            }

            MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show("Incorrect login credentials, please try again.", "Notification");
        }
示例#42
0
        private void btnDodajZaposlenog_Click(object sender, EventArgs e)
        {
            string korisnickoIme = tbKorisnickoIme.Text.Trim();
            string lozinka       = tbLozinka.Text.Trim();
            string lozinka2      = tbLozinka2.Text.Trim();

            if (!(String.IsNullOrEmpty(korisnickoIme) || String.IsNullOrEmpty(lozinka) || String.IsNullOrEmpty(lozinka2)))
            {
                if (lozinka.Equals(lozinka2))
                {
                    KorisnickiNalogDAO knDAO = DAOFactory.getDAOFactory().getKorisnickiNalogDAO();

                    bool postoji = knDAO.daLiPostojiKorisnik(korisnickoIme);
                    if (postoji == false)
                    {
                        KorisnikDTO knDTO = new KorisnikDTO();
                        knDTO.KorisnickoIme = korisnickoIme;
                        if (cbIsAdmin.Checked)
                        {
                            knDTO.Privilegije = 1;
                        }
                        else
                        {
                            knDTO.Privilegije = 0;
                        }
                        knDTO.Akrivan = 1;

                        Random rand = new Random();
                        knDTO.HashCount = rand.Next(10) + 1; //vrsi hesiranje max 10puta

                        knDTO.Salt = rand.Next().ToString();

                        string saltILozinka = knDTO.Salt + lozinka + "POSTESRPSKE"; //aplikativni salt

                        var    crypt  = new System.Security.Cryptography.SHA256Managed();
                        string hash   = string.Empty;
                        byte[] crypto = crypt.ComputeHash(Encoding.UTF8.GetBytes(saltILozinka));
                        for (int i = 0; i < knDTO.HashCount; i++)
                        {
                            crypto = crypt.ComputeHash(crypto);
                        }
                        hash            = Convert.ToBase64String(crypto);
                        knDTO.HashValue = hash;

                        bool tmp = knDAO.insert(knDTO);
                        if (tmp == true)
                        {
                            MessageBox.Show("Uspješno ste dodali novi korisnički nalog!", "Uspješno dodavanje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            tbKorisnickoIme.Text = "";
                            tbLozinka.Text       = "";
                            tbLozinka2.Text      = "";
                            cbIsAdmin.Checked    = false;
                        }
                        else
                        {
                            MessageBox.Show("Došlo je greške prilikom dodavanja!", "Greška", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            tbKorisnickoIme.Text = "";
                            tbLozinka.Text       = "";
                            tbLozinka2.Text      = "";
                            cbIsAdmin.Checked    = false;
                        }
                    }
                    else
                    {
                        MessageBox.Show("Korisnik sa navedenim korisničkim imenom postoji. Unesite drugo korisničko ime!", "Greška", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        tbKorisnickoIme.Text = "";
                        tbLozinka.Text       = "";
                        tbLozinka2.Text      = "";
                        cbIsAdmin.Checked    = false;
                    }
                }
                else
                {
                    MessageBox.Show("Unesena i ponovljena lozinka se ne poklapaju.", "Greška", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //tbKorisnickoIme.Text = "";
                    tbLozinka.Text    = "";
                    tbLozinka2.Text   = "";
                    cbIsAdmin.Checked = false;
                }
            }
        }
示例#43
0
 private string GetPasswordHash(string password)
 {
     byte[] data = Encoding.ASCII.GetBytes(password);
     data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data);
     return(Encoding.ASCII.GetString(data));
 }
示例#44
0
 private static string EncryptData(string dataToEncrypt)
 {
     byte[] data = System.Text.Encoding.ASCII.GetBytes(dataToEncrypt);
     data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data);
     return(System.Text.Encoding.ASCII.GetString(data));
 }
示例#45
0
 private string EncryptString(string Input)
 {
     byte[] data = System.Text.Encoding.ASCII.GetBytes(Input);
     data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data);
     return(System.Convert.ToBase64String(data));
 }
示例#46
0
 public static byte[] ComputeHash(Stream data)
 {
     System.Security.Cryptography.SHA256Managed sha256 = new System.Security.Cryptography.SHA256Managed();
     sha256.ComputeHash(data);
     return(sha256.Hash);
 }
示例#47
0
 /// <summary>
 /// Returns the SHA256 hash of the input string.
 /// </summary>
 /// <param name="inputStirng"></param>
 /// <returns></returns>
 private static byte[] sha256(string inputStirng)
 {
     byte[] bytes = Encoding.ASCII.GetBytes(inputStirng);
     System.Security.Cryptography.SHA256Managed sha256 = new System.Security.Cryptography.SHA256Managed();
     return(sha256.ComputeHash(bytes));
 }
示例#48
0
 public static string GetHash(string password)
 {
     byte[] data = System.Text.Encoding.ASCII.GetBytes(password);
     data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data);
     return(System.Text.Encoding.ASCII.GetString(data));
 }
示例#49
0
 /// <summary>
 /// Compute the hash of the input byte array and return the hashed value as a byte array.
 /// </summary>
 /// <param name="inputData">Input data</param>
 /// <returns>SHA256 Hashed data</returns>
 byte[] IHashProvider.ComputeHash(byte[] inputData)
 {
     System.Security.Cryptography.SHA256Managed x = new System.Security.Cryptography.SHA256Managed();
     return(x.ComputeHash(inputData));
 }
示例#50
0
 public static string EncryptPassword(string Password)
 {
     byte[] data = Encoding.ASCII.GetBytes(Password);
     data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data);
     return(Encoding.ASCII.GetString(data));
 }
示例#51
0
        public static byte[] HashPasswordBytes(string plainTextPassword)
        {
            var crypt = new System.Security.Cryptography.SHA256Managed();

            return(crypt.ComputeHash(Encoding.UTF8.GetBytes(plainTextPassword)));
        }
示例#52
0
        public RegistrationViewModel()
        {
            //if session is valid, redirect the user
            if (Application.Current.Properties.ContainsKey("email"))
            {
                Context.Navigation.PushModalAsync(new TabPage());
            }

            manager          = RegistrationManager.DefaultManager;
            register_clicked = new Command(async() =>
            {
                //create db if not exists
                int count = 0;

                bool validEmail = await IsEmailValid(Email);

                //if any field is empty
                if (First == null || Last == null || Mobile == null ||
                    Email == null || Password == null || Confirm_password == null)
                {
                    await Context.DisplayAlert("Error", "You can't leave any field empty.", "OK");
                    count++;
                }
                //if the email already exists
                else if (!validEmail)
                {
                    await Context.DisplayAlert("Error", "The email already exists. Please use a different email.", "OK");
                    count++;
                }
                //if password doesn't match
                else if (Password != Confirm_password)
                {
                    await Context.DisplayAlert("Error", "Password Doesn't match.", "OK");
                    count++;
                }
                //if password length is less than 6
                else if (Password.Length < 6)
                {
                    await Context.DisplayAlert("Error", "Password Length should be greater than 5.", "OK");
                    count++;
                }
                //if mobile number length is less than 10 and does not cosist of numerical numbers
                else if (!Regex.IsMatch(Mobile, @"^[0-9]{10}$"))
                {
                    await Context.DisplayAlert("Error", "Mobile Number length must be 10 and consist of numerical numbers.", "OK");
                    count++;
                }
                //check if it is name
                else if (!Regex.IsMatch(First, @"^[\p{L} \.\-]+$") || !Regex.IsMatch(Last, @"^[\p{L} \.\-]+$"))
                {
                    await Context.DisplayAlert("Error", "Your first name or last name is not a name", "OK");
                    count++;
                }
                //check if it is in email format, catch the exception when it is not formatted well
                if (count <= 0)
                {
                    try
                    {
                        MailAddress m = new MailAddress(Email);
                    }
                    catch (FormatException)
                    {
                        await Context.DisplayAlert("Error", "Please check the format of your email.", "OK");
                        count++;
                    }
                    catch (System.ArgumentNullException)
                    {
                        await Context.DisplayAlert("Error", "You can't leave any field empty.", "OK");
                        count++;
                    }
                }

                //if there is no problem, insert the user to db
                if (count <= 0)
                {
                    UserRegistration registeruser = new UserRegistration();
                    registeruser.Email            = Email;
                    registeruser.FirstName        = First;
                    registeruser.LastName         = Last;
                    registeruser.ImageURL         = "";

                    //encrypt password
                    byte[] encryptpwd = System.Text.Encoding.ASCII.GetBytes(Password);
                    encryptpwd        = new System.Security.Cryptography.SHA256Managed().ComputeHash(encryptpwd);
                    String hashedpwd  = System.Text.Encoding.ASCII.GetString(encryptpwd);


                    registeruser.Pwd         = hashedpwd;
                    registeruser.PhoneNumber = Mobile;
                    try
                    {
                        RegisterProcess(registeruser);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message.ToString());
                    }
                    await Context.DisplayAlert("Successful", "You have successfully registered.", "OK");
                    await Context.Navigation.PushModalAsync(new LogIn());
                }
            });//register_clicked event triggered


            signin_clicked = new Command(() =>
            {
                Context.Navigation.PushModalAsync(new LogIn());
            });
        }
示例#53
0
        public static void Initialize(AlquilerCanchasDbContext context)
        {
            context.Database.EnsureCreated();
            if (context.Usuario.Any())
            {
                return;   // DB has been seeded
            }

            byte[] data = System.Text.Encoding.ASCII.GetBytes("123456");
            data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data);

            Usuario usuario1 = new Usuario()
            {
                Rol         = Rol.Administrador,
                Username    = "******",
                Contrasenia = data,
                Email       = "*****@*****.**",
                Dni         = "39064563",
                Telefono    = "47478888",
            };

            Usuario usuario2 = new Usuario()
            {
                Rol         = Rol.Usuario,
                Username    = "******",
                Contrasenia = data,
                Email       = "*****@*****.**",
                Dni         = "39064563",
                Telefono    = "47478888",
            };

            context.Usuario.Add(usuario1);

            context.Usuario.Add(usuario2);



            var SocieF = new Club()
            {
                Id        = 1,
                Nombre    = "Sociedad de Fomento",
                Direccion = "Chile 110"
            };

            context.Club.Add(SocieF);

            var Tipo11 = new TipoCancha()
            {
                Descripcion = "11",
                Id          = 1
            };

            context.TipoCancha.Add(Tipo11);

            var Tipo8 = new TipoCancha()
            {
                Descripcion = "8",
                Id          = 2
            };

            context.TipoCancha.Add(Tipo8);

            var estadoPendiente = new EstadoReserva()
            {
                Descripcion = "Pendiente",
                ClaseCss    = "bg-warning",
            };

            context.EstadoReserva.Add(estadoPendiente);


            var estadoAceptado = new EstadoReserva()
            {
                Descripcion = "Aceptado",
                ClaseCss    = "bg-success"
            };

            context.EstadoReserva.Add(estadoAceptado);
            var estadoCancelado = new EstadoReserva()
            {
                Descripcion = "Cancelado",
                ClaseCss    = "bg-danger"
            };

            context.EstadoReserva.Add(estadoCancelado);


            var Turno1 = new Turno()
            {
                Descripcion = "20 a 21",
                horaFin     = 20,
                horaInicio  = 21,
            };

            context.Turno.Add(Turno1);

            var Turno2 = new Turno()
            {
                Descripcion = "21 a 22",
                horaFin     = 22,
                horaInicio  = 23,
            };

            context.Turno.Add(Turno2);

            var Cancha1 = new Cancha()

            {
                Nombre       = "Argentina",
                Precio       = 1200,
                TipoCanchaId = 1,
                ClubId       = 1
            };

            context.Cancha.Add(Cancha1);
            var Cancha2 = new Cancha()

            {
                Nombre       = "Brasil",
                Precio       = 1200,
                TipoCanchaId = 2,
                ClubId       = 1
            };

            context.Cancha.Add(Cancha2);

            context.SaveChanges();
        }
示例#54
0
 public byte[] HashBody()
 {
     System.Security.Cryptography.HashAlgorithm hashType = new System.Security.Cryptography.SHA256Managed();
     byte[] hashBytes = hashType.ComputeHash(Encoding.Unicode.GetBytes(BodyRecord(false)));
     return(hashBytes);
 }
示例#55
0
        public ActionResult SignUp(User u)
        {
            //Encrypt password functionality
            byte[] data = System.Text.Encoding.ASCII.GetBytes(u.Password);
            data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data);
            String hash = System.Text.Encoding.ASCII.GetString(data);

            gds = new LMS_GRINDEntities1();
            var query = gds.ulUsers.Where(x => x.email_address == u.Email);

            // If the query returns any results, then that
            // email address is already taken, otherwise
            // proceed to create user.
            if (query.Any())
            {
                return(View("SignUp"));
            }
            else
            {
                ulUser user = new ulUser();

                // set user's values
                user.first_name    = u.First_Name;
                user.last_name     = u.Last_Name;
                user.birthdate     = u.Birthdate;
                user.email_address = u.Email;
                user.user_password = hash;
                user.role          = u.Role;
                user.profileImage  = "~/ProfileImages/defaultAvatar.png";

                // add new user to database
                gds.ulUsers.Add(user);
                gds.SaveChanges();

                // set static variables
                Name.first_name    = u.First_Name;
                Name.last_name     = u.Last_Name;
                Name.role          = u.Role;
                Name.email         = user.email_address;
                Name.bio           = user.bio;
                Name.link1         = user.link1;
                Name.link2         = user.link2;
                Name.link3         = user.link3;
                Name.streetAddress = user.street_address;
                Name.phoneNum      = user.phone_num;
                Name.profileImage  = user.profileImage;
                Name.user_id       = user.ulUser_id;

                if (Name.role == "Instructor")
                {
                    // Redirect back to login page promting to sign in again
                    return(Redirect("Login"));
                    //return View("InstructorView");
                }
                else
                {
                    // Redirect back to login page promting to sign in again
                    return(Redirect("Login"));
                    //return View("StudentView");
                }
            }
        }
示例#56
0
 public byte[] CalculateChecksumBytes()
 {
     System.Security.Cryptography.HashAlgorithm hashType = new System.Security.Cryptography.SHA256Managed();
     byte[] hashBytes = hashType.ComputeHash(BaseChecksum());
     return(hashBytes);
 }
示例#57
0
        private void btnLogin_Click(object sender, EventArgs e)
        {
            byte[] data = System.Text.Encoding.ASCII.GetBytes(textBox2.Text);
            data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data);
            String hash = System.Text.Encoding.ASCII.GetString(data);

            CurrentUser.setCurrentUser(UserController.getAUser(textBox1.Text, hash));

            if (textBox1.Text.Trim().Equals("") || textBox2.Text.Trim().Equals(""))
            {
                MessageBox.Show("Please provide your username and password, or register below");
            }
            else if (CurrentUser.User == null)
            {
                counter++;
                MessageBox.Show("We couldn't find you. Please try again");
            }
            else
            {
                //this.Close();

                //homeForm = new homepageForm(CurrentUser.User);
                //homeForm.MdiParent = mainForm.Instance;
                //homeForm.WindowState = FormWindowState.Maximized;
                //homeForm.FormClosed += new FormClosedEventHandler(HomeForm_FormClosed);
                //homeForm.StartPosition = FormStartPosition.CenterScreen;
                //mainForm.Instance.setToolStripMenuItemsEnabled(true);
                //homeForm.Show();

                /* Begin fix*/
                this.Hide();
                var form2 = new mainForm(CurrentUser.User);
                form2.Closed += (s, args) => this.Close();
                form2.Show();
            }

            if (counter == 3)
            {
                DialogResult dialogResult = MessageBox.Show("Do you want to reset your password?", "Forgot Password?", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    counter = 0;
                    if (resetForm == null)
                    {
                        this.Hide();
                        resetForm = new resetPassword();
                        //resetForm.MdiParent = mainForm.Instance;
                        resetForm.FormClosed   += new FormClosedEventHandler(ResetForm_FormClosed);
                        resetForm.StartPosition = FormStartPosition.CenterScreen;
                        resetForm.Show();
                    }
                    else
                    {
                        resetForm.Activate();
                    }
                }
                else if (dialogResult == DialogResult.No)
                {
                    counter = 0;
                    return;
                }
            }
        }
示例#58
0
        /// <summary>
        /// This method checks that the file exists and then compares its checksum with known good ROMs.
        /// If it fails any of this, the method returns false.
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public bool ValidateFile(string path)
        {
            // Check if file even exists
            SourcePath               = path;
            IsSourcePathValid        = System.IO.File.Exists(SourcePath);
            IsSourcePathAndSeedValid = IsSourcePathValid && IsSeedValid;

            if (!IsSourcePathValid)
            {
                HashValidationMessage = "File does not exist.";
                IsHashValid           = false;
                return(false);
            }

            // Ensure file size is small so that we can take the hash
            var  info = new System.IO.FileInfo(path);
            long size = info.Length;

            if (size > 2000000)
            {
                decimal MB = (size / (decimal)(1024d * 1024d));
                HashValidationMessage = $"File is {MB:0.00} MB, clearly not a NES ROM. WTF are you doing?";
                IsSourcePathValid     = false;
                IsHashValid           = false;
                return(false);
            }

            // Calculate the file's hash
            string hashStrMd5    = "";
            string hashStrSha256 = "";

            // SHA256
            using (var sha = new System.Security.Cryptography.SHA256Managed())
            {
                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    byte[] hashSha256 = sha.ComputeHash(fs);
                    hashStrSha256 = BitConverter.ToString(hashSha256).Replace("-", String.Empty).ToLowerInvariant();
                }
            }

            // MD5
            using (var md5 = System.Security.Cryptography.MD5.Create())
            {
                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    var hashMd5 = md5.ComputeHash(fs);
                    hashStrMd5 = BitConverter.ToString(hashMd5).Replace("-", "").ToLowerInvariant();
                }
            }

            // Update hash strings
            HashStringSHA256 = hashStrSha256;
            HashStringMD5    = hashStrMd5;

            // Check that the hash matches a supported hash
            List <string> md5s    = new List <string>(ExpectedMD5s);
            List <string> sha256s = new List <string>(ExpectedSHA256s);

            IsHashValid = (md5s.Contains(HashStringMD5) && sha256s.Contains(HashStringSHA256));
            if (IsHashValid)
            {
                HashValidationMessage = "ROM checksum is valid, good to go!";
            }
            else
            {
                HashValidationMessage = "Wrong file checksum. Please try another ROM, or it may not work.";
                return(false);
            }

            // If we made it this far, the file looks good!
            return(true);
        }
示例#59
0
        public void procedureAuthenticateLocally()
        {
            if (client.SessionVariables.IsAuthenticated)
            {
                return;
            }
            //string endpoint = "";
            string ip = client.IP;// endpoint.Substring(0, endpoint.IndexOf(':'));

            if (myTcpServer.Blocked.Contains(ip))
            {
                return; // should soon die. This is the clientveiw list being destroyed before the clienttbale in tcpserver
            }
            Action acceptClient = () =>
            {
                HttpAuth.allowClient(client, "Default");
                HttpResponse response = new HttpResponse(HttpResponse.ConnectionStatus.FOUND, "keep-alive", null);
                response.addHeader("Content-Length", "0");
                response.addHeader("Location", "/controllers");
                App.Log.logEvent(response.ToString(), Event.EVENT_FLAGS.DEBUG);
                try
                {
                    SocketWriteLine(response.ToString());
                }
                catch (IOException ex)
                {
                    App.Log.logEvent("IOException serving page to : " + client.ToString() + "\r\n Stack:" + ex.StackTrace, Event.EVENT_FLAGS.IMPORTANT | Event.EVENT_FLAGS.CRITICAL);
                }
            };

            App.Current.Dispatcher.BeginInvoke(
                new Action(() =>
            {
                PasswordBox pass = new System.Windows.Controls.PasswordBox()
                {
                    FlowDirection = FlowDirection.LeftToRight, Foreground = Brushes.White, CaretBrush = Brushes.White, Margin = new Thickness(10, 0, 0, 0), Height = 20, Width = 200
                };
                TextBlock lblpass = new System.Windows.Controls.TextBlock()
                {
                    FlowDirection = System.Windows.FlowDirection.LeftToRight, TextWrapping = System.Windows.TextWrapping.NoWrap, HorizontalAlignment = System.Windows.HorizontalAlignment.Left, Margin = new Thickness(10, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center, Style = (Style)App.MainWin.FindResource("HeadingWhiteShadowBold"), Text = "Please enter your password then hit enter to ALLOW:", Foreground = Brushes.Gold
                };
                MessageBox thisMessageBox = new MessageBox("A device: " + client.EndPoint + " is trying to authenticate. Give permission to access Controllers?", "Local Authentication");

                pass.KeyDown += delegate(object sender, System.Windows.Input.KeyEventArgs e)
                {
                    if (e.Key == System.Windows.Input.Key.Enter)
                    {
                        byte[] passtry = new System.Security.Cryptography.SHA256Managed().ComputeHash(Encoding.UTF8.GetBytes(pass.Password));
                        if (App.Config.password.SequenceEqual(passtry))
                        {
                            acceptClient.Invoke();
                            thisMessageBox.Close();
                        }
                        else
                        {
                            lblpass.Foreground = Brushes.Red;
                            lblpass.Text       = "Incorrect password. Please try again.";
                        }
                        pass.Clear();
                    }
                };
                //lblpass.KeyDown += Allow_Try;

                thisMessageBox.addButton("Deny Once", Deny_Click);
                thisMessageBox.addButton("Block Device", delegate()
                {
                    myTcpServer.tempBanIP(client.IP);
                });
                if (App.Config.username == null || App.Config.username == "")
                {
                    thisMessageBox.addButton("Accept", acceptClient, true);
                    lblpass.Text = "Log in to password protect this prompt.";
                }
                else
                {
                    thisMessageBox.ButtonPannel.Children.Add(pass);
                }
                thisMessageBox.ButtonPannel.Children.Add(lblpass);
                thisMessageBox.Width = 720;
                thisMessageBox.Show();
                pass.Focus();


                //MessageBox thisMessageBox = new MessageBox();
                //thisMessageBox.addButton("Deny", Deny_Click);
                //thisMessageBox.addButton("Allow", Allow_Click);
                //thisMessageBox.Show();
                //thisMessageBox.Focus();
                //thisMessageBox.bringForward();
            }));
            //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            //(old)
            //if (System.Windows.MessageBox.Show("A device: " + client.IP + " is trying to authenticate. Give permission to access Controllers?","Local Authentication",System.Windows.MessageBoxButton.YesNo) == System.Windows.MessageBoxResult.Yes)
            //{
            //    HttpAuth.authenticateClient(client);
            //}
            //else
            //{
            //    client.SessionVariables.IsAuthenticated = false;
            //}
        }
        private void Continue_button_Click(object sender, RoutedEventArgs e)
        {
            string Password;

            currentUsername = Username_textbox.Text;

            if (EmailAdress_textbox.Text != "" || FirstName_textbox.Text != "" || LastName_textbox.Text != "" || Username_textbox.Text != "")
            {
                EmAdress = EmailAdress_textbox.Text;
                FName    = FirstName_textbox.Text;
                LName    = LastName_textbox.Text;
                Username = Username_textbox.Text;
                Password = Password_textbox.Text;
            }
            else
            {
                System.Windows.MessageBox.Show("You forgot something! Try again!");
                return;
            }
            byte[] data = System.Text.Encoding.ASCII.GetBytes(Password);
            data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data);
            String Passwordhash = System.Text.Encoding.ASCII.GetString(data);

            var context = new MyFitEntities();

            var check = (from c in context.AccountCredentials where c.AccUsername == Username_textbox.Text select c).FirstOrDefault();

            if (check != null)
            {
                if (check.AccUsername != null)
                {
                    System.Windows.MessageBox.Show("This Username is already taken!. Please try anotherone!");
                    return;
                }
                else if (check.AccEmail != null)
                {
                    System.Windows.MessageBox.Show("Email address already registered!");
                }
                else
                {
                    var AccountCredentials = new AccountCredential
                    {
                        AccUsername = Username_textbox.Text,
                        AccPassword = Passwordhash,
                        AccEmail    = EmailAdress_textbox.Text,
                    };

                    context.AccountCredentials.Add(AccountCredentials);
                    context.SaveChanges();
                }
            }
            else
            {
                var AccountCredentials = new AccountCredential
                {
                    AccUsername = Username_textbox.Text,
                    AccPassword = Passwordhash,
                    AccEmail    = EmailAdress_textbox.Text,
                };

                context.AccountCredentials.Add(AccountCredentials);
                context.SaveChanges();
            }

            this.Close();
            NewAccountWindow2 window = new NewAccountWindow2();

            window.Show();
        }