Example #1
0
 [System.Security.SecuritySafeCritical]  // auto-generated 
 public HMACSHA512 (byte[] key) { 
     m_hashName = "SHA512";
     m_hash1 = new SHA512Managed(); 
     m_hash2 = new SHA512Managed();
     HashSizeValue = 512;
     BlockSizeValue = BlockSize;
     base.InitializeKey(key); 
 }
Example #2
0
 public static string CreateSHAHash(string Phrase)
 {
     SHA512Managed HashTool = new SHA512Managed();
     Byte[] PhraseAsByte = System.Text.Encoding.UTF8.GetBytes(string.Concat(Phrase));
     Byte[] EncryptedBytes = HashTool.ComputeHash(PhraseAsByte);
     HashTool.Clear();
     return Convert.ToBase64String(EncryptedBytes);
 }
        [System.Security.SecuritySafeCritical]  // auto-generated
        public HMACSHA512 (byte[] key) {
            m_hashName = "SHA512";
#if FULL_AOT_RUNTIME
            m_hash1 = new SHA512Managed();
            m_hash2 = new SHA512Managed();
#else
            m_hash1 = GetHashAlgorithmWithFipsFallback(() => new SHA512Managed(), () => HashAlgorithm.Create("System.Security.Cryptography.SHA512CryptoServiceProvider"));
            m_hash2 = GetHashAlgorithmWithFipsFallback(() => new SHA512Managed(), () => HashAlgorithm.Create("System.Security.Cryptography.SHA512CryptoServiceProvider"));
#endif
            HashSizeValue = 512;
            BlockSizeValue = BlockSize;
            base.InitializeKey(key);
        }
Example #4
0
    public string Generatehash512(string text)
    {
        byte[] message = Encoding.UTF8.GetBytes(text);

        UnicodeEncoding UE = new UnicodeEncoding();
        byte[] hashValue;
        SHA512Managed hashString = new SHA512Managed();
        string hex = "";
        hashValue = hashString.ComputeHash(message);
        foreach (byte x in hashValue)
        {
            hex += String.Format("{0:x2}", x);
        }
        return hex;
    }
 protected override byte[] getHash()
 {
     var hashIterations = 24200;
     List<byte> hashList = new List<byte>();
     var hash = new SHA512Managed();
     var hashLength = Math.Max(plaintext.Length, cyphertext.Length);
     while (hashList.Count <= hashLength)
     {
         byte[] hashBytes = hash.ComputeHash(key);
         for (var i = 1; i < hashIterations; i++)
         {
             hashBytes = hash.ComputeHash(hashBytes);
         }
         hashList.AddRange(hashBytes);
     }
     return hashList.ToArray();
 }
Example #6
0
	SHA512Managed (SHA512Managed other)
	{
		xBuf = new byte [other.xBuf.Length];
		Array.Copy (other.xBuf, xBuf, xBuf.Length);
		xBufOff = other.xBufOff;
		byteCount1 = other.byteCount1;
		byteCount2 = other.byteCount2;
		H1 = other.H1;
		H2 = other.H2;
		H3 = other.H3;
		H4 = other.H4;
		H5 = other.H5;
		H6 = other.H6;
		H7 = other.H7;
		H8 = other.H8;
		W = new ulong [other.W.Length];
		Array.Copy (other.W, W, W.Length);
		wOff = other.wOff;
	}
        protected void btn_Register_Click(object sender, EventArgs e)
        {
            var checker    = 0;
            var FName      = HttpUtility.HtmlEncode(tb_FName.Text);
            var LName      = HttpUtility.HtmlEncode(tb_LName.Text);
            var CCNo       = HttpUtility.HtmlEncode(tb_CCNo.Text);
            var ExpDate    = HttpUtility.HtmlEncode(tb_ExpDate.Text);
            var CVV        = HttpUtility.HtmlEncode(tb_CVV.Text);
            var Email      = HttpUtility.HtmlEncode(tb_Email.Text);
            var Passwd     = HttpUtility.HtmlEncode(tb_Passwd.Text);
            var CnfmPasswd = HttpUtility.HtmlEncode(tb_CnfmPasswd.Text);
            var DOB        = HttpUtility.HtmlEncode(tb_DOB.Text);

            if (IsValidEmail(Email) == false)
            {
                lb_EmailChecker.Text      = "Invalid Email";
                lb_EmailChecker.ForeColor = Color.Red;
            }
            else if (IsValidEmail(Email) == true)
            {
                checker++;
            }
            int    scores = checkPassword(Passwd);
            string status = "";

            switch (scores)
            {
            case 1:
                status = "Weak Passwords are not allowed";
                break;

            case 2:
                status = "Weak Passwords are not allowed";
                break;

            case 3:
                status = "Weak Passwords are not allowed";
                break;

            case 4:
                status = "Weak Passwords are not allowed";
                break;

            case 5:
                //all good
                break;
            }
            lb_PasswdChecker.Text = status;
            if (scores < 4)
            {
                lb_PasswdChecker.ForeColor = Color.Red;
            }
            else
            {
                checker++;
            }
            if (CnfmPasswd != Passwd)
            {
                lb_CnfmChecker.Text      = "Passwords do not match!";
                lb_CnfmChecker.ForeColor = Color.Red;
            }
            else if (CnfmPasswd == Passwd)
            {
                checker++;
            }
            if (IsCreditCardInfoValid(CCNo, ExpDate, CVV) == false)
            {
                lb_CCMsg.Text      = "Credit Card information is not valid!";
                lb_CCMsg.ForeColor = Color.Red;
            }
            else if (IsCreditCardInfoValid(CCNo, ExpDate, CVV) == true)
            {
                lb_CCMsg.Text = "";
                checker++;
            }
            ;
            if (checker == 4)
            {
                string pwd = Passwd.Trim();;
                //Generate random "salt"
                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                byte[] saltByte = new byte[8];
                //Fills array of bytes with a cryptographically strong sequence of random values.
                rng.GetBytes(saltByte);
                salt = Convert.ToBase64String(saltByte);
                SHA512Managed hashing      = new SHA512Managed();
                string        pwdWithSalt  = pwd + salt;
                byte[]        plainHash    = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwd));
                byte[]        hashWithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt));
                finalHash = Convert.ToBase64String(hashWithSalt);
                RijndaelManaged cipher = new RijndaelManaged();
                cipher.GenerateKey();
                Key = cipher.Key;
                IV  = cipher.IV;
                createAccount(Email, FName, LName, CCNo, ExpDate, CVV, DOB);
                Response.Redirect("Login.aspx", true);
            }
        }
Example #8
0
        private byte[] GetSystemEntropy()
        {
            SHA512Managed h = new SHA512Managed();

            byte[] pb4 = new byte[4];
            byte[] pb8 = new byte[8];

            GAction <byte[], bool> f = delegate(byte[] pbValue, bool bClearValue)
            {
                if (pbValue == null)
                {
                    Debug.Assert(false); return;
                }
                if (pbValue.Length == 0)
                {
                    return;
                }
                h.TransformBlock(pbValue, 0, pbValue.Length, pbValue, 0);
                if (bClearValue)
                {
                    MemUtil.ZeroByteArray(pbValue);
                }
            };
            Action <int> fI32 = delegate(int iValue)
            {
                MemUtil.Int32ToBytesEx(iValue, pb4, 0);
                f(pb4, false);
            };
            Action <long> fI64 = delegate(long lValue)
            {
                MemUtil.Int64ToBytesEx(lValue, pb8, 0);
                f(pb8, false);
            };
            Action <string> fStr = delegate(string strValue)
            {
                if (strValue == null)
                {
                    Debug.Assert(false); return;
                }
                if (strValue.Length == 0)
                {
                    return;
                }
                f(StrUtil.Utf8.GetBytes(strValue), false);
            };

            fI32(Environment.TickCount);
            fI64(DateTime.UtcNow.ToBinary());

#if !KeePassLibSD
            // In try-catch for systems without GUI;
            // https://sourceforge.net/p/keepass/discussion/329221/thread/20335b73/
            try
            {
                Point pt = Cursor.Position;
                fI32(pt.X);
                fI32(pt.Y);
            }
            catch (Exception) { Debug.Assert(NativeLib.IsUnix()); }
#endif

            try
            {
                fI32((int)NativeLib.GetPlatformID());
#if KeePassUAP
                fStr(EnvironmentExt.OSVersion.VersionString);
#else
                fStr(Environment.OSVersion.VersionString);
#endif

                fI32(Environment.ProcessorCount);

#if !KeePassUAP
                fStr(Environment.CommandLine);
                fI64(Environment.WorkingSet);
#endif
            }
            catch (Exception) { Debug.Assert(false); }

            try
            {
                foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
                {
                    fStr(de.Key as string);
                    fStr(de.Value as string);
                }
            }
            catch (Exception) { Debug.Assert(false); }

            try
            {
#if KeePassUAP
                f(DiagnosticsExt.GetProcessEntropy(), true);
#elif !KeePassLibSD
                using (Process p = Process.GetCurrentProcess())
                {
                    fI64(p.Handle.ToInt64());
                    fI32(p.HandleCount);
                    fI32(p.Id);
                    fI64(p.NonpagedSystemMemorySize64);
                    fI64(p.PagedMemorySize64);
                    fI64(p.PagedSystemMemorySize64);
                    fI64(p.PeakPagedMemorySize64);
                    fI64(p.PeakVirtualMemorySize64);
                    fI64(p.PeakWorkingSet64);
                    fI64(p.PrivateMemorySize64);
                    fI64(p.StartTime.ToBinary());
                    fI64(p.VirtualMemorySize64);
                    fI64(p.WorkingSet64);

                    // Not supported in Mono 1.2.6:
                    // fI32(p.SessionId);
                }
#endif
            }
            catch (Exception) { Debug.Assert(NativeLib.IsUnix()); }

            try
            {
                CultureInfo ci = CultureInfo.CurrentCulture;
                if (ci != null)
                {
                    fI32(ci.GetHashCode());
                }
                else
                {
                    Debug.Assert(false);
                }
            }
            catch (Exception) { Debug.Assert(false); }

            f(Guid.NewGuid().ToByteArray(), false);
            f(GetCspRandom(), true);

            h.TransformFinalBlock(MemUtil.EmptyByteArray, 0, 0);
            byte[] pbHash = h.Hash;
            h.Clear();
            MemUtil.ZeroByteArray(pb4);
            MemUtil.ZeroByteArray(pb8);
            return(pbHash);
        }
