Esempio n. 1
0
 public void Clear()
 {
     byte[] inputABC = Encoding.Default.GetBytes("abc");
     hash.ComputeHash(inputABC);
     hash.Clear();
     // cannot use a disposed object
     hash.ComputeHash(inputABC);
 }
Esempio n. 2
0
        public bool Verify(Stream input, byte[] hash)
        {
            bool same = true;

            hashAlgorithm.Initialize();

            int len;

            while ((len = input.Read(buffer1, 0, BufferSize)) > 0)
            {
                hashAlgorithm.TransformBlock(buffer1, 0, len, buffer1, 0);
            }

            hashAlgorithm.TransformFinalBlock(new byte[0], 0, 0);

            if (hash.Length != hashAlgorithm.Hash.Length)
            {
            }
            else
            {
                for (int i = 0; i < hash.Length; i++)
                {
                    if (hash [i] != hashAlgorithm.Hash [i])
                    {
                        same = false;
                        logger.Warn("Different hash");
                        break;
                    }
                }
            }
            hashAlgorithm.Clear();

            return(same);
        }
Esempio n. 3
0
        byte[] Crypt(byte[] key, byte[] salt, int rounds, HashAlgorithm A)
        {
            byte[] H = null;

            try
            {
                A.Initialize();
                AddToDigest(A, salt);
                AddToDigest(A, key);
                FinishDigest(A);

                H = (byte[])A.Hash.Clone();

                for (int i = 0; i < (1 << rounds); i++)
                {
                    A.Initialize();
                    AddToDigest(A, H);
                    AddToDigest(A, key);
                    FinishDigest(A);

                    Array.Copy(A.Hash, H, H.Length);
                }

                return((byte[])H.Clone());
            }
            finally
            {
                A.Clear();
                Security.Clear(H);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// 加密字符串,并以base64的编码方式输出
        /// </summary>
        //public string HashString(string Value)
        //{

        //    if (m_IsAddSalt)
        //    {
        //        if (m_SaltValue.Length == 0)
        //            m_SaltValue = this.CreateSalt();
        //    }
        //    else
        //    {
        //        m_SaltValue = string.Empty;
        //    }
        //    // 将原始字符串转换成字节数组
        //    byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(Value + m_SaltValue);

        //    // 计算散列,并返回一个字节数组
        //    byte[] bytHash = mhash.ComputeHash(bytValue);

        //    mhash.Clear();

        //    // 返回散列值
        //    return Convert.ToBase64String(bytHash);
        //}
        public string HashString(string Value)
        {
            if (m_IsAddSalt)
            {
                if (m_SaltValue.Length == 0)
                {
                    m_SaltValue = this.CreateSalt();
                }
            }
            else
            {
                m_SaltValue = string.Empty;
            }
            // 将原始字符串转换成字节数组
            byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(Value + m_SaltValue);

            // 计算散列,并返回一个字节数组
            byte[] bytHash = mhash.ComputeHash(bytValue);

            mhash.Clear();
            var sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data
            // and format each one as a hexadecimal string.
            for (var i = 0; i < bytHash.Length; i++)
            {
                sBuilder.AppendFormat("{0:x2}", bytHash[i]);
            }

            // Return the hexadecimal string.
            return(sBuilder.ToString());
        }
Esempio n. 5
0
        /// <summary>
        /// Gets the hash of a <see cref="SecureString" />
        /// </summary>
        /// <param name="source">The <see cref="SecureString" /> to get the hash of</param>
        /// <param name="saltString">The salt used for secure strings</param>
        /// <param name="algorithm">The algorithm used, default <see cref="SHA256Managed" /></param>
        /// <param name="encoding">The encoding used in the secured string and salt, default <see cref="Encoding.UTF8" /></param>
        /// <returns>A Hash representation of the SecureString</returns>
        public static string CalculateHash(this SecureString source, string saltString = null, HashAlgorithm algorithm = null, Encoding encoding = null)
        {
            encoding = encoding ?? Encoding.UTF8;
            IntPtr unmanagedString = IntPtr.Zero;

            try
            {
                unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(source);
                byte[] allBytes;
                byte[] passwordBytes = encoding.GetBytes(Marshal.PtrToStringUni(unmanagedString));
                if (!string.IsNullOrWhiteSpace(saltString))
                {
                    byte[] saltBytes             = encoding.GetBytes(saltString);
                    byte[] passwordPlusSaltBytes = new byte[passwordBytes.Length + saltBytes.Length];
                    Buffer.BlockCopy(passwordBytes, 0, passwordPlusSaltBytes, 0, passwordBytes.Length);
                    Buffer.BlockCopy(saltBytes, 0, passwordPlusSaltBytes, passwordBytes.Length, saltBytes.Length);
                    allBytes = passwordPlusSaltBytes;
                }
                else
                {
                    allBytes = passwordBytes;
                }
                algorithm = algorithm ?? new SHA256Managed();
                return(Convert.ToBase64String(algorithm.ComputeHash(allBytes)));
            }
            finally
            {
                if (unmanagedString != IntPtr.Zero)
                {
                    Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
                }
                // dispose of the algorithm
                algorithm?.Clear();
            }
        }
Esempio n. 6
0
        /// <summary>バイト配列のハッシュ値を計算して返す。</summary>
        /// <param name="asb">バイト配列</param>
        /// <param name="eha">ハッシュ・アルゴリズム列挙型</param>
        /// <param name="stretchCount">ストレッチ回数</param>
        /// <returns>ハッシュ値(バイト配列)</returns>
        public static byte[] GetHashBytes(byte[] asb, EnumHashAlgorithm eha, int stretchCount)
        {
            byte[] temp = null;

#if NETSTD
            // NETSTDの場合の実装
            if (eha == EnumHashAlgorithm.RIPEMD160_M)
            {
                // ハッシュ値を計算して返す。
                temp = GetHash.GetDigestBytesByBC(asb, new RipeMD160Digest());

                for (int i = 0; i < stretchCount; i++)
                {
                    // stretchCountが1以上なら繰り返す。
                    temp = GetHash.GetDigestBytesByBC(temp, new RipeMD160Digest());
                }

                return(temp);
            }
#endif
            // ハッシュ(キー無し)サービスプロバイダを生成
            HashAlgorithm ha = HashAlgorithmCmnFunc.CreateHashAlgorithmSP(eha);

            // ハッシュ値を計算して返す。
            temp = ha.ComputeHash(asb);

            for (int i = 0; i < stretchCount; i++)
            {
                // stretchCountが1以上なら繰り返す。
                temp = ha.ComputeHash(temp);
            }

            ha.Clear(); // devps(1725)
            return(temp);
        }
Esempio n. 7
0
 public void Dispose()
 {
     if (algo != null)
     {
         algo.Clear();
     }
 }
Esempio n. 8
0
 public static byte[] HashStream(HashAlgorithm hashAlgorithm_0, Stream stream_0)
 {
     byte[] result = hashAlgorithm_0.ComputeHash(stream_0);
     hashAlgorithm_0.Clear();
     stream_0.Close();
     return(result);
 }
Esempio n. 9
0
 // https://www.geekytidbits.com/one-way-hashing/
 public static string HashText(string text, string salt, HashAlgorithm hasher)
 {
     byte[] textWithSaltBytes = Encoding.UTF8.GetBytes(string.Concat(text, salt));
     byte[] hashedBytes       = hasher.ComputeHash(textWithSaltBytes);
     hasher.Clear();
     return(Convert.ToBase64String(hashedBytes));
 }
        public void CalculateHashTest()
        {
            string        rawSource       = "this is some sensitive text";
            SecureString  source          = rawSource.ToSecureString();
            Encoding      encoding        = Encoding.UTF8;
            IntPtr        unmanagedString = IntPtr.Zero;
            HashAlgorithm algorithm       = null;
            string        saltString      = "this is some salty salt";
            string        result;

            try
            {
                unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(source);
                byte[] passwordBytes         = encoding.GetBytes(Marshal.PtrToStringUni(unmanagedString));
                byte[] saltBytes             = encoding.GetBytes(saltString);
                byte[] passwordPlusSaltBytes = new byte[passwordBytes.Length + saltBytes.Length];
                Buffer.BlockCopy(passwordBytes, 0, passwordPlusSaltBytes, 0, passwordBytes.Length);
                Buffer.BlockCopy(saltBytes, 0, passwordPlusSaltBytes, passwordBytes.Length, saltBytes.Length);
                algorithm = algorithm ?? new SHA256Managed();
                result    = Convert.ToBase64String(algorithm.ComputeHash(passwordPlusSaltBytes));
            }
            finally
            {
                if (unmanagedString != IntPtr.Zero)
                {
                    Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
                }
                // dispose of the algorithm
                algorithm?.Clear();
            }

            Assert.Equal(result, source.CalculateHash(saltString));
            Assert.NotEqual(result, source.CalculateHash());
        }
Esempio n. 11
0
 /// <summary> Mechanisms inherit from the HashAlgorithm base class so we can use that to cast the crypto service provider
 /// </summary>
 /// <param name="provider">Type of provider</param>
 /// <param name="plainText">To be hash content</param>
 /// <returns>Array of bytes</returns>
 private byte[] ComputeHash(HashAlgorithm provider, string plainText)
 {
     //All hashing mechanisms inherit from the HashAlgorithm base class so we can use that to cast the crypto service provider
     byte[] hash = provider.ComputeHash(System.Text.Encoding.UTF8.GetBytes(plainText));
     provider.Clear();
     return(hash);
 }
Esempio n. 12
0
        static string SaltedCrypt(HashAlgorithm algorithm, byte[] password, byte[] salt)
        {
            // If we're under the hash length, assume we only have the salt.
            int hashLength = algorithm.HashSize / 8;
            int saltOffset = salt.Length < hashLength ? 0 : hashLength;
            int saltLength = salt.Length - saltOffset;

            byte[] saltedHash = new byte[hashLength + saltLength];
            try
            {
                algorithm.Initialize();
                algorithm.TransformBlock(password, 0, password.Length, password, 0);
                algorithm.TransformBlock(salt, saltOffset, saltLength, salt, saltOffset);
                algorithm.TransformFinalBlock(new byte[0], 0, 0);

                Array.Copy(algorithm.Hash, saltedHash, hashLength);
                Array.Copy(salt, saltOffset, saltedHash, hashLength, saltLength);
                string crypt = Convert.ToBase64String(saltedHash);
                return(crypt);
            }
            finally
            {
                algorithm.Clear();
                Security.Clear(saltedHash);
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Hash file with specific hash algorithm (for large file).
        /// </summary>
        /// <param name="path"></param>
        /// <param name="hash"></param>
        /// <returns></returns>
        public static string HashLarge(string path, HashAlgorithm hash)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException("File path can't be null.");
            }

            if (!File.Exists(path))
            {
                throw new ArgumentException("File doesn't exist: " + path);
            }

            int bufferSize = 1024 * 16;

            byte[] buffer = new byte[bufferSize];

            Stream inputStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            int    readLength  = 0;
            var    output      = new byte[bufferSize];

            while ((readLength = inputStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                hash.TransformBlock(buffer, 0, readLength, output, 0);
            }

            hash.TransformFinalBlock(buffer, 0, 0);
            string md5 = BitConverter.ToString(hash.Hash);

            hash.Clear();
            inputStream.Close();
            md5 = md5.Replace("-", "");

            return(md5);
        }
        /// <summary>
        /// Calculates the hash of a string.
        /// </summary>
        /// <param name="data">The data to hash.</param>
        /// <param name="offset">The offset.</param>
        /// <param name="count">The count.</param>
        /// <param name="hashAlgorithm">The hash algorithm.</param>
        /// <returns>
        /// Calculated hash
        /// </returns>
        private static byte[] CalculateHash(this byte[] data, int offset, int count, HashAlgorithm hashAlgorithm)
        {
            byte[] hashRaw = hashAlgorithm.ComputeHash(data, offset, count);
            hashAlgorithm.Clear();

            return(hashRaw);
        }
Esempio n. 15
0
        /// <summary>
        /// 在函数里面会释放 calculator
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="calculator"></param>
        /// <returns></returns>
        public static String ComputeHashCode(String fileName, HashAlgorithm calculator)
        {
            String hashCode = String.Empty;

            //检查文件是否存在,如果文件存在则进行计算,否则返回空值
            if (File.Exists(fileName) && calculator != null)
            {
                using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    //计算文件的HASH值
                    using (calculator)
                    {
                        Byte[] buffer = calculator.ComputeHash(fs);
                        calculator.Clear();
                        //将字节数组转换成十六进制的字符串形式
                        StringBuilder stringBuilder = new StringBuilder(40);
                        for (int i = 0; i < buffer.Length; i++)
                        {
                            stringBuilder.Append(buffer[i].ToString("x2"));
                        }
                        hashCode = stringBuilder.ToString();
                    }
                } //关闭文件流
            }     //结束计算
            return(hashCode);
        }
Esempio n. 16
0
        internal override void EndPacket()
        {
            CloseStream();

            // Set Name
            string fileName = mFileName;

            mFileName = null;
            if (fileName != null)
            {
                try
                {
                    mEntity.MoveTo(Path.Combine(mEntity.DirectoryName, fileName));
                }
                catch (Exception) { }
            }

            // Hash
            HashAlgorithm hash = mHashAlgorithm;

            mHashAlgorithm = null;
            if (hash != null)
            {
                hash.TransformFinalBlock(new byte[0], 0, 0);
                SetHash(BitConverter.ToString(hash.Hash).Replace("-", ""));
                hash.Clear();
                hash.Dispose();
            }
        }
Esempio n. 17
0
        public static string GetFileChecksum(string fileName, ChecksumType checksumType)
        {
            HashAlgorithm hasher = null;
            string        hash   = String.Empty;

            try
            {
                switch (checksumType)
                {
                case ChecksumType.MD5:
                    hasher = MD5.Create();
                    break;

                case ChecksumType.SHA1:
                    hasher = SHA1.Create();
                    break;

                case ChecksumType.SHA256:
                    hasher = SHA256.Create();
                    break;

                case ChecksumType.SHA512:
                    hasher = SHA512.Create();
                    break;
                }

                try
                {
                    // compute hash from file
                    using (StreamReader fileReader = new StreamReader(fileName))
                    {
                        hash = ByteHashToString(hasher.ComputeHash(fileReader.BaseStream));
                    }
                }
                catch (IOException)
                {
                    // try again with long path
                    using (StreamReader fileReader = new StreamReader(@"\\?\" + fileName))
                    {
                        hash = ByteHashToString(hasher.ComputeHash(fileReader.BaseStream));
                    }
                }
            }
            catch (Exception)
            {
                hash = String.Empty;
            }

            if (hasher != null)
            {
                // Clear() "Releases all resources used by the HashAlgorithm class"
                hasher.Clear();

                // NOTE: HashAlgorithm.Dispose is private, so let's cast to IDisposable anyways and it'll work
                ((IDisposable)hasher).Dispose();
            }

            return(hash);
        }
Esempio n. 18
0
        private void ComputeHash(TextBox _txtBox, HashAlgorithm _ha, byte[] _aby)
        {
            byte[] aby = _ha.ComputeHash(_aby);
            _ha.Clear();
            _ha = null;

            _txtBox.Text = ByteArrayToString(aby);
        }
Esempio n. 19
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         _hashAlgorithm.Clear();
         _hashAlgorithm.Dispose();
     }
 }
Esempio n. 20
0
        private byte[] GetHash(string inputString)
        {
            HashAlgorithm algorithm = SHA256.Create();
            var           hashedpw  = algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString));

            algorithm.Dispose(); algorithm.Clear();
            return(hashedpw);
        }
