Esempio n. 1
0
        public void BytesArrayTest(HashMethod hashMethod)
        {
            var bf = FilterBuilder.Build(10000, 0.01, hashMethod);

            var rng = RandomNumberGenerator.Create();

            var len  = 10;
            var list = new List <byte[]>(len);

            for (int i = 0; i < len; i++)
            {
                var data = new byte[1024];
                rng.GetBytes(data);
                list.Add(data);
            }

            Assert.All(bf.Add(list), r => Assert.True(r));
            Assert.All(bf.Contains(list), r => Assert.True(r));

            Assert.True(bf.All(list));

            bf.Clear();

            Assert.All(bf.Contains(list), r => Assert.False(r));
            Assert.False(bf.All(list));
        }
Esempio n. 2
0
        public static string ComputeHashDigest(string hashString, string preSharedKey, HashMethod hashMethod)
        {
            byte[] key = StringToByteArray(preSharedKey);
            byte[] data = StringToByteArray(hashString);

            byte[] hashDigest;

            switch (hashMethod)
            {
                case HashMethod.HMACMD5:
                    hashDigest = new HMACMD5(key).ComputeHash(data);
                    break;
                case HashMethod.HMACSHA1:
                    hashDigest = new HMACSHA1(key).ComputeHash(data);
                    break;
                case HashMethod.MD5:
                    hashDigest = new MD5CryptoServiceProvider().ComputeHash(data);
                    break;
                case HashMethod.SHA1:
                    hashDigest = new SHA1CryptoServiceProvider().ComputeHash(data);
                    break;
                default:
                    throw new InvalidOperationException("Invalid hash method");
            }

            return (ByteArrayToHexString(hashDigest));
        }
Esempio n. 3
0
        private void ConductTest(HashMethod method, string emptyHash, string helloHash, string longfileHash)
        {
            //Assert.ThrowsException<ArgumentException>(() => { method.Invoke(""); });
            //Assert.ThrowsException<FileNotFoundException>(() => { method.Invoke("notarealfile.notreal.donotmake"); });

            const string testPath = "hashtestfile.test";

            File.Create(testPath).Close();
            Assert.AreEqual(emptyHash, method.Invoke(testPath));

            File.WriteAllText(testPath, "Hello, world!");
            Assert.AreEqual(helloHash, method.Invoke(testPath));

            try
            {
                using (Stream s = File.OpenWrite(testPath))
                {
                    long size = 1024 * 1024 * 32;
                    for (long i = 0; i < size; i++)
                    {
                        s.WriteByte((byte)i);
                    }
                }
                Assert.AreEqual(longfileHash, method.Invoke(testPath));
            }
            finally
            {
                File.Delete(testPath);
            }
        }
Esempio n. 4
0
        public static bool Compare(HashMethod method, Stream stream1, Stream stream2)
        {
            try
            {
                string strHash1 = string.Empty;
                string strHash2 = string.Empty;
                switch (method)
                {
                case HashMethod.SHA256:
                    strHash1 = SHA256(stream1);
                    strHash2 = SHA256(stream2);
                    break;

                case HashMethod.SHA512:
                    strHash1 = SHA512(stream1);
                    strHash2 = SHA512(stream2);
                    break;

                case HashMethod.MD5:
                    strHash1 = MD5(stream1);
                    strHash2 = MD5(stream2);
                    break;
                }

                StringComparer sc = StringComparer.OrdinalIgnoreCase;

                return(0 == sc.Compare(strHash1, strHash2));
            }
            catch
            {
                throw;
            }
        }