Example #9
0
            public static string ComputeHash(string plaintext, Supported_HA hash, byte[] salt)
            {
                int minSaltLength = 4;
                int maxSaltLenght = 6;

                byte[] SaltBytes = null;

                if (salt != null)
                {
                    SaltBytes = salt;
                }
                else
                {
                    Random r          = new Random();
                    int    SaltLenght = r.Next(minSaltLength, maxSaltLenght);
                    SaltBytes = new byte[SaltLenght];
                    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                    rng.GetNonZeroBytes(SaltBytes);
                    rng.Dispose();
                }

                byte[] plaintData       = ASCIIEncoding.UTF8.GetBytes(plaintext);
                byte[] plainDataAndSalt = new byte[plaintData.Length + SaltBytes.Length];

                for (int x = 0; x < plaintData.Length; x++)
                {
                    plainDataAndSalt[x] = plaintData[x];
                }
                for (int n = 0; n < SaltBytes.Length; n++)
                {
                    plainDataAndSalt[plaintData.Length + n] = SaltBytes[n];
                }

                byte[] hashValue = null;

                switch (hash)
                {
                case Supported_HA.SHA256:
                    SHA256Managed sha = new SHA256Managed();
                    hashValue = sha.ComputeHash(plainDataAndSalt);
                    sha.Dispose();
                    break;

                case Supported_HA.SHA384:
                    SHA384Managed sha1 = new SHA384Managed();
                    hashValue = sha1.ComputeHash(plainDataAndSalt);
                    sha1.Dispose();
                    break;

                case Supported_HA.SHA512:
                    SHA512Managed sha2 = new SHA512Managed();
                    hashValue = sha2.ComputeHash(plainDataAndSalt);
                    sha2.Dispose();
                    break;
                }

                byte[] resuflt = new byte[hashValue.Length + SaltBytes.Length];
                for (int x = 0; x < hashValue.Length; x++)
                {
                    resuflt[x] = hashValue[x];
                }
                for (int n = 0; n < SaltBytes.Length; n++)
                {
                    resuflt[hashValue.Length + n] = SaltBytes[n];
                }
                return(Convert.ToBase64String(resuflt));
            }
Example #10
0
        private void button_Click(object sender, RoutedEventArgs e)
        {
            var cinfo = C9ScanNative.NativeAccessHelpers.VolumeInformation("C:\\");

            var files = Directory.GetFiles("e:\\ebooks", "*.*", SearchOption.AllDirectories);
            {
                var item = new TreeViewItem();
                item.Header = "Files Found";
                foreach (var file in files)
                {
                    item.Items.Add(new TreeViewItem()
                    {
                        Header = file.ToString()
                    });
                }
                foundMatches.Items.Add(item);
            }

            {
                foreach (var file in files)
                {
                    // Open the file so that we can look inside it...
                    using (BinaryReader reader = new BinaryReader(File.Open(file, FileMode.Open)))
                    {
                        var  information   = new System.IO.FileInfo(file);
                        var  fileLength    = information.Length;
                        var  maximumLength = (1024L * 16L);
                        long readSize      = Math.Min(fileLength, maximumLength);

                        byte[] data   = reader.ReadBytes((int)readSize);
                        var    stream = reader.BaseStream;
                        {
                            int wherem = Array.IndexOf(data, (byte)13);
                            int wheren = Array.IndexOf(data, (byte)10);
                            int where = Math.Min(wherem, wheren);
                            if (where > 0)
                            {
                                string s  = System.Text.Encoding.UTF8.GetString(data, 0, where);
                                string sa = System.Text.Encoding.ASCII.GetString(data, 0, where);
                            }
                        }

                        {
                            long chunkSize = 64;
                            if (fileLength > chunkSize)
                            {
                                stream.Seek(-chunkSize, SeekOrigin.End);
                                byte[] endData = reader.ReadBytes((int)chunkSize);
                            }
                        }
                    }

                    using (FileStream stream = File.OpenRead(file))
                    {
                        var    sha        = new SHA256Managed();
                        byte[] checksum   = sha.ComputeHash(stream);
                        var    resultHash = BitConverter.ToString(checksum).Replace("-", String.Empty);
                    }

                    using (FileStream stream = File.OpenRead(file))
                    {
                        var    sha        = new SHA1Managed();
                        byte[] checksum   = sha.ComputeHash(stream);
                        var    resultHash = BitConverter.ToString(checksum).Replace("-", String.Empty);
                    }

                    using (FileStream stream = File.OpenRead(file))
                    {
                        var    sha        = new SHA512Managed();
                        byte[] checksum   = sha.ComputeHash(stream);
                        var    resultHash = BitConverter.ToString(checksum).Replace("-", String.Empty);
                    }
                }
            }

            //var ii = new C9ScanNative.Tzpx();
            var jj = new C9ScanHelpers.GetScanResults();

            C9ScanHelpers.GetScanResults.GetSomething();
            //string result = C9ScanNative.NativeAccessHelpers.GetSomething();

            {
                var item = new TreeViewItem();
                item.Header = "Volumes";
                var names = C9ScanNative.NativeAccessHelpers.VolumeNames();
                foreach (string volumeName in names)
                {
                    // Create a node for the actual volume
                    var volumeItem = new TreeViewItem();
                    volumeItem.Header = volumeName;
                    item.Items.Add(volumeItem);

                    // Now enumerate the mount points...
                    var mounts = C9ScanNative.NativeAccessHelpers.MountNames(volumeName);
                    foreach (var mount in mounts)
                    {
                        item.Items.Add(new TreeViewItem()
                        {
                            Header = mount
                        });
                    }
                }
                foundMatches.Items.Add(item);
            }

            C9ScanNative.NativeAccessHelpers.DriveNames();

            //var jjj = new NativeAccessHelpers();
            //jjj.DoSomething();

            //var aa = new C9ScanNative.

            // var tt = new C9ScanNative.Class1();
            //tt.Foo();

            //var i = new NativeAccessHelpers();


            //C9ScanNative.NativeAccessHelpers

            //String[] vols =
        }
Example #11
0
 /// <summary>
 /// Hashes a byte array through SHA-512.
 /// </summary>
 /// <param name="input">The byte array for which to calculate the hash</param>
 /// <returns>The SHA-512 digest.</returns>
 public static byte[] SHA512(byte[] input)
 {
     using SHA512Managed sha512 = new SHA512Managed();
     return(sha512.ComputeHash(input));
 }
Example #12
0
            //
            //==========================================================================================
            /// <summary>
            /// Generates a hash for the given plain text value and returns a
            /// base64-encoded result. Before the hash is computed, a random salt
            /// is generated and appended to the plain text. This salt is stored at
            /// the end of the hash value, so it can be used later for hash
            /// verification.
            /// </summary>
            /// <param name="plainText">
            /// Plaintext value to be hashed. The function does not check whether
            /// this parameter is null.
            /// </param>
            /// <param name="hashAlgorithm">
            /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1",
            /// "SHA256", "SHA384", and "SHA512" (if any other value is specified
            /// MD5 hashing algorithm will be used). This value is case-insensitive.
            /// </param>
            /// <param name="saltBytes">
            /// Salt bytes. This parameter can be null, in which case a random salt
            /// value will be generated.
            /// </param>
            /// <returns>
            /// Hash value formatted as a base64-encoded string.
            /// </returns>
            public static string computeHash(string plainText, string hashAlgorithm, byte[] saltBytes)
            {
                byte[] workingSalt;
                if (saltBytes != null)
                {
                    //
                    // -- use provide sale
                    workingSalt = saltBytes.ToArray();
                }
                else
                {
                    //
                    // If salt is not specified, generate it on the fly.
                    int minSaltSize = 4;
                    int maxSaltSize = 8;
                    //
                    // Generate a random number for the size of the salt.
                    Random random   = new Random();
                    int    saltSize = random.Next(minSaltSize, maxSaltSize);
                    //
                    // Allocate a byte array, which will hold the salt.
                    workingSalt = new byte[saltSize];
                    //
                    // Initialize
                    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                    //
                    // Fill the salt with cryptographically strong byte values.
                    rng.GetNonZeroBytes(workingSalt);
                }
                //
                // Convert plain text into a byte array.
                byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
                //
                // Allocate array, which will hold plain text and salt.
                byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + workingSalt.Length];
                //
                // Copy plain text bytes into resulting array.
                for (int i = 0; i < plainTextBytes.Length; i++)
                {
                    plainTextWithSaltBytes[i] = plainTextBytes[i];
                }
                //
                // Append salt bytes to the resulting array.
                for (int i = 0; i < workingSalt.Length; i++)
                {
                    plainTextWithSaltBytes[plainTextBytes.Length + i] = workingSalt[i];
                }
                //
                // Because we support multiple hashing algorithms, we must define
                // hash object as a common (abstract) base class. We will specify the
                // actual hashing algorithm class later during object creation.
                HashAlgorithm hash = null;

                switch ((hashAlgorithm != null) ? hashAlgorithm.ToUpperInvariant() : "")
                {
                case "SHA1": {
                    hash = new SHA1Managed();
                    break;
                }

                case "SHA256": {
                    hash = new SHA256Managed();
                    break;
                }

                case "SHA384": {
                    hash = new SHA384Managed();
                    break;
                }

                case "SHA512": {
                    hash = new SHA512Managed();
                    break;
                }

                default: {
                    hash = new MD5CryptoServiceProvider();
                    break;
                }
                }
                //
                // Compute hash value of our plain text with appended salt.
                byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);
                //
                // Create array which will hold hash and original salt bytes.
                byte[] hashWithSaltBytes = new byte[hashBytes.Length + workingSalt.Length];
                //
                // Copy hash bytes into resulting array.
                for (int i = 0; i < hashBytes.Length; i++)
                {
                    hashWithSaltBytes[i] = hashBytes[i];
                }
                //
                // Append salt bytes to the result.
                for (int i = 0; i < workingSalt.Length; i++)
                {
                    hashWithSaltBytes[hashBytes.Length + i] = workingSalt[i];
                }
                //
                // Convert result into a base64-encoded string.
                string hashValue = Convert.ToBase64String(hashWithSaltBytes);

                //
                // Return the result.
                return(hashValue);
            }
Example #13
0
 public static void SHA512(this ReadOnlySequence <byte> data, Span <byte> hash)
 {
     using (var sha = new SHA512Managed()) {
         sha.TransformFinalBlock(data, hash);
     }
 }
Example #14
0
        protected void LoginMe(object sender, EventArgs e)
        {
            if (ValidateCaptcha())
            {
                bool validInput = ValidateInput();
                if (validInput)
                {
                    string        pwd      = tb_loginpass.Text.ToString().Trim();
                    string        userid   = tb_loginid.Text.ToString().Trim();
                    SHA512Managed hashing  = new SHA512Managed();
                    string        dbStatus = DBStatus(userid);
                    string        dbHash   = getDBHash(userid);
                    string        dbSalt   = getDBSalt(userid);
                    if (dbStatus != null && dbStatus.Length > 0)
                    {
                        if (dbStatus == "Open")
                        {
                            try
                            {
                                if (dbSalt != null && dbSalt.Length > 0 && dbHash != null && dbHash.Length > 0)
                                {
                                    string pwdWithSalt  = pwd + dbSalt;
                                    byte[] hashWithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt));
                                    string userHash     = Convert.ToBase64String(hashWithSalt);
                                    if (userHash.Equals(dbHash))
                                    {
                                        Session["LoggedIn"] = tb_loginid.Text.Trim();
                                        // creat a new GUID and save it into the session
                                        string guid = Guid.NewGuid().ToString();
                                        Session["AuthToken"] = guid;

                                        // to create a new cookie with this guid value
                                        Response.Cookies.Add(new HttpCookie("AuthToken", guid));

                                        Response.Redirect("HomePage.aspx", false);
                                    }
                                    else if (attemptcount < 3)
                                    {
                                        attemptcount++;
                                        lblMessage.ForeColor = Color.Red;
                                        lblMessage.Text      = "Password is invalid. You have " + (3 - attemptcount) + " attempts remaining" + "<br/>";
                                    }
                                    else if (attemptcount == 3)
                                    {
                                        setlockstatus(userid);
                                        lblMessage.ForeColor = Color.Red;
                                        lblMessage.Text      = "Your account is locked.";
                                    }
                                }
                                else
                                {
                                    lblMessage.ForeColor = Color.Red;
                                    lblMessage.Text     += "Email or password is not valid. Please try again." + "<br/>";
                                }
                            }
                            catch (Exception ex)
                            {
                                throw new Exception(ex.ToString());
                            }
                        }
                        else
                        {
                            lblMessage.ForeColor = Color.Red;
                            lblMessage.Text      = "Your account is locked.";
                        }
                    }
                }
            }
            else
            {
                lblMessage.ForeColor = Color.Red;
                lblMessage.Text     += "Failed to verify captcha" + "<br/>";
            }
        }