Esempio n. 21
0
 public void Release()
 {
     IsReleased = true;
     //_hashAlgorithm.Clear();
     //_symmetricAlgorithm.Clear();
     _hashAlgorithm.Clear();
     _symmetricAlgorithm.Dispose();
 }
Esempio n. 22
0
 private string GetHashCode(System.IO.Stream stream, HashAlgorithm algorithm)
 {
     try
     {
         byte[] byteResult = algorithm.ComputeHash(stream);
         algorithm.Clear();
         string result = this.CleanUpShaCode(byteResult);
         return(result);
     }
     finally
     {
         if (algorithm != null)
         {
             algorithm.Clear();
         }
     }
 }
Esempio n. 23
0
 /// <summary>
 /// Освобождение ресурсов
 /// </summary>
 public void Dispose()
 {
     if (_algorithm != null)
     {
         _algorithm.Clear();
         _algorithm = null;
     }
 }
Esempio n. 24
0
 // prints the hash of a specified input to the console
 public static void PrintHash(string name, HashAlgorithm algo, byte[] data)
 {
     // compute the hash of the input data..
     byte[] hash = algo.ComputeHash(data);
     // ..and write the hash to the console
     Console.WriteLine(name + BytesToHex(hash));
     // dispose of the hash algorithm; we do not need to hash more data with it
     algo.Clear();
 }