Esempio n. 5
0
        public static bool CompareResult(HashMethod method, string file, string hash)
        {
            try
            {
                if (!File.Exists(file))
                {
                    return(false);
                }

                string strResult = string.Empty;
                switch (method)
                {
                case HashMethod.SHA256:
                    strResult = SHA256(file);
                    break;

                case HashMethod.SHA512:
                    strResult = SHA512(file);
                    break;

                case HashMethod.MD5:
                    strResult = MD5(file);
                    break;
                }

                StringComparer sc = StringComparer.OrdinalIgnoreCase;

                return(0 == sc.Compare(strResult, hash));
            }
            catch
            {
                throw;
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Create a hash value from a byte array's content.
        /// </summary>
        /// <param name="content">the literal content to evaluate for the hash.</param>
        /// <param name="method">The HashMethod enumeration for the evaluation</param>
        /// <returns>A hex-encoded value of the hash value</returns>
        public static string GetHash(byte[] content, HashMethod method)
        {
            HashAlgorithm hashString = new SHA1Managed();

            switch (method)
            {
            case HashMethod.SHA1:
                break;

            case HashMethod.SHA256:
                hashString = new SHA256Managed();
                break;

            case HashMethod.SHA384:
                hashString = new SHA384Managed();
                break;

            case HashMethod.SHA512:
                hashString = new SHA512Managed();
                break;

            case HashMethod.MD5:
                hashString = new MD5CryptoServiceProvider();
                break;

            case HashMethod.RIPEMD:
                hashString = new RIPEMD160Managed();
                break;

            default:
                throw new ArgumentException("Unrecognized hash encoding: " + method.ToString());
            }
            return(ByteArrayToHex(hashString.ComputeHash(content)));
        }
Esempio n. 7
0
        public static string GerarHash(string source, HashMethod algorithm)
        {
            HashAlgorithm hashAlgorithm = null;

            switch (algorithm)
            {
            case HashMethod.MD5:

                hashAlgorithm = new MD5CryptoServiceProvider();

                break;

            case HashMethod.SHA1:

                hashAlgorithm = new SHA1CryptoServiceProvider();

                break;

            case HashMethod.SHA384:

                hashAlgorithm = new SHA384Managed();

                break;

            default:


                return(string.Empty);
            }

            byte[] byteValue = Encoding.UTF8.GetBytes(source);
            byte[] hashValue = hashAlgorithm.ComputeHash(byteValue);

            return(Convert.ToBase64String(hashValue));
        }
Esempio n. 8
0
 /// <summary>
 /// Gets the hash.
 /// </summary>
 /// <param name="data">The data.</param>
 /// <param name="method">The method.</param>
 /// <returns></returns>
 public static byte[] GetHash(Stream data, HashMethod method)
 {
     using (var alogirthm = GetHashAlogrithm(method))
     {
         return(alogirthm.ComputeHash(data));
     }
 }
        public static byte[] SaltedHash(this byte[] input, byte[] salt, HashMethod method = HashMethod.SHA256)
        {
            List <byte> tempList = input.ToList();

            tempList.Concat(salt.ToList());
            return(tempList.ToArray().Hash(method));
        }
Esempio n. 10
0
        public bool AuthenticateAsClient(Stream stream, byte[] additionalChallenge = null)
        {
            if (additionalChallenge == null)
            {
                additionalChallenge = new byte[] { }
            }
            ;

            byte[] clientNonce = m_nonce.Next();
            stream.WriteWithLength(m_usernameBytes);
            stream.WriteWithLength(clientNonce);
            stream.Flush();

            HashMethod hashMethod = (HashMethod)stream.ReadByte();

            byte[] serverNonce = stream.ReadBytes();
            byte[] salt        = stream.ReadBytes();
            int    iterations  = stream.ReadInt32();

            SetServerValues(hashMethod, salt, iterations);

            byte[] authMessage     = Scram.ComputeAuthMessage(serverNonce, clientNonce, salt, m_usernameBytes, iterations, additionalChallenge);
            byte[] clientSignature = ComputeClientSignature(authMessage);
            byte[] clientProof     = Scram.XOR(m_clientKey, clientSignature);
            stream.WriteWithLength(clientProof);
            stream.Flush();

            byte[] serverSignature       = ComputeServerSignature(authMessage);
            byte[] serverSignatureVerify = stream.ReadBytes();
            return(serverSignature.SecureEquals(serverSignatureVerify));
        }
    }
Esempio n. 11
0
        public static bool CompareResult(HashMethod method, Stream stream, string hash)
        {
            try
            {
                string strResult = string.Empty;
                switch (method)
                {
                case HashMethod.SHA256:
                    strResult = SHA256(stream);
                    break;

                case HashMethod.SHA512:
                    strResult = SHA512(stream);
                    break;

                case HashMethod.MD5:
                    strResult = MD5(stream);
                    break;
                }

                StringComparer sc = StringComparer.OrdinalIgnoreCase;

                return(0 == sc.Compare(strResult, hash));
            }
            catch
            {
                throw;
            }
        }
        public static byte[] Hash(this byte[] input, HashMethod method = HashMethod.SHA256)
        {
            HashAlgorithm algorithm = SHA256.Create();

            try
            {
                switch (method)
                {
                case HashMethod.MD5:
                    algorithm = MD5.Create();
                    break;

                case HashMethod.SHA1:
                    algorithm = SHA1.Create();
                    break;

                case HashMethod.SHA256:
                    break;

                case HashMethod.SHA384:
                    algorithm = SHA384.Create();
                    break;

                case HashMethod.SHA512:
                    algorithm = SHA512.Create();
                    break;
                }
                return(algorithm.ComputeHash(input));
            }
            finally { algorithm.Dispose(); }
        }
        /// <summary>
        /// This method is used to hash binary data using the specified hashing algorithm.
        /// </summary>
        /// <param name="binaryData">Contains the binary data array to hash.</param>
        /// <param name="hashMethod">Contains the hashing algorithm to use to hash the specified data.</param>
        /// <param name="maximumLength">Contains the maximum number of hash bytes to return in the hash result.</param>
        /// <returns>Returns a byte array of hashed bytes</returns>
        public static byte[] ToHash(this byte[] binaryData, HashMethod hashMethod = HashMethod.SHA256, int maximumLength = 0)
        {
            byte[]        result        = Array.Empty <byte>();
            HashAlgorithm hashTransform = null;

            switch (hashMethod)
            {
            case HashMethod.SHA256:
                hashTransform = SHA256.Create();
                break;

            case HashMethod.SHA512:
                hashTransform = SHA512.Create();
                break;
            }

            if (hashTransform != null)
            {
                result = hashTransform.ComputeHash(binaryData);

                if (maximumLength > 0)
                {
                    result = result.Take(maximumLength).ToArray();
                }

                hashTransform.Dispose();
            }

            return(result);
        }
Esempio n. 14
0
 public Scanner(string rootPath, HashMethod hashMethod)
 {
     this.root = new DirectoryInfo(rootPath);
     this.hashMethod = hashMethod;
     this.items = new List<FileInformationItem>();
     this.running = false;
     this.shouldRun = false;
 }
 public void AddUser(string username, string password, int iterations = 4000, int saltSize = 32, HashMethod hashMethod = HashMethod.Sha256)
 {
     var user = new ScramUserCredential(username, password, iterations, saltSize, hashMethod);
     lock (m_users)
     {
         m_users.Add(user.UserBytes, user);
     }
 }
        /// <summary>
        /// This method is used to hash binary data using the specified hashing algorithm.
        /// </summary>
        /// <param name="fileInfo">Contains a <c>FileInfo</c> containing the file to hash.</param>
        /// <param name="hashMethod">Contains the hashing algorithm to use to hash the specified data.</param>
        /// <returns>Returns a hex-encoded string representing the bytes of the file hash result.</returns>
        public static string ToHashString(this FileInfo fileInfo, HashMethod hashMethod = HashMethod.SHA256)
        {
            if (fileInfo == null)
            {
                throw new ArgumentNullException(nameof(fileInfo));
            }

            return(File.ReadAllBytes(fileInfo.FullName).ToHash(hashMethod).ToHexString());
        }
Esempio n. 17
0
 public void FromRegistryString(string str)
 {
     string[] parts = Regex.Split(str, @"\n");
     if (parts.Length == 2)
     {
         Name   = parts[0];
         Method = (HashMethod)Enum.Parse(typeof(HashMethod), parts[1]);
     }
 }
Esempio n. 18
0
 public void FromRegistryString(string str)
 {
     string[] parts = Regex.Split(str, @"\n");
     if (parts.Length == 2)
     {
         Name = parts[0];
         Method = (HashMethod)Enum.Parse(typeof(HashMethod), parts[1]);
     }
 }
Esempio n. 19
0
        internal static void hash(HashMethod hm)
        {
            byte [] b        = GetSelectedText();
            string  dlgTitle = "";

            if (b == null) // Get whole content
            {
                MessageBox.Show("No selected data to hash.");
                return;
            }

            byte[] hash = null;
            if (hm == HashMethod.hm_MD5)
            {
                hash     = GetMD5(b);
                dlgTitle = "MD5";
            }
            else if (hm == HashMethod.hm_SHA1)
            {
                hash     = GetSha1(b);
                dlgTitle = "SHA1";
            }
            else if (hm == HashMethod.hm_SHA256)
            {
                hash     = GetSha256(b);
                dlgTitle = "SHA256";
            }
            else if (hm == HashMethod.hm_SHA384)
            {
                hash     = GetSha384(b);
                dlgTitle = "SHA384";
            }
            else if (hm == HashMethod.hm_SHA512)
            {
                hash     = GetSha512(b);
                dlgTitle = "SHA512";
            }
            else
            {
                return;
            }

            String hashStr    = BitConverter.ToString(hash).Replace("-", "");
            String hashB64Str = Convert.ToBase64String(hash);
            String data2hash  = GetTipStringFromByteArray(b, maxDisplayDataStringLen);

            if (hashResultDlg == null)
            {
                hashResultDlg = new HashResultDlg();
            }

            hashResultDlg.SetDlgTitle(dlgTitle);
            hashResultDlg.SetDataTipText(data2hash);
            hashResultDlg.SetHashResult(hashStr);
            hashResultDlg.SetHashB64Result(hashB64Str);
            hashResultDlg.Show();
        }
Esempio n. 20
0
        static HashBuilder()
        {
            Ldtoken(Method(Type <HashAlgorithm>(), nameof(HashCore), typeof(ReadOnlySpan <byte>)));
            Pop(out RuntimeMethodHandle handle);
            HashCore = Unsafe.As <MethodInfo>(MethodBase.GetMethodFromHandle(handle)).CreateDelegate <HashMethod>();

            Ldtoken(Method(Type <HashAlgorithm>(), nameof(TryHashFinal), typeof(Span <byte>), Type <int>().MakeByRefType()));
            Pop(out handle);
            TryHashFinal = Unsafe.As <MethodInfo>(MethodBase.GetMethodFromHandle(handle)).CreateDelegate <TryHashFinalMethod>();
        }
Esempio n. 21
0
        /// <summary>
        /// Gets the alogrithm.
        /// </summary>
        /// <param name="method">The method.</param>
        /// <param name="hashName">Name of the hash algorithm.</param>
        /// <returns></returns>
        /// <exception cref="System.NotSupportedException">
        /// </exception>
        private static HashAlgorithm GetHashAlogrithm(HashMethod method, string hashName = null)
        {
            if (hashName == null)
            {
                switch (method)
                {
                case HashMethod.MD5:
                    return(MD5CryptoServiceProvider.Create());

                case HashMethod.SHA1:
                    return(SHA1CryptoServiceProvider.Create());

                case HashMethod.SHA256:
                    return(SHA256CryptoServiceProvider.Create());

                case HashMethod.SHA384:
                    return(SHA384CryptoServiceProvider.Create());

                case HashMethod.SHA512:
                    return(SHA512CryptoServiceProvider.Create());

                case HashMethod.CRC32:
                    return(new CRC32());

                default:
                    throw new NotSupportedException(
                              string.Format("Method [{0}] is not supported.", method.ToString()));
                }
            }
            else
            {
                switch (method)
                {
                case HashMethod.MD5:
                    return(MD5CryptoServiceProvider.Create(hashName));

                case HashMethod.SHA1:
                    return(SHA1CryptoServiceProvider.Create(hashName));

                case HashMethod.SHA256:
                    return(SHA256CryptoServiceProvider.Create(hashName));

                case HashMethod.SHA384:
                    return(SHA384CryptoServiceProvider.Create(hashName));

                case HashMethod.SHA512:
                    return(SHA512CryptoServiceProvider.Create(hashName));

                default:
                    throw new NotSupportedException(
                              string.Format("Method [{0}] is not supported.", method.ToString()));
                }
            }
        }
Esempio n. 22
0
 private void SetHashMethod(HashMethod hashMethod)
 {
     m_hash = hashMethod switch
     {
         HashMethod.Sha1 => new Sha1Digest(),
         HashMethod.Sha256 => new Sha256Digest(),
         HashMethod.Sha384 => new Sha384Digest(),
         HashMethod.Sha512 => new Sha512Digest(),
         _ => throw new Exception("Unsupported Hash Method")
     };
 }
Esempio n. 23
0
        /// <summary>
        /// Performs basic validation of the transaction result (you should also implement your own e.g. check amounts against order)
        /// </summary>
        /// <param name="result">Transaction result</param>
        public void ValidateResult(ServerTransactionResult result, String MerchantId, String MerchantPassword, String PreSharedKey)
        {
            NameValueCollection nameValueCollection = new NameValueCollection();
            HashMethod          hashMethod          = HashMethod.SHA1;

            nameValueCollection.Add("PreSharedKey", PreSharedKey);
            nameValueCollection.Add("MerchantID", MerchantId);
            nameValueCollection.Add("Password", MerchantPassword);
            nameValueCollection.Add("StatusCode", Convert.ToInt32(result.StatusCode));
            nameValueCollection.Add("Message", result.Message);
            if (result.StatusCode == TransactionStatus.DuplicateTransaction)
            {
                nameValueCollection.Add("PreviousStatusCode", Convert.ToInt32(result.PreviousStatusCode));
            }
            else
            {
                nameValueCollection.Add("PreviousStatusCode", "");
            }
            nameValueCollection.Add("PreviousMessage", result.PreviousMessage);
            nameValueCollection.Add("CrossReference", result.CrossReference);
            nameValueCollection.Add("AddressNumericCheckResult", result.AddressNumericCheckResult);
            nameValueCollection.Add("PostCodeCheckResult", result.PostCodeCheckResult);
            nameValueCollection.Add("CV2CheckResult", result.CV2CheckResult);
            nameValueCollection.Add("ThreeDSecureAuthenticationCheckResult", result.ThreeDSecureAuthenticationCheckResult);
            nameValueCollection.Add("CardType", result.CardType);
            nameValueCollection.Add("CardClass", result.CardClass);
            nameValueCollection.Add("CardIssuer", result.CardIssuer);
            nameValueCollection.Add("CardIssuerCountryCode", result.CardIssuerCountryCode);
            nameValueCollection.Add("Amount", result.Amount);
            nameValueCollection.Add("CurrencyCode", Convert.ToString(result.CurrencyCode));
            nameValueCollection.Add("OrderID", result.OrderID);
            nameValueCollection.Add("TransactionType", result.TransactionType);
            nameValueCollection.Add("TransactionDateTime", Convert.ToString(result.TransactionDateTime));
            nameValueCollection.Add("OrderDescription", result.OrderDescription);
            nameValueCollection.Add("CustomerName", result.CustomerName);
            nameValueCollection.Add("Address1", result.Address1);
            nameValueCollection.Add("Address2", result.Address2);
            nameValueCollection.Add("Address3", result.Address3);
            nameValueCollection.Add("Address4", result.Address4);
            nameValueCollection.Add("City", result.City);
            nameValueCollection.Add("State", result.State);
            nameValueCollection.Add("PostCode", result.PostCode);
            nameValueCollection.Add("CountryCode", Convert.ToString(result.CountryCode));
            nameValueCollection.Add("EmailAddress", result.EmailAddress);
            nameValueCollection.Add("PhoneNumber", result.PhoneNumber);
            bool   flag        = false;
            string queryString = nameValueCollection.ToQueryString("&", false, flag);
            string str         = HashUtil.ComputeHashDigest(queryString, PreSharedKey, hashMethod);

            if (result.HashDigest != str)
            {
                throw new Exception("Hash Check Failed");
            }
        }
Esempio n. 24
0
 public static string HashTextUTF8(HashMethod method, string content)
 {
     try
     {
         return(HashText(method, Encoding.UTF8, content));
     }
     catch
     {
         throw;
     }
 }
Esempio n. 25
0
        private bool Authenticate(Stream stream, byte[] additionalChallenge)
        {
            HashMethod passwordHashMethod = (HashMethod)stream.ReadNextByte();

            byte[] salt       = stream.ReadBytes(stream.ReadNextByte());
            int    iterations = stream.ReadInt32();

            SetHashMethod((HashMethod)stream.ReadNextByte());
            SetSrpStrength((SrpStrength)stream.ReadInt32());

            m_credentials.TryUpdate(passwordHashMethod, salt, iterations);

            BigInteger pubA = m_client.GenerateClientCredentials(m_hash, salt, m_credentials.UsernameBytes, m_credentials.SaltedPassword);

            byte[] pubABytes = pubA.ToPaddedArray(m_srpByteLength);

            stream.Write(pubABytes);
            stream.Flush();

            //Read from Server: B
            byte[]     pubBBytes = stream.ReadBytes(m_srpByteLength);
            BigInteger pubB      = new BigInteger(1, pubBBytes);

            //Calculate Session Key
            BigInteger S = m_client.CalculateSecret(m_hash, pubB);

            byte[] SBytes = S.ToPaddedArray(m_srpByteLength);

            byte[] clientProof = m_hash.ComputeHash(pubABytes, pubBBytes, SBytes, additionalChallenge);
            stream.Write(clientProof);
            stream.Flush();

            byte[] serverProof = m_hash.ComputeHash(pubBBytes, pubABytes, SBytes, additionalChallenge);

            if (stream.ReadBoolean())
            {
                byte[] serverProofCheck = stream.ReadBytes(m_hash.GetDigestSize());
                int    ticketLength     = stream.ReadInt16();
                if (ticketLength < 0 || ticketLength > 10000)
                {
                    return(false);
                }

                if (serverProofCheck.SecureEquals(serverProof))
                {
                    m_resumeTicket  = stream.ReadBytes(ticketLength);
                    m_sessionSecret = m_hash.ComputeHash(pubABytes, SBytes, pubBBytes).Combine(m_hash.ComputeHash(pubBBytes, SBytes, pubABytes));
                    return(true);
                }
                return(false);
            }
            return(false);
        }
        public static HashMethod Sequence(HashMethod method1, params HashMethod[] methods)
        {
            return x =>
            {
                x = method1(x);

                foreach (var m in methods)
                    x = m(x);

                return x;
            };
        }
Esempio n. 27
0
        /// <summary>
        /// Gets the hash.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <param name="method">The hash method.</param>
        /// <param name="encoding">The encoding of parameter <c>data</c>.</param>
        /// <returns></returns>
        public static byte[] GetHash(string data, HashMethod method, Encoding encoding)
        {
            if (encoding == null)
            {
                throw new ArgumentNullException(nameof(encoding));
            }

            using (var alogrithm = GetHashAlogrithm(method))
            {
                return(alogrithm.ComputeHash(encoding.GetBytes(data)));
            }
        }
Esempio n. 28
0
        /// <summary>
        /// Returns a secure hash of the given input string.
        /// </summary>
        /// <param name="input">The string to hash</param>
        /// <param name="method">The hash algorithm implementation to use.</param>
        /// <returns>The secure hash</returns>
        public static byte[] ComputeHash(string input, HashMethod method = HashMethod.Sha256)
        {
            if (input == null)
            {
                return(null);
            }

            UnicodeEncoding ue = new UnicodeEncoding();

            byte[] bytes = ue.GetBytes(input);

            using (var hasher = HashAlgorithm.Create(method.StringOf()))
                return(hasher?.ComputeHash(bytes));
        }
Esempio n. 29
0
        private static string StringOf(this HashMethod method)
        {
            switch (method)
            {
            case HashMethod.Md5:
                return("MD5");

            case HashMethod.Sha256:
                return("SHA256");

            default:
                throw new ArgumentOutOfRangeException(nameof(method), method, null);
            }
        }
        public static HashMethod Sequence(HashMethod method1, params HashMethod[] methods)
        {
            return(x =>
            {
                x = method1(x);

                foreach (var m in methods)
                {
                    x = m(x);
                }

                return x;
            });
        }
Esempio n. 31
0
        /// <summary>
        /// Updates the <see cref="SaltedPassword"/>. Returns False if the password value did not change.
        /// </summary>
        /// <param name="hashMethod"></param>
        /// <param name="salt"></param>
        /// <param name="iterations"></param>
        /// <returns>Returns False if the password value did not change.</returns>
        public bool TryUpdate(HashMethod hashMethod, byte[] salt, int iterations)
        {
            bool hasChanged = false;

            if (m_salt == null || !salt.SecureEquals(m_salt))
            {
                hasChanged = true;
                m_salt     = salt;
            }

            if (m_hashMethod != hashMethod)
            {
                hasChanged   = true;
                m_hashMethod = hashMethod;
            }

            if (iterations != m_iterations)
            {
                hasChanged   = true;
                m_iterations = iterations;
            }

            if (hasChanged)
            {
                switch (hashMethod)
                {
                case HashMethod.Sha1:
                    SaltedPassword = PBKDF2.ComputeSaltedPassword(HMACMethod.SHA1, m_passwordBytes, m_salt, m_iterations, 20);
                    break;

                case HashMethod.Sha256:
                    SaltedPassword = PBKDF2.ComputeSaltedPassword(HMACMethod.SHA256, m_passwordBytes, m_salt, m_iterations, 32);
                    break;

                case HashMethod.Sha384:
                    SaltedPassword = PBKDF2.ComputeSaltedPassword(HMACMethod.SHA384, m_passwordBytes, m_salt, m_iterations, 48);
                    break;

                case HashMethod.Sha512:
                    SaltedPassword = PBKDF2.ComputeSaltedPassword(HMACMethod.SHA512, m_passwordBytes, m_salt, m_iterations, 64);
                    break;

                default:
                    throw new Exception("Invalid Hash Method");
                }
                return(true);
            }
            return(false);
        }
    protected void submit_Click(object sender, EventArgs e)
    {
        danger(this.prono.Text);
        danger(this.password.Text);

        string        connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
        SqlConnection conn    = new SqlConnection(connStr);

        conn.Open();

        SqlCommand cmd = new SqlCommand();

        cmd.Connection  = conn;
        cmd.CommandText = "SELECT password,leader,money,name FROM project WHERE username = '******'";

        SqlDataReader dr = cmd.ExecuteReader();

        HashMethod hm = new HashMethod();

        if (dr.Read())
        {
            if (hm.Encrypto(this.password.Text) == dr[0].ToString().Trim())
            {
                Session["xiangmuhao"]  = this.prono.Text;
                Session["guanliyuan"]  = dr[1].ToString().Trim();
                Session["money"]       = dr[2].ToString().Trim();
                Session["xiangmuming"] = dr[3].ToString().Trim();

                conn.Close();
                conn.Dispose();

                Response.Redirect("manage/frontpage.aspx");
            }
            else
            {
                conn.Close();
                conn.Dispose();

                ClientScript.RegisterStartupScript(GetType(), "", "<script>alert(\"用户名或密码错误,请重新输入!\")</script>");
            }
        }
        else
        {
            conn.Close();
            conn.Dispose();

            ClientScript.RegisterStartupScript(GetType(), "", "<script>alert(\"用户名或密码错误,请重新输入!\")</script>");
        }
    }
 private void hashMethodChanged(object sender, EventArgs e)
 {
     if (lazyHashRadioButton.Checked)
     {
         this.selectedHash = HashMethod.Lazy;
     }
     else if (simpleHashRadioButton.Checked)
     {
         this.selectedHash = HashMethod.Simple;
     }
     else
     {
         this.selectedHash = HashMethod.Full;
     }
 }
 internal static IDigest CreateDigest(HashMethod hashMethod)
 {
     switch (hashMethod)
     {
         case HashMethod.Sha1:
             return new Sha1Digest();
         case HashMethod.Sha256:
             return new Sha256Digest();
         case HashMethod.Sha384:
             return new Sha384Digest();
         case HashMethod.Sha512:
             return new Sha512Digest();
         default:
             throw new InvalidEnumArgumentException("hashMethod", (int)hashMethod, typeof(HashMethod));
     }
 }
Esempio n. 35
0
        private void ErrRateTest(HashMethod hashMethod, IList <byte[]> hashData, IList <byte[]> probeData, int n, double p)
        {
            var bf = FilterBuilder.Build(n, p, hashMethod);

            int inserts  = hashData.Count;
            int errRates = 0;
            var set      = new HashSet <byte[]>();

            Stopwatch sw = Stopwatch.StartNew();

            foreach (var data in hashData)
            {
                if (bf.Contains(data) && !set.Contains(data))
                {
                    errRates++;
                }
                bf.Add(data);
                set.Add(data);
            }
            sw.Stop();

            int totalErrRates = 0;
            int probed        = 0;

            foreach (var data in probeData)
            {
                if (probed > inserts)
                {
                    break;
                }
                if (!set.Contains(data))
                {
                    probed++;
                    if (bf.Contains(data))
                    {
                        totalErrRates++;
                    }
                }
            }

            double errorRate      = 100.0 * errRates / inserts;
            double totalErrorRate = 100.0 * totalErrRates / inserts;

            Console.WriteLine($"{hashMethod} {bf} \r\n Speed:{sw.Elapsed.TotalMilliseconds}ms " +
                              $"ErrRate:{errorRate.ToString("F3")} Final ErrRate:{totalErrorRate.ToString("F3")}");
        }
Esempio n. 36
0
 public static string CalculateHash(FileInformationItem file, HashMethod method)
 {
     if (HashMethod.Simple == method)
     {
         return CalculateSimpleHash(file);
     }
     else if (HashMethod.Lazy == method)
     {
         return CalculateLazyHash(file);
     }
     else if (HashMethod.Full == method)
     {
         return CalculateFullHash(file);
     }
     else
     {
         throw new ArgumentException();
     }
 }
 void SetHashMethod(HashMethod hashMethod)
 {
     switch (hashMethod)
     {
         case HashMethod.Sha1:
             m_hash = new Sha1Digest();
             break;
         case HashMethod.Sha256:
             m_hash = new Sha256Digest();
             break;
         case HashMethod.Sha384:
             m_hash = new Sha384Digest();
             break;
         case HashMethod.Sha512:
             m_hash = new Sha512Digest();
             break;
         default:
             throw new Exception("Unsupported Hash Method");
     }
 }
Esempio n. 38
0
        internal static IDigest CreateDigest(HashMethod hashMethod)
        {
            switch (hashMethod)
            {
            case HashMethod.Sha1:
                return(new Sha1Digest());

            case HashMethod.Sha256:
                return(new Sha256Digest());

            case HashMethod.Sha384:
                return(new Sha384Digest());

            case HashMethod.Sha512:
                return(new Sha512Digest());

            default:
                throw new InvalidEnumArgumentException("hashMethod", (int)hashMethod, typeof(HashMethod));
            }
        }
Esempio n. 39
0
        /// <summary>
        /// Finds the cached version or tries to fetch the method based on the name and its parameters.
        /// </summary>
        /// <param name="methodName"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public MethodInfo       GetMethod(string methodName, string parameters)
        {
            // Ugly? Why not? @_@
            int hash = methodName.GetHashCode() + parameters.GetHashCode();

            // Check if cached.
            for (int i = 0; i < this.indexLeft; i++)
            {
                if (this.methods[i].hash == hash)
                {
                    return(this.methods[i].methodInfo);
                }
            }

            try
            {
                // Populate new file.
                HashMethod hashMethod = new HashMethod(hash);

                hashMethod.methodInfo = this.GetMethodInfo(methodName, parameters);

                // Check array overflow.
                if (this.indexLeft == this.methods.Length)
                {
                    Array.Resize(ref this.methods, this.methods.Length << 1);
                }

                this.methods[this.indexLeft] = hashMethod;
                ++this.indexLeft;

                //Debug.Log("Cached method:" + methodName + "(" + parameters + ")");
                return(hashMethod.methodInfo);
            }
            catch (Exception ex)
            {
                InternalNGDebug.LogException(ex);
            }

            return(null);
        }
        /// <summary>
        /// Sets the server parameters and regenerates the salted password if 
        /// the salt values have changed.
        /// </summary>
        /// <param name="hashMethod">the hashing method</param>
        /// <param name="salt">the salt for the user credentials.</param>
        /// <param name="iterations">the number of iterations.</param>
        void SetServerValues(HashMethod hashMethod, byte[] salt, int iterations)
        {
            bool hasPasswordDataChanged = false;
            bool hasHashMethodChanged = false;

            if (m_salt == null || !salt.SecureEquals(m_salt))
            {
                hasPasswordDataChanged = true;
                m_salt = salt;
            }
            if (iterations != m_iterations)
            {
                hasPasswordDataChanged = true;
                m_iterations = iterations;
            }
            if (m_hashMethod != hashMethod)
            {
                m_hashMethod = hashMethod;
                hasHashMethodChanged = true;
            }

            if (hasPasswordDataChanged)
            {
                m_saltedPassword = Scram.GenerateSaltedPassword(m_passwordBytes, m_salt, m_iterations);
            }
            if (hasPasswordDataChanged || hasHashMethodChanged)
            {
                m_serverKey = Scram.ComputeServerKey(m_hashMethod, m_saltedPassword);
                m_clientKey = Scram.ComputeClientKey(m_hashMethod, m_saltedPassword);
                m_storedKey = Scram.ComputeStoredKey(m_hashMethod, m_clientKey);
                m_clientSignature = new HMac(Scram.CreateDigest(m_hashMethod));
                m_clientSignature.Init(new KeyParameter(m_storedKey));

                m_serverSignature = new HMac(Scram.CreateDigest(m_hashMethod));
                m_serverSignature.Init(new KeyParameter(m_serverKey));
            }
        }
 internal static byte[] ComputeServerKey(HashMethod hashMethod, byte[] saltedPassword)
 {
     return ComputeHMAC(hashMethod, saltedPassword, StringServerKey);
 }
 internal static byte[] ComputeStoredKey(HashMethod hashMethod, byte[] clientKey)
 {
     return Hash.Compute(CreateDigest(hashMethod), clientKey);
 }
 internal static byte[] ComputeHMAC(HashMethod hashMethod, byte[] key, byte[] message)
 {
     return HMAC.Compute(CreateDigest(hashMethod), key, message);
 }