Example #15
0
        public string ComputeHash(string plaintext, string hashalgo, byte[] saltbyte)
        {
            if (saltbyte == null)
            {
                Random rand     = new Random();
                int    saltsize = rand.Next(2, 10);
                saltbyte = new byte[saltsize];
                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                rng.GetNonZeroBytes(saltbyte);
            }
            byte[] plaintextbytes     = Encoding.UTF8.GetBytes(plaintext);
            byte[] plaintextsaltbytes = new byte[plaintextbytes.Length + saltbyte.Length];
            for (int i = 0; i < plaintextbytes.Length; i++)
            {
                plaintextsaltbytes[i] = plaintextbytes[i];
            }
            for (int i = 0; i < saltbyte.Length; i++)
            {
                plaintextsaltbytes[i + plaintextbytes.Length] = saltbyte[i];
            }


            HashAlgorithm hash;

            if (hashalgo == null)
            {
                hashalgo = "";
            }

            switch (hashalgo.ToUpper())
            {
            case "SHA1":
                hash = new SHA1Managed();
                break;

            case "SHA256":
                hash = new SHA256Managed();
                break;

            case "SHA384":
                hash = new SHA384Managed();
                break;

            case "SHA512":
                hash = new SHA512Managed();
                break;

            default:
                hash = new MD5CryptoServiceProvider();
                break;
            }

            byte[] hashbytes = hash.ComputeHash(plaintextsaltbytes);

            byte[] hashWithSaltBytes = new byte[hashbytes.Length +
                                                saltbyte.Length];

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

            for (int i = 0; i < saltbyte.Length; i++)
            {
                hashWithSaltBytes[hashbytes.Length + i] = saltbyte[i];
            }

            string hashValue = Convert.ToBase64String(hashWithSaltBytes);

            return(hashValue);
        }
Example #16
0
 public SiteSecurityManager(IPrincipal principal, IDasBlogSettings dasBlogSettings)
 {
     _dasBlogSettings = dasBlogSettings;
     _principal       = principal;
     _hashAlgorithm   = SHA512Managed.Create();
 }
        protected void checkpass_Click(object sender, EventArgs e)
        {
            string pwd    = tb_password.Text.ToString().Trim();;
            int    scores = checkPassword(tb_password.Text);

            string status = "";

            switch (scores)
            {
            case 1:
                status = "Very Weak";
                break;

            case 2:
                status = "Weak";
                break;

            case 3:
                status = "Medium";
                break;

            case 4:
                status = "Strong";
                break;

            case 5:
                status = "Excellent";
                break;

            default:
                break;
            }
            tb_pwdchecker.Text = "Status : " + status;
            if (scores < 4)
            {
                tb_pwdchecker.ForeColor = Color.Red;
                return;
            }

            else
            {
                if (ValidateCaptcha())
                {
                    tb_pwdchecker.ForeColor = Color.Green;
                    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                    byte[] saltByte = new byte[8];
                    //Fills array of bytes with a cryptographically strong sequence of random values.
                    rng.GetBytes(saltByte);
                    salt = Convert.ToBase64String(saltByte);
                    SHA512Managed hashing      = new SHA512Managed();
                    string        pwdWithSalt  = pwd + salt;
                    byte[]        plainHash    = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwd));
                    byte[]        hashWithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt));
                    finalHash = Convert.ToBase64String(hashWithSalt);
                    RijndaelManaged cipher = new RijndaelManaged();
                    cipher.GenerateKey();
                    Key     = cipher.Key;
                    IV      = cipher.IV;
                    lockOut = false;

                    createAccount();
                }
            }
        }
Example #18
0
        private void try_login()
        {
            try
            {
                if (username_input.Text == "")
                {
                    throw new Exception("Sisesta kasutajanimi");
                }

                if (password_input.Text == "")
                {
                    throw new Exception("Sisesta parool");
                }

                network udpcon = new network();

                if (udpcon.connect_to_server())
                {
                    // Get sha512 password
                    string sha512_password = "";

                    if (Properties.Settings.Default.remember_me)
                    {
                        sha512_password = Properties.Settings.Default.sha512_pw;
                    }
                    else
                    {
                        UnicodeEncoding UE         = new UnicodeEncoding();
                        byte[]          message    = UE.GetBytes(password_input.Text);
                        SHA512Managed   hashString = new SHA512Managed();

                        byte[] hashValue = hashString.ComputeHash(message);
                        foreach (byte x in hashValue)
                        {
                            sha512_password += String.Format("{0:x2}", x);
                        }
                    }


                    // Let's start building the packet
                    List <string> login_packet = new List <string>();
                    string        version      = Properties.Settings.Default.version.ToString();
                    //Clipboard.SetText(sha512_password);
                    if (version.Contains(","))
                    {
                        version = version.Replace(',', '.');
                    }

                    login_packet.Add(username_input.Text.ToLower());
                    login_packet.Add(sha512_password);

                    login_packet.Add(version);
                    login_packet.Add(get_hw_id());

                    // Send login packet and recieve response
                    byte[] login_response = udpcon.send_and_recieve(0x02, login_packet);

                    if (login_response[0] == 0xFA)
                    {
                        // we have failed login attempt
                        switch (login_response[1])
                        {
                        case 0x01:
                            throw new Exception("Tundmatu veateade!");

                        case 0x02:
                            throw new Exception("Sinu kliendi versioon on liiga vana!");

                        case 0x03:
                            throw new Exception("Vale kasutajanimi või parool!");

                        case 0x04:
                            throw new Exception("Kasutaja on juba sisse loginud. Juhul kui Sinu ühendus aegus, oota 2min!");

                        case 0x05:
                            List <string> ban_info = udpcon.extract_data(login_response);
                            throw new Exception("Sa oled banned.\nPõhjus: " + ban_info[0] + "\nKestab kuni: " + ban_info[1]);

                        case 0x06:
                            throw new Exception("Serveriga ühenduse loomine ebaõnnestus!");
                        }
                    }

                    if (login_response[0] == 0xFF)
                    {
                        // Login was successful
                        List <string> recieved_data = udpcon.extract_data(login_response);
                        steamid = recieved_data[0];
                        string password = recieved_data[1];
                        s_hash = long.Parse(recieved_data[2]);

                        if (password != sha512_password)
                        {
                            List <string> abuse_data = new List <string>();
                            abuse_data.Add("Passwords do not match at user-side after getting 'ok'");
                            //main_client.send_data(0x16, abuseData);
                        }
                        else
                        {
                            if (remember_me.Checked)
                            {
                                string keyName = @"HKEY_CURRENT_USER\SOFTWARE\everest\Gather";
                                Registry.SetValue(keyName, "username", username_input.Text);
                                Registry.SetValue(keyName, "password", sha512_password);
                                Registry.SetValue(keyName, "remember_me", true);
                            }
                            else
                            {
                                string keyName = @"HKEY_CURRENT_USER\SOFTWARE\everest\Gather";
                                Registry.SetValue(keyName, "username", "");
                                Registry.SetValue(keyName, "password", "");
                                Registry.SetValue(keyName, "remember_me", false);
                            }

                            // initialize new window and give refrence to connection and this form
                            main_hub_scr main_window = new main_hub_scr(this, udpcon);
                            main_window.Show();
                            this.Hide();
                            //throw new Exception("LOGIN OK");
                        }
                    }

                    //c_msgbox.show_msg(false, "See funktsioon ei ole valmis veel!\nSinu hw_id: " + get_hw_id());
                }
                else
                {
                    c_msgbox.show_msg(true, "Serveriga ühenduse loomine ebaõnnestus!");
                }
            }
            catch (Exception ex)
            {
                c_msgbox.show_msg(true, ex.Message);
            }
        }
        internal bool InvokeNetGetData(ref byte msgId, MessageBuffer buffer, ref int index, ref int length)
        {
            if (Main.netMode == 2)
            {
                // A critical server crash/slow-down bug was exploited in which a 0-length
                // packet is sent, causing all NetGetData handlers to throw exceptions.
                // Because a packet's header is 2 bytes of length + 1 byte of packet type,
                // all packets must contain at least 3 bytes.
                // Ideally this check should occur in an OTAPI modification.
                if (length < 1)
                {
                    RemoteClient currentClient = Netplay.Clients[buffer.whoAmI];
                    Netplay.Clients[buffer.whoAmI].PendingTermination = true;
                    return(true);
                }

                // A critical server crash/corruption bug was reported by @bartico6 on GitHub.
                // If a packet length comes in at extreme values, the server can enter infinite loops, deadlock, and corrupt the world.
                // As a result, we take the following action: disconnect the player and log the attempt as soon as we can.
                // The length 1000 was chosen as an arbitrarily large number for all packets. It may need to be tuned later.
                if (length > 1000)
                {
                    RemoteClient currentClient = Netplay.Clients[buffer.whoAmI];
                    Netplay.Clients[buffer.whoAmI].PendingTermination = true;
                    return(true);
                }

                switch ((PacketTypes)msgId)
                {
                case PacketTypes.ConnectRequest:
                    if (this.InvokeServerConnect(buffer.whoAmI))
                    {
                        Netplay.Clients[buffer.whoAmI].PendingTermination = true;
                        return(true);
                    }

                    break;

                case PacketTypes.ContinueConnecting2:
                    if (this.InvokeServerJoin(buffer.whoAmI))
                    {
                        Netplay.Clients[buffer.whoAmI].PendingTermination = true;
                        return(true);
                    }

                    break;

                case PacketTypes.LoadNetModule:
                    using (var stream = new MemoryStream(buffer.readBuffer))
                    {
                        stream.Position = index;
                        using (var reader = new BinaryReader(stream))
                        {
                            ushort moduleId = reader.ReadUInt16();
                            //LoadNetModule is now used for sending chat text.
                            //Read the module ID to determine if this is in fact the text module
                            if (moduleId == Terraria.Net.NetManager.Instance.GetId <Terraria.GameContent.NetModules.NetTextModule>())
                            {
                                //Then deserialize the message from the reader
                                Terraria.Chat.ChatMessage msg = Terraria.Chat.ChatMessage.Deserialize(reader);

                                if (InvokeServerChat(buffer, buffer.whoAmI, @msg.Text, msg.CommandId))
                                {
                                    return(true);
                                }
                            }
                        }
                    }

                    break;

                //Making sure packet length is 38, otherwise it's not a valid UUID packet length.
                //We copy the bytes of the UUID then convert it to string. Then validating the GUID so its the correct format.
                //Then the bytes get hashed, and set as ClientUUID (and gets written in DB for auto-login)
                //length minus 2 = 36, the length of a UUID.
                case PacketTypes.ClientUUID:
                    if (length == 38)
                    {
                        byte[] uuid = new byte[length - 2];
                        Buffer.BlockCopy(buffer.readBuffer, index + 1, uuid, 0, length - 2);
                        Guid guid = new Guid();
                        if (Guid.TryParse(Encoding.Default.GetString(uuid, 0, uuid.Length), out guid))
                        {
                            SHA512 shaM   = new SHA512Managed();
                            var    result = shaM.ComputeHash(uuid);
                            Netplay.Clients[buffer.whoAmI].ClientUUID = result.Aggregate("", (s, b) => s + b.ToString("X2"));
                            return(true);
                        }
                    }
                    Netplay.Clients[buffer.whoAmI].ClientUUID = "";
                    return(true);
                }
            }

            GetDataEventArgs args = new GetDataEventArgs
            {
                MsgID  = (PacketTypes)msgId,
                Msg    = buffer,
                Index  = index,
                Length = length
            };

            this.NetGetData.Invoke(args);

            msgId  = (byte)args.MsgID;
            index  = args.Index;
            length = args.Length;
            return(args.Handled);
        }
        public static string Get_salt()
        {
            var size_in_bytes = SHA512Managed.Create().HashSize / 8;

            return(RandomString(size_in_bytes));
        }