Esempio n. 25
0
        internal static void Dispose(this HashAlgorithm algorithm)
        {
            if (algorithm == null)
            {
                throw new NullReferenceException();
            }

            algorithm.Clear();
        }
Esempio n. 26
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing && (m_algorithm != null))
     {
         m_algorithm.Clear();
         m_algorithm     = null;
         m_AlgorithmType = HashAlgorithmType.Unknown;
     }
 }
Esempio n. 27
0
 private IHashed ComputeHash(byte[] data)
 {
     using (HashAlgorithm hash = SHA512.Create())
     {
         var result = hash.ComputeHash(data);
         hash.Clear();
         return(new GenericHash(result));
     }
 }
Esempio n. 28
0
 // prints the hash of a specified input to the console
 public static void PrintHash(string name, HashAlgorithm algo, byte[] data)
 {
     // compute the hash of the input data..
     byte[] hash = algo.ComputeHash(data);
     // ..and write the hash to the console
     Console.WriteLine(name + BytesToHex(hash));
     // dispose of the hash algorithm; we do not need to hash more data with it
     algo.Clear();
 }
Esempio n. 29
0
        protected virtual string GetPasswordHash(string username, string password)
        {
            hash.Clear();
            var numUser   = Encoding.UTF8.GetBytes(username, 0, username.Length, buffer, 0);
            var numPass   = Encoding.UTF8.GetBytes(password, 0, password.Length, buffer, numUser);
            var hashBytes = hash.ComputeHash(buffer, 0, numUser + numPass);

            return(Convert.ToBase64String(hashBytes));
        }