Example #21
0
        public String Hash(String input)
        {
            SHA512Managed sha512 = new SHA512Managed();

            return(sha512.ComputeHash(this.TextEncoding.GetBytes(input)).ToHexString());
        }
Example #22
0
        protected void changBtn_Click(object sender, EventArgs e)
        {
            var score = checkPassword(newPass.Text);

            if (score < 4)
            {
                errorMsg.Text      = "Password not strong enough";
                errorMsg.ForeColor = Color.Red;
                return;
            }

            var           email   = Session["LoggedIn"];
            SHA512Managed hashing = new SHA512Managed();
            string        gethash = "SELECT PasswordHash FROM ASusers WHERE Email = @Email";
            string        getsalt = "SELECT PasswordSalt FROM ASusers WHERE Email = @Email";

            using (SqlConnection connection = new SqlConnection(MYDBConnectionString))
            {
                connection.Open();
                SqlCommand hashcommand = new SqlCommand(gethash, connection);
                SqlCommand saltcommand = new SqlCommand(getsalt, connection);
                hashcommand.Parameters.AddWithValue("@Email", email);
                saltcommand.Parameters.AddWithValue("@Email", email);
                string hash         = hashcommand.ExecuteScalar().ToString();
                string salt         = saltcommand.ExecuteScalar().ToString();
                var    pwdWithSalt  = oldPass.Text + salt;
                byte[] hashWithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt));
                var    finalHash    = Convert.ToBase64String(hashWithSalt);
                if (hash == finalHash)
                {
                    string     checkpass1        = "SELECT Password1 FROM [PasswordHistory] WHERE Email = @Email";
                    string     checkpass2        = "SELECT Password2 FROM [PasswordHistory] WHERE Email = @Email";
                    SqlCommand checkpass1command = new SqlCommand(checkpass1, connection);
                    SqlCommand checkpass2command = new SqlCommand(checkpass2, connection);
                    checkpass1command.Parameters.AddWithValue("@Email", email);
                    checkpass2command.Parameters.AddWithValue("@Email", email);
                    string pass1           = checkpass1command.ExecuteScalar().ToString();
                    string pass2           = checkpass2command.ExecuteScalar().ToString();
                    var    newpwdWithSalt  = newPass.Text + salt;
                    byte[] newhashWithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(newpwdWithSalt));
                    var    newfinalHash    = Convert.ToBase64String(newhashWithSalt);
                    if (newfinalHash == pass1)
                    {
                        errorMsg.Text      = "Please use another password";
                        errorMsg.ForeColor = Color.Red;
                        return;
                    }
                    if (newfinalHash == pass2)
                    {
                        errorMsg.Text      = "Please use another password";
                        errorMsg.ForeColor = Color.Red;
                        return;
                    }
                    string     updatePassword = "******";
                    SqlCommand updateCommand  = new SqlCommand(updatePassword, connection);
                    updateCommand.Parameters.AddWithValue("@PasswordHash", newfinalHash);
                    updateCommand.Parameters.AddWithValue("@Email", email);
                    updateCommand.ExecuteNonQuery();

                    using (SqlCommand cmd = new SqlCommand("UPDATE [PasswordHistory] SET Password1 = @PasswordHash1, Password2 = @PasswordHash2 ,TimeCreated = @TimeCreated WHERE Email = @Email", connection))
                    {
                        using (SqlDataAdapter sda = new SqlDataAdapter())
                        {
                            cmd.CommandType = CommandType.Text;
                            cmd.Parameters.AddWithValue("@PasswordHash1", newfinalHash);
                            cmd.Parameters.AddWithValue("@PasswordHash2", finalHash);
                            cmd.Parameters.AddWithValue("@Email", email);
                            cmd.Parameters.AddWithValue("@TimeCreated", DateTime.Now.ToString());

                            cmd.ExecuteNonQuery();
                            connection.Close();
                        }
                    }
                }
                else
                {
                    errorMsg.Text = "Password is incorrect";
                }
                connection.Close();
                Session["PasswordAge"] = DateTime.Now.AddMinutes(5).ToString();
                Response.Redirect("Home.aspx");
            }
        }
    public override void GenerateKey(string secretKey, AlgorithmKeyType type)
    {
        Key = new byte[8];
        IV  = new byte[8];
        byte[] bKey = Encoding.UTF8.GetBytes(secretKey);
        switch (type)
        {
        case AlgorithmKeyType.MD5:    //16 byte
            using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
            {
                md5.ComputeHash(bKey);
                byte[] rmd5 = md5.Hash;
                for (int i = 0; i < 8; i++)
                {
                    Key[i] = rmd5[i];
                }
                for (int j = 15; j >= 8; j--)
                {
                    IV[15 - j] = rmd5[j];
                }
            }
            break;

        case AlgorithmKeyType.SHA1:    //20 byte
            using (SHA1Managed sha1 = new SHA1Managed())
            {
                sha1.ComputeHash(bKey);
                byte[] rsha1 = sha1.Hash;
                for (int i = 0; i < 8; i++)
                {
                    Key[i] = rsha1[i];
                }
                for (int j = 19; j > 11; j--)
                {
                    IV[19 - j] = rsha1[j];
                }
            }
            break;

        case AlgorithmKeyType.SHA256:    //32 byte
            using (SHA256Managed sha256 = new SHA256Managed())
            {
                sha256.ComputeHash(bKey);
                byte[] rsha256 = sha256.Hash;
                for (int i = 0; i < 8; i++)
                {
                    Key[i] = rsha256[i];
                }
                for (int j = 31; j >= 24; j--)
                {
                    IV[31 - j] = rsha256[j];
                }
            }
            break;

        case AlgorithmKeyType.SHA384:    //48 byte
            using (SHA384Managed sha384 = new SHA384Managed())
            {
                sha384.ComputeHash(bKey);
                byte[] rsha384 = sha384.Hash;
                for (int i = 0; i < 8; i++)
                {
                    Key[i] = rsha384[i];
                }
                for (int j = 47; j > 39; j--)
                {
                    IV[47 - j] = rsha384[j];
                }
            }
            break;

        case AlgorithmKeyType.SHA512:    //64 byte
            using (SHA512Managed sha512 = new SHA512Managed())
            {
                sha512.ComputeHash(bKey);
                byte[] rsha512 = sha512.Hash;
                for (int i = 0; i < 8; i++)
                {
                    Key[i] = rsha512[i];
                }
                for (int j = 63; j > 55; j--)
                {
                    IV[63 - j] = rsha512[j];
                }
            }
            break;

        default:
            break;
        }
    }
Example #24
0
        protected (Boolean, string, string, string) getPasswordReuse(string email)
        {
            SHA512Managed hashing = new SHA512Managed();
            string        dbSalt  = getDBSalt(email);
            Boolean       s       = false;

            if (dbSalt != null && dbSalt.Length > 0)
            {
                SqlConnection connection = new SqlConnection(AppSecDBConnectionString);
                string        sql        = "select passwordList FROM Account WHERE email=@EMAIL";
                SqlCommand    command    = new SqlCommand(sql, connection);
                command.Parameters.AddWithValue("@EMAIL", email);
                try
                {
                    connection.Open();
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            if (reader["passwordList"] != null)
                            {
                                if (reader["passwordList"] != DBNull.Value)
                                {
                                    string   plist      = reader["passwordList"].ToString();
                                    string[] plistsplit = plist.Split(new[] { "|||" }, StringSplitOptions.None);

                                    string passwordWithSalt = tb_changePW.Text + dbSalt;
                                    byte[] hashWithSalt     = hashing.ComputeHash(Encoding.UTF8.GetBytes(passwordWithSalt));
                                    string userHash         = Convert.ToBase64String(hashWithSalt);

                                    for (int i = 0; i < plistsplit.Length; i++)
                                    {
                                        if (userHash.Equals(plistsplit[i]))
                                        {
                                            s = true;
                                        }
                                    }
                                    if (!(s))
                                    {
                                        if (plistsplit.Length < 3)
                                        {
                                            var newplist = plistsplit[0] + "|||" + userHash + "|||";
                                            return(s, email, newplist.Trim(), userHash);
                                        }
                                        else
                                        {
                                            var newplist = plistsplit[1] + "|||" + userHash + "|||";
                                            return(s, email, newplist.Trim(), userHash);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.ToString());
                }
                finally { connection.Close(); }
                return(s, "", "", "");
            }
            return(s, "", "", "");
        }
Example #25
0
        public static string ComputeHash(string plainText, string hashAlgorithm, byte[] saltBytes)
        {
            // If salt is not specified, generate it.
            if (saltBytes == null)
            {
                // Define min and max salt sizes.
                int minSaltSize = 4;
                int maxSaltSize = 8;

                // Generate a random number for the size of the salt.
                Random random   = new Random();
                int    saltSize = random.Next(minSaltSize, maxSaltSize);

                // Allocate a byte array, which will hold the salt.
                saltBytes = new byte[saltSize];

                // Initialize a random number generator.
                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

                // Fill the salt with cryptographically strong byte values.
                rng.GetNonZeroBytes(saltBytes);
            }

            // Convert plain text into a byte array.
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            // Allocate array, which will hold plain text and salt.
            byte[] plainTextWithSaltBytes =
                new byte[plainTextBytes.Length + saltBytes.Length];

            // Copy plain text bytes into resulting array.
            for (int i = 0; i < plainTextBytes.Length; i++)
            {
                plainTextWithSaltBytes[i] = plainTextBytes[i];
            }

            // Append salt bytes to the resulting array.
            for (int i = 0; i < saltBytes.Length; i++)
            {
                plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];
            }

            HashAlgorithm hash;

            // Make sure hashing algorithm name is specified.
            if (hashAlgorithm == null)
            {
                hashAlgorithm = "";
            }

            // Initialize appropriate hashing algorithm class.
            switch (hashAlgorithm.ToUpper())
            {
            case "SHA384":
                hash = new SHA384Managed();
                break;

            case "SHA512":
                hash = new SHA512Managed();
                break;

            default:
                hash = new MD5CryptoServiceProvider();
                break;
            }

            // Compute hash value of our plain text with appended salt.
            byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);

            // Create array which will hold hash and original salt bytes.
            byte[] hashWithSaltBytes = new byte[hashBytes.Length +
                                                saltBytes.Length];

            // Copy hash bytes into resulting array.
            for (int i = 0; i < hashBytes.Length; i++)
            {
                hashWithSaltBytes[i] = hashBytes[i];
            }

            // Append salt bytes to the result.
            for (int i = 0; i < saltBytes.Length; i++)
            {
                hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];
            }

            // Convert result into a base64-encoded string.
            string hashValue = Convert.ToBase64String(hashWithSaltBytes);

            // Return the result.
            return(hashValue);
        }
        /// <summary>
        /// Calculates the hash of a data using SHA hash algorithm.
        /// </summary>
        /// <param name="data">The data to hash.</param>
        /// <param name="offset">The offset.</param>
        /// <param name="length">The length.</param>
        /// <param name="hashSize">Size of the hash.</param>
        /// <returns>
        /// Calculated hash
        /// </returns>
        private static byte[] CalculateHashSha(this byte[] data, int offset, int length, int hashSize)
        {
            data.CannotBeNullOrEmpty();
            offset.MustBeGreaterThanOrEqualTo(0);
            length.MustBeGreaterThanOrEqualTo(0);
            hashSize.MustBeOneOf(128, 256, 384, 512);

            byte[] hashRaw = null;

            if (data != null)
            {
                if (hashSize == 128)
                {
#pragma warning disable CA5350 // Do not use insecure cryptographic algorithm SHA1.
                    using (HashAlgorithm sha = new SHA1CryptoServiceProvider())
#pragma warning restore CA5350 // Do not use insecure cryptographic algorithm SHA1.
                    {
                        hashRaw = CalculateHash(data, offset, length, sha);
                    }
                }
                else if (hashSize == 256)
                {
                    try
                    {
                        using (HashAlgorithm sha = new SHA256CryptoServiceProvider())
                        {
                            hashRaw = CalculateHash(data, offset, length, sha);
                        }
                    }
                    catch (PlatformNotSupportedException)
                    {
                        // Fall back to the managed version if the CSP
                        // is not supported on this platform.
                        using (HashAlgorithm sha = new SHA256Managed())
                        {
                            hashRaw = CalculateHash(data, offset, length, sha);
                        }
                    }
                }
                else if (hashSize == 384)
                {
                    try
                    {
                        using (HashAlgorithm sha = new SHA384CryptoServiceProvider())
                        {
                            hashRaw = CalculateHash(data, offset, length, sha);
                        }
                    }
                    catch (PlatformNotSupportedException)
                    {
                        // Fall back to the managed version if the CSP
                        // is not supported on this platform.
                        using (HashAlgorithm sha = new SHA384Managed())
                        {
                            hashRaw = CalculateHash(data, offset, length, sha);
                        }
                    }
                }
                else if (hashSize == 512)
                {
                    try
                    {
                        using (HashAlgorithm sha = new SHA512CryptoServiceProvider())
                        {
                            hashRaw = CalculateHash(data, offset, length, sha);
                        }
                    }
                    catch (PlatformNotSupportedException)
                    {
                        // Fall back to the managed version if the CSP
                        // is not supported on this platform.
                        using (HashAlgorithm sha = new SHA512Managed())
                        {
                            hashRaw = CalculateHash(data, offset, length, sha);
                        }
                    }
                }
            }

            return hashRaw;
        }
Example #27
0
        public static string ComputeHash(string plainText,
                                         Algorith hashAlgorithm,
                                         byte[] saltBytes)
        {
            // If salt is not specified, generate it on the fly.
            if (saltBytes == null)
            {
                // Define min and max salt sizes.
                int minSaltSize = 4;
                int maxSaltSize = 8;

                // Generate a random number for the size of the salt.
                Random random   = new Random();
                int    saltSize = random.Next(minSaltSize, maxSaltSize);

                // Allocate a byte array, which will hold the salt.
                saltBytes = new byte[saltSize];

                // Initialize a random number generator.
                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

                // Fill the salt with cryptographically strong byte values.
                rng.GetNonZeroBytes(saltBytes);
            }

            // Convert plain text into a byte array.
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            // Allocate array, which will hold plain text and salt.
            byte[] plainTextWithSaltBytes =
                new byte[plainTextBytes.Length + saltBytes.Length];

            // Copy plain text bytes into resulting array.
            for (int i = 0; i < plainTextBytes.Length; i++)
            {
                plainTextWithSaltBytes[i] = plainTextBytes[i];
            }

            // Append salt bytes to the resulting array.
            for (int i = 0; i < saltBytes.Length; i++)
            {
                plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];
            }

            // Because we support multiple hashing algorithms, we must define
            // hash object as a common (abstract) base class. We will specify the
            // actual hashing algorithm class later during object creation.
            HashAlgorithm hash;

            // Initialize appropriate hashing algorithm class.
            switch (hashAlgorithm)
            {
            case Algorith.SHA1:
                hash = new SHA1Managed();
                break;

            case Algorith.SHA256:
                hash = new SHA256Managed();
                break;

            case Algorith.SHA384:
                hash = new SHA384Managed();
                break;

            case Algorith.SHA512:
                hash = new SHA512Managed();
                break;

            case Algorith.MD5:
                hash = new MD5CryptoServiceProvider();
                break;

            default:
                hash = new MD5CryptoServiceProvider();
                break;
            }

            // Compute hash value of our plain text with appended salt.
            byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);

            // Create array which will hold hash and original salt bytes.
            byte[] hashWithSaltBytes = new byte[hashBytes.Length +
                                                saltBytes.Length];

            // Copy hash bytes into resulting array.
            for (int i = 0; i < hashBytes.Length; i++)
            {
                hashWithSaltBytes[i] = hashBytes[i];
            }

            // Append salt bytes to the result.
            for (int i = 0; i < saltBytes.Length; i++)
            {
                hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];
            }

            // Convert result into a base64-encoded string.
            string hashValue = Convert.ToBase64String(hashWithSaltBytes);

            // Return the result.
            return(hashValue);
        }
        protected void submitBtn_Click(object sender, EventArgs e)
        {
            int scores = checkPassword(HttpUtility.HtmlEncode(firstPasswordTB.Text.Trim()));

            switch (scores)
            {
            case 1:
                firstPasswordError.Text      = "Very Weak";
                firstPasswordError.ForeColor = Color.Red;
                break;

            case 2:
                firstPasswordError.Text      = "Weak";
                firstPasswordError.ForeColor = Color.Red;
                break;

            case 3:
                firstPasswordError.Text      = "Medium";
                firstPasswordError.ForeColor = Color.Red;
                break;

            case 4:
                firstPasswordError.Text      = "Strong";
                firstPasswordError.ForeColor = Color.Red;
                break;

            case 5:
                firstPasswordError.Text      = "Excellent";
                firstPasswordError.ForeColor = Color.Green;
                break;

            default:
                break;
            }

            bool validInput = ValidateInput();

            bool validCaptcha = ValidateCaptcha();

            if (validInput == true && validCaptcha == true && scores == 5)
            {
                bool presentEmail = getEmail(emailTB.Text);

                //Checks if email is present or not
                if (presentEmail == true)
                {
                    errorMsg.Text        = "Please choose another email for registration";
                    errorMsg.ForeColor   = Color.Red;
                    emailError.Text      = "Please choose another email for registration";
                    emailError.ForeColor = Color.Red;
                    //Response.Redirect("Registration.aspx",false);
                }
                else
                {
                    //submitBtn.Enabled = true;
                    //secondPasswordTB.Text = validCaptcha.ToString();
                    //Retrieve password input
                    string password = HttpUtility.HtmlEncode(firstPasswordTB.Text.ToString().Trim());

                    //Generate random salt
                    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                    byte[] saltByte = new byte[8];

                    //Fills array of bytes with a cryptographically strong sequence of random values.
                    rng.GetBytes(saltByte);
                    salt = Convert.ToBase64String(saltByte);

                    SHA512Managed hashing     = new SHA512Managed();
                    string        pwdWithSalt = password + salt;

                    byte[] plainHash    = hashing.ComputeHash(Encoding.UTF8.GetBytes(password));
                    byte[] hashWithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(pwdWithSalt));

                    finalHash = Convert.ToBase64String(hashWithSalt);

                    RijndaelManaged cipher = new RijndaelManaged();
                    cipher.GenerateKey();
                    Key = cipher.Key;
                    IV  = cipher.IV;
                    CreateAccount();
                    //Redirect to Login page
                    Response.Redirect("Login.aspx", false);
                }
            }
            else
            {
                ValidateInput();
                //submitBtn.Enabled = false;
                //Response.Redirect("Registration.aspx", false);
            }
        }
Example #29
0
        protected void btn_ChangePassword_Click(object sender, EventArgs e)
        {
            string email = Session["SSEmail"].ToString();

            int scores = checkPassword(tb_new_password.Text);

            string status = "";

            switch (scores)
            {
            case 1:
                status = "Very Weak";
                break;

            case 2:
                status = "Weak";
                break;

            case 3:
                status = "Medium";
                break;

            case 4:
                status = "Strong";
                break;

            case 5:
                status = "Excellent";
                break;

            default:
                break;
            }
            lbl_pwdChecker.Text = "Status : " + status;
            if (scores < 4)
            {
                lbl_pwdChecker.ForeColor = Color.Red;
                return;
            }
            else
            {
                lbl_pwdChecker.ForeColor = Color.Green;
            }

            string currentPwd = tb_old_password.Text.ToString().Trim();

            string newPwd = tb_new_password.Text.ToString().Trim();

            //Generate random "salt"
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

            byte[] saltByte = new byte[8];

            //Fills array of bytes with a cryptographically strong sequence of random values.
            //rng.GetBytes(saltByte);
            //salt = Convert.ToBase64String(saltByte);

            SHA512Managed hashing = new SHA512Managed();

            //string dbHash = getDBHash(email);

            string dbSalt = getDBSalt(email);

            string currentPwdWithSalt = currentPwd + dbSalt;
            string newPwdWithSalt     = newPwd + dbSalt;

            string oldPwdHash = getOldDBHash(email);

            byte[] newHashWithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(newPwdWithSalt));
            NewHash = Convert.ToBase64String(newHashWithSalt);

            byte[] currentHashWithSalt = hashing.ComputeHash(Encoding.UTF8.GetBytes(currentPwdWithSalt));

            if (newPwdWithSalt == currentPwdWithSalt)
            {
                passChangeErrMsg.Text      = "Cannot use the same password.";
                passChangeErrMsg.ForeColor = System.Drawing.Color.Red;
            }
            else if (NewHash.Equals(oldPwdHash))
            {
                passChangeErrMsg.Text      = "Cannot use the same password as the first time or password is incorrect.";
                passChangeErrMsg.ForeColor = System.Drawing.Color.Red;
            }
            else
            {
                finalHash = Convert.ToBase64String(newHashWithSalt);
                Response.Redirect("SuccessPasswordChange.aspx", false);
                UpdateAccount(email, finalHash, dbSalt);
            }

            //finalHash = Convert.ToBase64String(newHashWithSalt);

            RijndaelManaged cipher = new RijndaelManaged();

            cipher.GenerateKey();
            Key = cipher.Key;
            IV  = cipher.IV;
        }