Esempio n. 30
0
        /// <summary>バイト配列のハッシュ値を計算して返す。</summary>
        /// <param name="asb">バイト配列</param>
        /// <param name="eha">ハッシュ・アルゴリズム列挙型</param>
        /// <returns>ハッシュ値(バイト配列)</returns>
        public static byte[] GetHashBytes(byte[] asb, EnumHashAlgorithm eha)
        {
            // ハッシュ(キー無し)サービスプロバイダを生成
            HashAlgorithm ha = GetHash.CreateHashAlgorithmServiceProvider(eha);

            // ハッシュ値を計算して返す。
            byte[] temp = ha.ComputeHash(asb);
            ha.Clear(); // devps(1725)
            return(temp);
        }
Esempio n. 31
0
        private static string ComputeHash(byte[] pwd, HashAlgorithm hash)
        {
            byte[] output = hash.ComputeHash(pwd);

            hash.Clear();

            var result = BitConverter.ToString(output);

            return(result);
        }
Esempio n. 32
0
	public static bool ExerciseHash(HashAlgorithm hash, int size)
	{
		// Exercise the properties
		//
		if (hash.CanReuseTransform != true)
		{
			Console.WriteLine("CanReuseTransform != true");
			return false;
		}

		if (hash.CanTransformMultipleBlocks != true)
		{
			Console.WriteLine("CanTransformMultipleBlocks != true");
			return false;
		}

		if (hash.HashSize != size)
		{
			Console.WriteLine("HashSize, expected={0} actual={1}", size, hash.HashSize);
			return false;
		}

		if (hash.InputBlockSize != 1)
		{
			Console.WriteLine("InputBlockSize != 1");
			return false;
		}

		if (hash.OutputBlockSize != 1)
		{
			Console.WriteLine("OutputBlockSize != 1");
			return false;
		}

		// Exercise the Initialize method.  Test proper behavior both when it is and is not called.
		//
		byte[] bytesHalf1 = {0x00, 0x01, 0x02, 0x03};
		byte[] bytesHalf2 = {0xfc, 0xfd, 0xfe, 0xff};
		byte[] bytesFull  = {0x00, 0x01, 0x02, 0x03, 0xfc, 0xfd, 0xfe, 0xff};
		byte[] bytesExpected;
		byte[] bytesActual;

		// Initialize is called between partial hashes
		//
		hash.Initialize();
		bytesExpected = hash.ComputeHash(bytesHalf1);
		
		hash.Initialize();
		hash.TransformBlock(bytesHalf2, 0, bytesHalf2.Length, bytesHalf2, 0);
		hash.Initialize();
		hash.TransformFinalBlock(bytesHalf1, 0, bytesHalf1.Length);
		bytesActual = hash.Hash;

		if (!CompareBytes(bytesExpected, bytesActual))
		{
			Console.WriteLine("\nInitialize test failed");
			return false;
		}

		// Initialize is not called between partial hashes
		//
		hash.Initialize();
		bytesExpected = hash.ComputeHash(bytesFull);

		hash.Initialize();
		hash.TransformBlock(bytesHalf1, 0, bytesHalf1.Length, bytesHalf1, 0);
		hash.TransformFinalBlock(bytesHalf2, 0, bytesHalf2.Length);
		bytesActual = hash.Hash;
		
		if (!CompareBytes(bytesExpected, bytesActual))
		{
			Console.WriteLine("\nNo Initialize test failed");
			return false;
		}

		// Exercise the Clear method -- ensure object disposed
		//
		hash.Initialize();
		hash.Clear();

		try
		{
			hash.ComputeHash(bytesFull);
			Console.WriteLine("Clear test failed -- no exception thrown");
			return false;
		}
		catch (ObjectDisposedException)
		{
		}
		
		return true;
	}