Example #30
0
        public override MazeErrorCode onReceiveData(byte[] Data, ref byte[] ResponseData)
        {
            ResponseData = new byte[0];

            if (LastErrorCode != MazeErrorCode.Success)
            {
                //don't continue if the client/server messed something up
                return(LastErrorCode);
            }

            switch (base.Step)
            {
            case 1:
            {
                //step 2
                if (Data.Length != Mazing.ByteCode.Length)
                {
                    SysLogger.Log("[MazeHandShake][Server] ByteCode Length Missmatch", SysLogType.Debug);
                    return(MazeErrorCode.WrongByteCode);
                }

                for (int i = 0; i < Mazing.ByteCode.Length; i++)
                {
                    if (Mazing.ByteCode[i] != Data[i])
                    {
                        SysLogger.Log("[MazeHandShake][Server] WrongByteCode from client", SysLogType.Debug);
                        return(MazeErrorCode.WrongByteCode);
                    }
                }
                Step++;
                break;
            }

            case 2:
            {
                if (onFindKeyInDatabase == null)     //programmer error
                {
                    SysLogger.Log("[MazeHandShake][Server] onFindKeyInDatabase is null", SysLogType.Debug);
                    ResponseData = GetFailResponseData();     //not encrypted, client knows this will fail
                    return(MazeErrorCode.Error);
                }

                string EncHashedMsg = BitConverter.ToString(SHA512Managed.Create().ComputeHash(Data, 0, Data.Length)).Replace("-", "");
                byte[] _key         = new byte[0];
                byte[] _salt        = new byte[0];
                byte[] _publicKey   = new byte[0];
                string _userName    = "";

                if (onFindKeyInDatabase(EncHashedMsg, ref _key, ref _salt, ref _publicKey, ref _userName))
                {
                    this.PublicKeyData = TrimArray(_publicKey, Mazing.MAX_KEY_SIZE);
                    this.wopEx         = base.GetWopEncryption(_key, _salt);

                    base.FinalKey  = _key;
                    base.FinalSalt = _salt;

                    //let's try to decrypt the data, should go successful
                    wopEx.Decrypt(Data, 0, Data.Length);

                    if (Data.Length != _publicKey.Length)
                    {
                        SysLogger.Log("[MazeHandShake][Server] Public key length missmatch", SysLogType.Debug);
                        //key size not the same... strange
                        ResponseData = GetFailResponseData();
                        return(MazeErrorCode.Error);
                    }

                    for (int i = 0; i < _publicKey.Length; i++)
                    {
                        if (Data[i] != _publicKey[i])
                        {
                            SysLogger.Log("[MazeHandShake][Server] Public key missmatch", SysLogType.Debug);
                            //public key did not match... strange
                            ResponseData = GetFailResponseData();
                            return(MazeErrorCode.Error);
                        }
                    }

                    //encryption / public key went successful for now
                    this.server_Prime = BigInteger.genPseudoPrime(256, 50, new Random(BitConverter.ToInt32(_key, 0)));
                    byte[] primeData = server_Prime.getBytes();
                    wopEx.Encrypt(primeData, 0, primeData.Length);
                    ResponseData = primeData;

                    this.Username = _userName;

                    Step++;
                }
                else
                {
                    SysLogger.Log("[MazeHandShake][Server] No user key found in database", SysLogType.Debug);
                    ResponseData = GetFailResponseData();
                    return(MazeErrorCode.UserKeyNotFound);
                }
                break;
            }

            case 3:
            {
                //response back from client with his prime number
                wopEx.Decrypt(Data, 0, Data.Length);

                this.client_Prime = new BigInteger(Data);
                if (this.client_Prime.isProbablePrime())
                {
                    //verify the prime from the client
                    BigInteger client_Prime_test = BigInteger.genPseudoPrime(256, 50, new Random(this.server_Prime.IntValue()));

                    if (this.client_Prime != client_Prime_test)
                    {
                        //Attacker detected ?
                        SysLogger.Log("[MazeHandShake][Server] Man-In-The-Middle detected", SysLogType.Debug);
                        return(MazeErrorCode.Error);
                    }

                    BigInteger key = base.ModKey(server_Prime, client_Prime);
                    //apply key to encryption
                    ApplyKey(wopEx, key);
                    return(MazeErrorCode.Finished);
                }
                else
                {
                    SysLogger.Log("[MazeHandShake][Server] Invalid response", SysLogType.Debug);
                    return(MazeErrorCode.Error);
                }
            }
            }
            return(MazeErrorCode.Success);
        }
Example #31
0
    public string validar_login_inyeccion_Sp(String documento, String clave)
    {
        string estado = "Activo";

        //se define la cadena de conexion con la red
        SqlConnection conex = new SqlConnection(ConfigurationManager.ConnectionStrings["invenire_cuero_ConnectionString"].ConnectionString);
        //se mapea(lee) el procedimieto alamcenado
        SqlCommand testCMD = new SqlCommand("validar_login", conex);

        //
        testCMD.CommandType = CommandType.StoredProcedure;

        //envio del parametro usuario al sp
        SqlParameter IdIn = testCMD.Parameters.Add("@documento", SqlDbType.VarChar, 20);

        IdIn.Direction = ParameterDirection.Input;
        IdIn.Value     = documento;

        //envio del parametro clave al sp

        //se consulta la clave encriptada
        // var consulta = "select contrasena  from tbl_usuario where contrasena = '" + clave + "'";
        // var cmd = new SqlCommand(consulta, conex);
        // conex.Open();
        // SqlDataReader leerbd = cmd.ExecuteReader();

        //if (leerbd.Read() == true)
        // {
        //     //captura la clave encriptada del usuario
        //     clave_encriptada = leerbd.GetString(0);
        // }
        //conex.Close();
        ////se desencripta la clave
        //string result = string.Empty;
        // byte[] decryted = System.Text.Encoding.Unicode.GetBytes(clave_encriptada);
        // result = Convert.ToBase64String(decryted);

        //string result = string.Empty;
        //byte[] encryted = System.Text.Encoding.Unicode.GetBytes(clave);
        //result = Convert.ToBase64String(encryted);

        SHA512        sha512   = SHA512Managed.Create();
        ASCIIEncoding encoding = new ASCIIEncoding();

        byte[]        stream = null;
        StringBuilder sb     = new StringBuilder();

        stream = sha512.ComputeHash(encoding.GetBytes(clave));
        for (int i = 0; i < stream.Length; i++)
        {
            sb.AppendFormat("{0:x2}", stream[i]);
        }

        string result = sb.ToString();


        SqlParameter IdIn1 = testCMD.Parameters.Add("@clave", SqlDbType.VarChar, 600);

        IdIn1.Direction = ParameterDirection.Input;
        IdIn1.Value     = result;



        //envio del parametro estado al sp
        SqlParameter IdIn2 = testCMD.Parameters.Add("@estado", SqlDbType.VarChar, 20);

        IdIn2.Direction = ParameterDirection.Input;
        IdIn2.Value     = estado;

        //se abre la conexion
        conex.Open();

        //se ejecuta el sp
        SqlDataReader myReader = testCMD.ExecuteReader();

        if (myReader.Read() == true)
        {
            mensaje = "Exito";
        }
        else
        {
            mensaje = "Error";
        }

        //se cierra la conexion
        conex.Close();

        return(mensaje);
    }//FIN METODO VALIDAR ACCESO
Example #32
0
	byte[] IHashAlgorithm.GetRunningHash ()
	{
		var copy = new SHA512Managed (this);
		copy.TransformFinalBlock (empty, 0, 0);
		return copy.Hash;
	}
Example #33
0
        /// <summary>
        /// Create a cryptographic key of length <paramref name="cbOut" />
        /// (in bytes) from <paramref name="pbIn" />.
        /// </summary>
        public static byte[] ResizeKey(byte[] pbIn, int iInOffset,
                                       int cbIn, int cbOut)
        {
            if (pbIn == null)
            {
                throw new ArgumentNullException("pbIn");
            }
            if (cbOut < 0)
            {
                throw new ArgumentOutOfRangeException("cbOut");
            }

            if (cbOut == 0)
            {
                return(MemUtil.EmptyByteArray);
            }

            byte[] pbHash;
            if (cbOut <= 32)
            {
                pbHash = HashSha256(pbIn, iInOffset, cbIn);
            }
            else
            {
                using (SHA512Managed h = new SHA512Managed())
                {
                    pbHash = h.ComputeHash(pbIn, iInOffset, cbIn);
                }
            }

            if (cbOut == pbHash.Length)
            {
                return(pbHash);
            }

            byte[] pbRet = new byte[cbOut];
            if (cbOut < pbHash.Length)
            {
                Array.Copy(pbHash, pbRet, cbOut);
            }
            else
            {
                int   iPos = 0;
                ulong r    = 0;
                while (iPos < cbOut)
                {
                    Debug.Assert(pbHash.Length == 64);
                    using (HMACSHA256 h = new HMACSHA256(pbHash))
                    {
                        byte[] pbR    = MemUtil.UInt64ToBytes(r);
                        byte[] pbPart = h.ComputeHash(pbR);

                        int cbCopy = Math.Min(cbOut - iPos, pbPart.Length);
                        Debug.Assert(cbCopy > 0);

                        Array.Copy(pbPart, 0, pbRet, iPos, cbCopy);
                        iPos += cbCopy;
                        ++r;

                        MemUtil.ZeroByteArray(pbPart);
                    }
                }
                Debug.Assert(iPos == cbOut);
            }

#if DEBUG
            byte[] pbZero = new byte[pbHash.Length];
            Debug.Assert(!MemUtil.ArraysEqual(pbHash, pbZero));
#endif
            MemUtil.ZeroByteArray(pbHash);
            return(pbRet);
        }
Example #34
0
        public static bool VerifyData(byte[] bytesToVerify, string signedMessage, RSAParameters publicKey)
        {
            bool success = false;
            using (var rsa = new RSACryptoServiceProvider())
            {
                byte[] signedBytes = Convert.FromBase64String(signedMessage);
                try
                {
                    rsa.ImportParameters(publicKey);

                    SHA512Managed Hash = new SHA512Managed();

                    byte[] hashedData = Hash.ComputeHash(signedBytes);

                    success = rsa.VerifyData(bytesToVerify, CryptoConfig.MapNameToOID("SHA512"), signedBytes);
                }
                catch (CryptographicException e)
                {
                    Console.WriteLine(e.Message);
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }
            return success;
        }
Example #35
0
    public static string ComputeHash(string plainText, string hashAlgorithm, byte[] saltBytes)
    {
        if (saltBytes == null)
        {
            int minSaltSize = 4;
            int maxSaltSize = 8;

            Random random = new Random();
            int saltSize = random.Next(minSaltSize, maxSaltSize);

            saltBytes = new byte[saltSize];

            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

            rng.GetNonZeroBytes(saltBytes);
        }

        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

        byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length];

        for (int i = 0; i < plainTextBytes.Length; i++)
            plainTextWithSaltBytes[i] = plainTextBytes[i];

        for (int i = 0; i < saltBytes.Length; i++)
            plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];

        HashAlgorithm hash;

        if (hashAlgorithm == null)
            hashAlgorithm = "";

        switch (hashAlgorithm.ToUpper())
        {
            case "SHA1":
                hash = new SHA1Managed();
                break;

            case "SHA256":
                hash = new SHA256Managed();
                break;

            case "SHA384":
                hash = new SHA384Managed();
                break;

            case "SHA512":
                hash = new SHA512Managed();
                break;

            default:
                hash = new MD5CryptoServiceProvider();
                break;
        }

        byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);

        byte[] hashWithSaltBytes = new byte[hashBytes.Length + saltBytes.Length];

        for (int i = 0; i < hashBytes.Length; i++)
            hashWithSaltBytes[i] = hashBytes[i];

        for (int i = 0; i < saltBytes.Length; i++)
            hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];

        string hashValue = Convert.ToBase64String(hashWithSaltBytes);

        return hashValue;
    }
Example #36
0
        // This function verifies if credentails exist and whether or not user is
        // authenticated by our system. (Overloading)

        public async Task <string> VerifyUserCredentials(string userEmail, string userPassword, AccountSalt accountSalt)
        {
            string isUserVerified = "";

            try
            {
                SHA512 sHA512         = new SHA512Managed();
                var    client         = new HttpClient();
                byte[] data           = sHA512.ComputeHash(Encoding.UTF8.GetBytes(userPassword + accountSalt.password_salt));
                string hashedPassword = BitConverter.ToString(data).Replace("-", string.Empty).ToLower();

                LogInPost loginPostContent = new LogInPost();
                loginPostContent.email           = userEmail;
                loginPostContent.password        = hashedPassword;
                loginPostContent.social_id       = "";
                loginPostContent.signup_platform = "";

                string loginPostContentJson = JsonConvert.SerializeObject(loginPostContent);

                var httpContent = new StringContent(loginPostContentJson, Encoding.UTF8, "application/json");
                var response    = await client.PostAsync(Constant.LogInUrl, httpContent);

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();

                    var authetication = JsonConvert.DeserializeObject <RDSAuthentication>(responseContent);

                    if (authetication.code.ToString() == Constant.EmailNotFound)
                    {
                        userToSignUp          = new SignUpAccount();
                        userToSignUp.email    = userEmail.ToLower().Trim();
                        userToSignUp.password = userPassword.Trim();
                        userToSignUp.platform = "DIRECT";

                        isUserVerified = "USER NEEDS TO SIGN UP";
                    }
                    else if (authetication.code.ToString() == Constant.AutheticatedSuccesful)
                    {
                        DateTime today   = DateTime.Now;
                        DateTime expDate = today.AddDays(Constant.days);

                        user             = new User();
                        user.id          = authetication.result[0].driver_uid;
                        user.sessionTime = expDate;
                        user.platform    = "DIRECT";
                        user.email       = "";
                        user.socialId    = "";
                        user.route_id    = "";

                        //var notificationStatus = await SetUserRemoteNotification();

                        //isUserVerified = EvaluteUserUpdates(notificationStatus);

                        isUserVerified = "SUCCESSFUL:0";

                        SaveUser(user);
                    }
                    else if (authetication.code.ToString() == Constant.ErrorPlatform)
                    {
                        //var RDSCode = JsonConvert.DeserializeObject<RDSLogInMessage>(responseContent);

                        isUserVerified = "WRONG SOCIAL MEDIA TO SIGN IN";
                    }
                    else if (authetication.code.ToString() == Constant.ErrorUserDirectLogIn)
                    {
                        isUserVerified = "WRONG DIRECT PASSWORD";
                    }
                }
            }
            catch (Exception errorLogInUser)
            {
                //var client = new Diagnostic();
                //client.parseException(errorLogInUser.ToString(), user);

                Debug.WriteLine("ERROR THE 'errorLogInUser' FUNCTION: " + errorLogInUser.Message);
            }

            return(isUserVerified);
        }
Example #37
0
    //AIM: THIS FUNCTION IS USE to encrypt the string and create hask key using diff hash methods
    public string FromString(string input, HashType hashtype)
    {
        Byte[] clearBytes;
            Byte[] hashedBytes;
            string output = String.Empty;

            switch (hashtype)
            {
                case HashType.RIPEMD160:
                    clearBytes = new UTF8Encoding().GetBytes(input);
                    RIPEMD160 myRIPEMD160 = RIPEMD160Managed.Create();
                    hashedBytes = myRIPEMD160.ComputeHash(clearBytes);
                    output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                    break;
                case HashType.MD5:
                    clearBytes = new UTF8Encoding().GetBytes(input);
                    hashedBytes = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes);
                    output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                    break;
                case HashType.SHA1:
                    clearBytes = Encoding.UTF8.GetBytes(input);
                    SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
                    sha1.ComputeHash(clearBytes);
                    hashedBytes = sha1.Hash;
                    sha1.Clear();
                    output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                    break;
                case HashType.SHA256:
                    clearBytes = Encoding.UTF8.GetBytes(input);
                    SHA256 sha256 = new SHA256Managed();
                    sha256.ComputeHash(clearBytes);
                    hashedBytes =sha256.Hash;

                    sha256.Clear();
                    output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                    break;
                case HashType.SHA384:
                    clearBytes = Encoding.UTF8.GetBytes(input);
                    SHA384 sha384 = new SHA384Managed();
                    sha384.ComputeHash(clearBytes);
                    hashedBytes = sha384.Hash;
                    sha384.Clear();
                    output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                    break;
                case HashType.SHA512:
                    clearBytes = Encoding.UTF8.GetBytes(input);
                    SHA512 sha512 = new SHA512Managed();
                    sha512.ComputeHash(clearBytes);
                    hashedBytes = sha512.Hash;
                    sha512.Clear();
                    output = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
                    break;
            }
            return output;
    }
Example #38
0
 private static string obf2_(string obf5_)
 {
     using (SHA512 obf3_ = new SHA512Managed())
     {
         byte[] obf4_ = obf3_.ComputeHash(Encoding.UTF8.GetBytes(obf5_));
         StringBuilder obf6_ = new StringBuilder();
         foreach (byte obf7_ in obf4_)
             obf6_.Append(obf7_.ToString("[TIMES2]"));
         return obf6_.ToString();
     }
 }
Example #39
0
 public String makeHash(String RekeningID, String pincode)
 {
     string input = String.Concat(RekeningID,pincode);
     byte[] bytes = Encoding.UTF8.GetBytes(input);
     SHA512Managed hashstring = new SHA512Managed();
     byte[] hash = hashstring.ComputeHash(bytes);
     string hashString = string.Empty;
     foreach (byte x in hash)
     {
         hashString += String.Format("{0:x2}", x);
     }
     return hashString;
 }
Example #40
0
        protected void register_btn_Click(object sender, EventArgs e)
        {
            error2_lb.Text = "";
            error_lb.Text  = "";
            bool pass = true;  // overall validation
            bool pmt  = false; // personal info empty check
            bool cmt  = false; // cc info empty check

            // checking if any fields are empty
            if (String.IsNullOrWhiteSpace(fname_tb.Text) || String.IsNullOrWhiteSpace(lname_tb.Text) || String.IsNullOrWhiteSpace(email_tb.Text) || String.IsNullOrWhiteSpace(dob_tb.Text) || String.IsNullOrWhiteSpace(pw1_tb.Text) || String.IsNullOrWhiteSpace(pw2_tb.Text))
            {
                error_lb.Text = "Please fill all fields. <br>";
                pmt           = true;
            }

            if (String.IsNullOrWhiteSpace(name_cc.Text) || String.IsNullOrWhiteSpace(cardno_cc.Text) || String.IsNullOrWhiteSpace(cvv_cc.Text) || String.IsNullOrWhiteSpace(expiry_cc.Text))
            {
                error2_lb.Text = "Please fill all fields. <br>";
                cmt            = true;
            }

            if (!pmt)
            {
                // checks if user exists
                DBServiceReference1.Service1Client client = new DBServiceReference1.Service1Client();
                var user = client.SelectByEmail(email_tb.Text.Trim());
                if (user != null)
                {
                    error_lb.Text = error_lb.Text + "User already exists.";
                    pass          = false;
                }

                Regex nameRegex = new Regex("[A-Za-z]");
                if (!nameRegex.IsMatch(fname_tb.Text.Trim()) || !nameRegex.IsMatch(lname_tb.Text.Trim()))
                {
                    error_lb.Text = error_lb.Text + "Please input a valid name <br>";
                    pass          = false;
                }

                // as long as dob is not today or in the future
                if (Convert.ToDateTime(dob_tb.Text.Trim()) >= DateTime.Now.Date)
                {
                    error_lb.Text = error_lb.Text + "Please input a valid date of birth <br>";
                    pass          = false;
                }

                Regex pwRegex = new Regex(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}");
                if (!pwRegex.IsMatch(pw1_tb.Text.Trim()))
                {
                    error_lb.Text = error_lb.Text + "Please input a password that fulfills all criteria <br>";
                    pass          = false;
                }

                if (pw1_tb.Text.Trim() != pw2_tb.Text.Trim())
                {
                    error_lb.Text = error_lb.Text + "Passwords must match <br>";
                    pass          = false;
                }
            }

            if (!cmt)
            {
                // validating credit card name is 2 words, number is 16 digits, cvv is 3 digits and date is valid
                Regex nameRegex = new Regex(@"^[A-Za-z]+\s+[A-Za-z]+$");
                if (!nameRegex.IsMatch(name_cc.Text.Trim()))
                {
                    error2_lb.Text = error2_lb.Text + "Please input a valid name <br>";
                    pass           = false;
                }

                Regex numRegex = new Regex(@"^([0-9]{4}\s*){4}$");
                if (!numRegex.IsMatch(cardno_cc.Text.Trim()))
                {
                    error2_lb.Text = error2_lb.Text + "Please input a valid card number <br>";
                    pass           = false;
                }

                Regex cvvRegex = new Regex("^[0-9]{3}$");
                if (!cvvRegex.IsMatch(cvv_cc.Text.Trim()))
                {
                    error2_lb.Text = error2_lb.Text + "Please input a valid CVV <br>";
                    pass           = false;
                }

                Regex expiryRegex = new Regex("^[0-9]{2}[/]{1}[0-9]{2}$");
                if (!expiryRegex.IsMatch(expiry_cc.Text.Trim()))
                {
                    error2_lb.Text = error2_lb.Text + "Please input a valid expiry date <br>";
                    pass           = false;
                }
                else
                {
                    string   date   = expiry_cc.Text.Trim();
                    string[] split  = date.Split('/');
                    DateTime expiry = Convert.ToDateTime("01/" + split[0] + "/20" + split[1]);

                    if (expiry <= DateTime.Now.Date)
                    {
                        error2_lb.Text = error2_lb.Text + "Please check your card's expiry <br>";
                        pass           = false;
                    }
                }
            }

            if (pass && !pmt && !cmt)
            {
                DBServiceReference1.Service1Client client = new DBServiceReference1.Service1Client();

                // retrieving data to hash
                string pw = pw1_tb.Text;

                // initializing bytes for salts
                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                byte[] pwsaltbyte            = new byte[8];

                // getting random salt bytes and converting into string
                rng.GetBytes(pwsaltbyte);
                string pwsalt = Convert.ToBase64String(pwsaltbyte);

                // initializing hashing thingy
                SHA512Managed hashing = new SHA512Managed();

                // salting plaintext and hashing after
                string saltedpw = pw.ToString() + pwsalt;
                string hashedpw = Convert.ToBase64String(hashing.ComputeHash(Encoding.UTF8.GetBytes(saltedpw)));

                RijndaelManaged cipher = new RijndaelManaged();
                cipher.GenerateKey();

                client.CreateAccount(email_tb.Text.Trim(), hashedpw, pwsalt, fname_tb.Text.Trim(), lname_tb.Text.Trim(), Convert.ToDateTime(dob_tb.Text.Trim()), name_cc.Text.Trim(), cardno_cc.Text.Trim(), cvv_cc.Text.Trim(), expiry_cc.Text.Trim(), cipher.IV, cipher.Key);
                Response.Redirect("Login.aspx");
            }
        }
Example #41
0
    /// <summary>
    /// Generates a hash for the given plain text value and returns a
    /// base64-encoded result. Before the hash is computed, a random salt
    /// is generated and appended to the plain text. This salt is stored at
    /// the end of the hash value, so it can be used later for hash
    /// verification.
    /// </summary>
    /// <param name="plainText">
    /// Plaintext value to be hashed. 
    /// </param>
    /// <param name="hashAlgorithm">
    /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1",
    /// "SHA256", "SHA384", and "SHA512" (if any other value is specified
    /// MD5 hashing algorithm will be used). This value is case-insensitive.
    /// </param>
    /// <param name="saltBytes">
    /// Salt bytes. This parameter can be null, in which case a random salt
    /// value will be generated.
    /// </param>
    /// <returns>
    /// Hash value formatted as a base64-encoded string.
    /// </returns>
    /// <remarks>
    /// ComputeHash code provided as an example by Obviex at
    /// http://www.obviex.com/samples/hash.aspx
    /// As noted by Obviex themselves, code is definitely not optimally efficient.
    /// Should performance requirements necessitate improvement, this should
    /// be improved.
    /// </remarks>
    public static string ComputeHash(string plainText,
                                     string hashAlgorithm,
                                     byte[] saltBytes)
    {
        if (plainText == null)
            return null;

        // If salt is not specified, generate it on the fly.
        if (saltBytes == null)
        {
            // Define min and max salt sizes.
            int minSaltSize = 4;
            int maxSaltSize = 8;

            // Generate a random number for the size of the salt.
            Random random = new Random();
            int saltSize = random.Next(minSaltSize, maxSaltSize);

            // Allocate a byte array, which will hold the salt.
            saltBytes = new byte[saltSize];

            // Initialize a random number generator.
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

            // Fill the salt with cryptographically strong byte values.
            rng.GetNonZeroBytes(saltBytes);
        }

        // Convert plain text into a byte array.
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

        // Allocate array, which will hold plain text and salt.
        byte[] plainTextWithSaltBytes =
                new byte[plainTextBytes.Length + saltBytes.Length];

        // Copy plain text bytes into resulting array.
        for (int i = 0; i < plainTextBytes.Length; i++)
            plainTextWithSaltBytes[i] = plainTextBytes[i];

        // Append salt bytes to the resulting array.
        for (int i = 0; i < saltBytes.Length; i++)
            plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];

        // Because we support multiple hashing algorithms, we must define
        // hash object as a common (abstract) base class. We will specify the
        // actual hashing algorithm class later during object creation.
        HashAlgorithm hash;

        // Make sure hashing algorithm name is specified.
        if (hashAlgorithm == null)
            hashAlgorithm = "";

        // Initialize appropriate hashing algorithm class.
        switch (hashAlgorithm.ToUpper())
        {
            case "SHA1":
                hash = new SHA1Managed();
                break;

            case "SHA256":
                hash = new SHA256Managed();
                break;

            case "SHA384":
                hash = new SHA384Managed();
                break;

            case "SHA512":
                hash = new SHA512Managed();
                break;

            default:
                hash = new MD5CryptoServiceProvider();
                break;
        }

        // Compute hash value of our plain text with appended salt.
        byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);

        // Create array which will hold hash and original salt bytes.
        byte[] hashWithSaltBytes = new byte[hashBytes.Length +
                                            saltBytes.Length];

        // Copy hash bytes into resulting array.
        for (int i = 0; i < hashBytes.Length; i++)
            hashWithSaltBytes[i] = hashBytes[i];

        // Append salt bytes to the result.
        for (int i = 0; i < saltBytes.Length; i++)
            hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];

        // Convert result into a base64-encoded string.
        string hashValue = Convert.ToBase64String(hashWithSaltBytes);

        // Return the result.
        return hashValue;
    }
Example #42
0
        private static string ComputeHash(string plainText,
                                          string hashAlgorithm,
                                          byte[] saltBytes)
        {
            if (saltBytes == null)
            {
                int minSaltSize = 4;
                int maxSaltSize = 8;


                Random random   = new Random();
                int    saltSize = random.Next(minSaltSize, maxSaltSize);


                saltBytes = new byte[saltSize];


                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();


                rng.GetNonZeroBytes(saltBytes);
            }


            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);


            byte[] plainTextWithSaltBytes =
                new byte[plainTextBytes.Length + saltBytes.Length];

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

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

            HashAlgorithm hash;

            if (hashAlgorithm == null)
            {
                hashAlgorithm = "";
            }

            switch (hashAlgorithm.ToUpper())
            {
            case "SHA1":
                hash = new SHA1Managed();
                break;

            case "SHA256":
                hash = new SHA256Managed();
                break;

            case "SHA384":
                hash = new SHA384Managed();
                break;

            case "SHA512":
                hash = new SHA512Managed();
                break;

            default:
                hash = new MD5CryptoServiceProvider();
                break;
            }

            byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);

            byte[] hashWithSaltBytes = new byte[hashBytes.Length +
                                                saltBytes.Length];

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

            for (int i = 0; i < saltBytes.Length; i++)
            {
                hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];
            }

            string hashValue = Convert.ToBase64String(hashWithSaltBytes);

            return(hashValue);
        }
Example #43
0
        /// <summary>
        /// Generates a hash for the given plain text value and returns a
        /// base64-encoded result. Before the hash is computed, a random salt
        /// is generated and appended to the plain text. This salt is stored at
        /// the end of the hash value, so it can be used later for hash
        /// verification.
        /// </summary>
        /// <param name="byteData">
        /// Plaintext value to be hashed.
        /// </param>
        /// <param name="hashAlgorithm">
        /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1",
        /// "SHA256", "SHA384", "SHA512", "HMACMD5", "HMACSHA1", "HMACSHA256",
        ///  "HMACSHA512" (if any other value is specified  MD5 will be used).
        ///
        /// HMAC algorithms uses Hash-based Message Authentication Code.
        /// The HMAC process mixes a secret key with the message data, hashes
        /// the result with the hash function, mixes that hash value with
        /// the secret key again, and then applies the hash function
        /// a second time. HMAC hashes are fixed lenght and generally
        /// much longer than non-HMAC hashes of the same type.
        ///
        /// https://msdn.microsoft.com/en-us/library/system.security.cryptography.hmacsha256(v=vs.110).aspx
        ///
        /// This value is case-insensitive.
        /// </param>
        /// <param name="saltBytes">
        /// Optional but recommended salt bytes to apply to the hash. If not passed the
        /// raw encoding is used. If salt is nullthe raw algorithm is used (useful for
        /// file hashes etc.) HMAC versions REQUIRE that salt is passed.
        /// </param>
        /// <param name="useBinHex">if true returns the data as BinHex byte pair string. Otherwise Base64 is returned.</param>
        /// <returns>
        /// Hash value formatted as a base64-encoded or BinHex stringstring.
        /// </returns>
        public static string ComputeHash(byte[] byteData,
                                         string hashAlgorithm,
                                         byte[] saltBytes,
                                         bool useBinHex = false)
        {
            if (byteData == null)
            {
                return(null);
            }

            // Convert plain text into a byte array.
            byte[] plainTextWithSaltBytes;

            if (saltBytes != null)
            {
                // Allocate array, which will hold plain text and salt.
                plainTextWithSaltBytes =
                    new byte[byteData.Length + saltBytes.Length];

                // Copy plain text bytes into resulting array.
                for (int i = 0; i < byteData.Length; i++)
                {
                    plainTextWithSaltBytes[i] = byteData[i];
                }

                // Append salt bytes to the resulting array.
                for (int i = 0; i < saltBytes.Length; i++)
                {
                    plainTextWithSaltBytes[byteData.Length + i] = saltBytes[i];
                }
            }
            else
            {
                plainTextWithSaltBytes = byteData;
            }

            HashAlgorithm hash;

            // Make sure hashing algorithm name is specified.
            if (hashAlgorithm == null)
            {
                hashAlgorithm = "";
            }

            // Initialize appropriate hashing algorithm class.
            switch (hashAlgorithm.ToUpper())
            {
            case "SHA1":
                hash = new SHA1Managed();
                break;

            case "SHA256":
                hash = new SHA256Managed();
                break;

            case "SHA384":
                hash = new SHA384Managed();
                break;

            case "SHA512":
                hash = new SHA512Managed();
                break;

            case "HMACMD5":
                hash = new HMACMD5(saltBytes);
                break;

            case "HMACSHA1":
                hash = new HMACSHA1(saltBytes);
                break;

            case "HMACSHA256":
                hash = new HMACSHA256(saltBytes);
                break;

            case "HMACSHA512":
                hash = new HMACSHA512(saltBytes);
                break;

            default:
                // default to MD5
                hash = new MD5CryptoServiceProvider();
                break;
            }

            byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);


            hash.Dispose();

            if (useBinHex)
            {
                return(BinaryToBinHex(hashBytes));
            }

            return(Convert.ToBase64String(hashBytes));
        }
Example #44
0
     public static string GetSHA512(string text)
     {
         ASCIIEncoding UE = new ASCIIEncoding();
         byte[] hashValue;
         byte[] message = UE.GetBytes(text);

         SHA512Managed hashString = new SHA512Managed();
         string hex = "";

         hashValue = hashString.ComputeHash(message);
         foreach (byte x in hashValue)
         {
             hex += String.Format("{0:x2}", x);
         }
         return hex;
     }