Beispiel #1
0
 public byte[] ComputeHash(byte[] buffer)
 {
     lock (locker)
     {
         return(_algorithm.ComputeHash(buffer));
     }
 }
 private void CheckCopy(string destination, string source, FileSystemEventArgs e = null)
 {
     if (File.Exists(destination)) //Checks is file exists
     {
         System.Security.Cryptography.HashAlgorithm ha = System.Security.Cryptography.HashAlgorithm.Create();
         using (FileStream f1 = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.ReadWrite),
                f2 = new FileStream(destination, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
         {
             /* Calculate Hash */
             byte[] hash1 = ha.ComputeHash(f1);
             byte[] hash2 = ha.ComputeHash(f2);
             //Compare files and copy if destination does not match server
             if (BitConverter.ToString(hash1) != BitConverter.ToString(hash2))
             {
                 log.Info("New Database version detected in ", sourceDBpath);
                 log.Debug("Copy [{0}] To [{1}]", source, destination);
                 File.Copy(source, destination, true);
                 OnDataBaseUpdate(e);
             }
             else
             {
                 log.Debug("Remote DB matches current copy");
             }
         }
     }
     else //copies if no destination file/
     {
         log.Warn("Database missing: {0} ", destination);
         log.Debug("Copy [{0}] To [{1}]", source, destination);
         File.Copy(source, destination, true);
     }
 }
Beispiel #3
0
 /// <summary>
 /// 判断文件内容是否相同
 /// 哈市
 /// </summary>
 /// <param name="filePath1"></param>
 /// <param name="filePath2"></param>
 /// <returns></returns>
 public static bool isValidFileContent(string filePath1, string filePath2)
 {
     //创建一个哈希算法对象
     using (System.Security.Cryptography.HashAlgorithm hash = System.Security.Cryptography.HashAlgorithm.Create())
     {
         using (FileStream file1 = new FileStream(filePath1, FileMode.Open), file2 = new FileStream(filePath2, FileMode.Open))
         {
             byte[] hashByte1 = hash.ComputeHash(file1);          //哈希算法根据文本得到哈希码的字节数组
             byte[] hashByte2 = hash.ComputeHash(file2);
             string str1      = BitConverter.ToString(hashByte1); //将字节数组装换为字符串
             string str2      = BitConverter.ToString(hashByte2);
             return(str1 == str2);                                //比较哈希码
         }
     }
 }
Beispiel #4
0
        /// <summary>
        /// 获取文件Hash值,如果文件正在使用中,则会报错
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="NullValue"></param>
        /// <returns></returns>
        public static string GetFileHash(string fileName, string NullValue)
        {
            string result = NullValue;

            if (System.IO.File.Exists(fileName))
            {
                lock (lockObject)
                {
                    try
                    {
                        using (System.Security.Cryptography.HashAlgorithm ah = System.Security.Cryptography.HashAlgorithm.Create())
                        {
                            using (FileStream fs = new FileStream(fileName, FileMode.Open))
                            {
                                result = All.Class.Num.Hex2Str(ah.ComputeHash(fs));
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        All.Class.Error.Add(e);
                    }
                }
            }
            return(result);
        }
 byte[] CalculateHash(String filePath, System.Security.Cryptography.HashAlgorithm hashAlgorithm)
 {
     using (FileStream stream = File.OpenRead(filePath))
     {
         return(hashAlgorithm.ComputeHash(stream));
     }
 }
Beispiel #6
0
		/// <summary>
		/// Computes the MD5 hash value for the specified byte array.
		/// </summary>
		/// <param name="bytes">The input to compute the hash code for.</param>
		/// <returns>The computed hash code as GUID.</returns>
		/// <remarks>
		/// One instance of the MD5 Crypto Service Provider
		/// can't operate properly with multiple simultaneous threads.
		/// Use lock to solve this problem.
		/// </remarks>
		public Guid ComputeMd5Hash(byte[] bytes)
		{
			byte[] hash;
			lock (HashProviderLock)
				hash = HashProvider.ComputeHash(bytes);
			return new Guid(hash);
		}
Beispiel #7
0
        // TODO: should this function follow the, apparent, dodSON.Core pattern of putting functions like this into ...Helper classes?

        /// <summary>
        /// Generates the Password Salt Result Hash.
        /// </summary>
        /// <param name="hashAlgorithm">The required <see cref="System.Security.Cryptography.HashAlgorithm"/>.</param>
        /// <param name="password">The password.</param>
        /// <param name="salt">The salt.</param>
        /// <returns>The generated Password Salt Result Hash.</returns>
        public static byte[] ComputeResult(System.Security.Cryptography.HashAlgorithm hashAlgorithm,
                                           System.Security.SecureString password,
                                           byte[] salt)
        {
            // merge salt and password
            byte[] saltedPassword = new byte[salt.Length + password.Length];
            byte[] passwordArray  = null;
            try
            {
                // add the salt
                for (int i = 0; i < salt.Length; i++)
                {
                    saltedPassword[i] = salt[i];
                }
                // extract the password
                passwordArray = CryptographyHelper.SecureStringToByteArray(password);
                // add the password
                for (int i = 0; i < passwordArray.Length; i++)
                {
                    saltedPassword[salt.Length + i] = passwordArray[i];
                }
                // return result hash
                return(hashAlgorithm.ComputeHash(saltedPassword));
            }
            finally
            {
                // clean up
                Array.Clear(saltedPassword, 0, saltedPassword.Length);
                Array.Clear(passwordArray, 0, passwordArray.Length);
            }
        }
Beispiel #8
0
        byte[] BuildAuthenticationData()
        {
            Contract.Ensures(Contract.Result <byte[]>() != null ||
                             mFooter.Authentication == BlobTransportStreamAuthentication.None);
            Contract.Assert(mFooterPosition.IsNotNone());

            System.Security.Cryptography.HashAlgorithm hash_algo = null;
            switch (mFooter.Authentication)
            {
            case BlobTransportStreamAuthentication.None: break;

            // #TODO_IMPLEMENT:
            case BlobTransportStreamAuthentication.Crc: throw new NotImplementedException();

            case BlobTransportStreamAuthentication.Hash: throw new NotImplementedException();

            case BlobTransportStreamAuthentication.Rsa: throw new NotImplementedException();
            }

            if (hash_algo != null)
            {
                return(hash_algo.ComputeHash(BaseStream, StartPosition, mFooterPosition));
            }

            return(null);
        }
Beispiel #9
0
        public byte[] GetAssemblyHash()
        {
            System.Security.Cryptography.HashAlgorithm HA = System.Security.Cryptography.SHA256.Create();

            try
            {
                byte[] b;
                using (System.IO.FileStream fs = new System.IO.FileStream(GetAssemblyPath(), System.IO.FileMode.Open, System.IO.FileAccess.Read))
                    b = HA.ComputeHash(fs);
                return(b);
            }
            catch
            {
                return(null);
                //Random r = new Random();
                //int keyLen = 128;
                //byte[] b = new byte[keyLen];
                //r.NextBytes(b);
                //return b;
            }
            finally
            {
                HA.Dispose();
            }
        }
Beispiel #10
0
        private static string MD5(string password)
        {
            //byte[] textBytes = Encoding.UTF8.GetBytes(password);
            //try
            //{
            //    System.Security.Cryptography.MD5CryptoServiceProvider cryptHandler;
            //    cryptHandler = new System.Security.Cryptography.MD5CryptoServiceProvider();
            //    byte[] hash = cryptHandler.ComputeHash(textBytes);
            //    string ret = "";
            //    foreach (byte a in hash)
            //    {
            //        ret += a.ToString("x2");
            //    }
            //    return ret;
            //}
            //catch
            //{
            //    throw;
            //}
            try
            {
                System.Security.Cryptography.HashAlgorithm hash = System.Security.Cryptography.MD5.Create();
                byte[] hash_out = hash.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));

                var md5_str = BitConverter.ToString(hash_out).Replace("-", "");
                return(md5_str.ToLower());
            }
            catch
            {
                throw;
            }
        }
Beispiel #11
0
        public static byte[] ComputeHash(System.Security.Cryptography.HashAlgorithm algorithm, byte[] inputBytes)
        {
            // calculate hash from inputBytes using provided algorithm
            byte[] hash = algorithm.ComputeHash(inputBytes);

            return(hash);
        }
Beispiel #12
0
 public string GetHash(string m_strSource)
 {
     System.Security.Cryptography.HashAlgorithm hashAlgorithm = System.Security.Cryptography.HashAlgorithm.Create("MD5");
     byte[] bytes   = System.Text.Encoding.UTF8.GetBytes(m_strSource);
     byte[] inArray = hashAlgorithm.ComputeHash(bytes);
     return(System.Convert.ToBase64String(inArray));
 }
Beispiel #13
0
        /// <summary>
        /// 获取指定文件的版本
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string GetFileCode(string fileName, string NullValue)
        {
            string result = NullValue;

            if (System.IO.File.Exists(fileName))
            {
                lock (lockObject)
                {
                    if (fileName.ToUpper().IndexOf(".exe".ToUpper()) > 0 || fileName.ToUpper().IndexOf(".dll".ToUpper()) > 0)
                    {
                        System.Diagnostics.FileVersionInfo fi = System.Diagnostics.FileVersionInfo.GetVersionInfo(fileName);
                        result = fi.FileVersion;
                    }
                    else
                    {
                        using (System.Security.Cryptography.HashAlgorithm ah = System.Security.Cryptography.HashAlgorithm.Create())
                        {
                            using (FileStream fs = new FileStream(fileName, FileMode.Open))
                            {
                                result = All.Class.Num.Hex2Str(ah.ComputeHash(fs));
                            }
                        }
                    }
                }
            }
            return(result);
        }
 /// <summary>Generates the hash chain up to the specified iteration.</summary>
 /// <param name="iteration">The maximum interation to calculate.</param>
 protected void CalculateTo(int iteration)
 {
     while (cache.Count < iteration)
     {
         cache.Add(hashAlgorithm.ComputeHash(cache[cache.Count - 1]));
     }
 }
        private void InitializeKey(byte[] key)
        {
            if (key.Length > BlockSizeValue)
            {
                KeyValue = _hash1.ComputeHash(key);
            }
            else
            {
                KeyValue = (byte[])key.Clone();
            }

            _inner = new byte[BlockSizeValue];
            _outer = new byte[BlockSizeValue];

            for (int i = 0; i < BlockSizeValue; i++)
            {
                _inner[i] = 0x36;
                _outer[i] = 0x5C;
            }

            for (int i = 0; i < KeyValue.Length; i++)
            {
                _inner[i] ^= KeyValue[i];
                _outer[i] ^= KeyValue[i];
            }
        }
Beispiel #16
0
        public override System.String GetLockID()
        {
            EnsureOpen();
            System.String dirName;             // name to be hashed
            try
            {
                dirName = directory.FullName;
            }
            catch (System.IO.IOException e)
            {
                throw new System.SystemException(e.ToString(), e);
            }

            byte[] digest;
            lock (DIGESTER)
            {
                digest = DIGESTER.ComputeHash(System.Text.Encoding.UTF8.GetBytes(dirName));
            }
            System.Text.StringBuilder buf = new System.Text.StringBuilder();
            buf.Append("lucene-");
            for (int i = 0; i < digest.Length; i++)
            {
                int b = digest[i];
                buf.Append(HEX_DIGITS[(b >> 4) & 0xf]);
                buf.Append(HEX_DIGITS[b & 0xf]);
            }

            return(buf.ToString());
        }
        /// <summary>
        /// Determine an unique identifier that specify the linked shader program.
        /// </summary>
        /// <param name="cctx">
        /// A <see cref="ShaderCompilerContext"/> determining the compiler parameteres.
        /// </param>
        /// <param name="libraryId">
        /// A <see cref="String"/> that identifies the shader object in library.
        /// </param>
        /// <returns>
        /// It returns a string that identify the a shader program classified with <paramref name="libraryId"/> by
        /// specifying <paramref name="cctx"/> as compiled parameters.
        /// </returns>
        internal static string ComputeLibraryHash(ShaderCompilerContext cctx, string libraryId)
        {
            StringBuilder hashMessage = new StringBuilder();

            // Take into account the shader program name
            hashMessage.Append(libraryId);
            // Take into account the shader version
            hashMessage.Append(cctx.ShaderVersion);

            // Do NOT take into account the shader program compilation symbols: they are considered
            // in attached shader objects.

            // Take into account the shader program include paths
            foreach (string includePath in cctx.Includes)
            {
                hashMessage.AppendFormat("{0}", includePath);
            }

            // Hash all information
            byte[] hashBytes;
            using (System.Security.Cryptography.HashAlgorithm hash = System.Security.Cryptography.HashAlgorithm.Create("SHA256")) {
                hashBytes = hash.ComputeHash(Encoding.ASCII.GetBytes(hashMessage.ToString()));
            }

            // ConvertItemType has to string
            return(Convert.ToBase64String(hashBytes));
        }
        public IndexerSetupResult Setup(IXDescriptor descriptor)
        {
            if (setup)
            {
                return(IndexerSetupResult.Failure);
            }

            hashFactory = new System.Security.Cryptography.SHA256Managed();

            string _v = Convert.ToBase64String(hashFactory.ComputeHash(System.Text.UTF8Encoding.UTF8.GetBytes(descriptor.ToString())));

            int df = indexSearcher.DocFreq(new Term(indexerDocumentDescriptorVersion, _v));

            // set up searcher
            TermDocs term = indexSearcher.IndexReader.TermDocs();

            List <Document> docs = new List <Document>();

            while (term.Next())
            {
                docs.Add(indexSearcher.Doc(term.Doc));
            }

            return(IndexerSetupResult.Okay);
        }
Beispiel #19
0
 public override byte[] encodeAsBuffer(byte[] data, int version)
 {
     if (!(data != null))
     {
         return(null);
     }
     System.Security.Cryptography.HashAlgorithm hashAlgorithm = null;
     if (capex.crypto.SHAEncoder.SHA1 == version)
     {
         hashAlgorithm = System.Security.Cryptography.SHA1.Create();
     }
     else if (capex.crypto.SHAEncoder.SHA256 == version)
     {
         hashAlgorithm = System.Security.Cryptography.SHA256.Create();
     }
     else if (capex.crypto.SHAEncoder.SHA384 == version)
     {
         hashAlgorithm = System.Security.Cryptography.SHA384.Create();
     }
     else if (capex.crypto.SHAEncoder.SHA512 == version)
     {
         hashAlgorithm = System.Security.Cryptography.SHA512.Create();
     }
     if (!(hashAlgorithm != null))
     {
         return(null);
     }
     return(hashAlgorithm.ComputeHash(data));
 }
Beispiel #20
0
        //These two functions used for calculating hash of Header object
        //GetFullHashBytes includes all fields in calculation, while GetSimpleHashBytes considers only two: Nonce and Datahash
        //This is done to decouple the key from the object and make it work separately
        //Otherwise including in the file data reference to its header would be impossible, leading to the infinite recursion.


        public static byte[] GetFullHashBytes(this HeaderModel header)
        {
            using (System.Security.Cryptography.HashAlgorithm sha256 = System.Security.Cryptography.SHA256.Create())
            {
                return(sha256.ComputeHash(Encoding.UTF8.GetBytes(header.Serialize())));
            }
        }
Beispiel #21
0
 public string MD5(string source)
 {
     System.Security.Cryptography.HashAlgorithm hashAlgorithm = System.Security.Cryptography.HashAlgorithm.Create("MD5");
     byte[] bytes = System.Text.Encoding.UTF8.GetBytes(source);
     byte[] value = hashAlgorithm.ComputeHash(bytes);
     return(System.BitConverter.ToString(value));
 }
 internal static ImmutableArray <byte> CalculateChecksum(byte[] buffer, int offset, int count, SourceHashAlgorithm algorithmId)
 {
     using (System.Security.Cryptography.HashAlgorithm algorithm = CryptographicHashProvider.TryGetAlgorithm(algorithmId))
     {
         Debug.Assert(algorithm != null);
         return(ImmutableArray.Create(algorithm.ComputeHash(buffer, offset, count)));
     }
 }
Beispiel #23
0
        public ulong HashImageData(System.Security.Cryptography.HashAlgorithm hashAlgorithm)
        {
            ulong metaHash = unchecked ((ulong)Width * 4551534108298448059ul + (ulong)Height * 7310107420406914801ul); // two random primes

            byte[] dataHashArr = hashAlgorithm.ComputeHash(_data);
            ulong  dataHash    = BitConverter.ToUInt64(dataHashArr, 0);

            return(dataHash ^ metaHash);
        }
        public void EnsureInputUnchangedTest(string name, Type expectedType)
        {
            System.Security.Cryptography.HashAlgorithm hasher = HashAlgorithm.Create(name);
            byte[] originalInput = (byte[])TestVectors.Battery.NumericRepeated.Clone();
            byte[] input         = (byte[])TestVectors.Battery.NumericRepeated.Clone();

            byte[] output = hasher.ComputeHash(input);
            CustomAssert.AreEqual(originalInput, input);
        }
Beispiel #25
0
        public BinaryHashData GetHash(System.Security.Cryptography.HashAlgorithm provider)
        {
            BinaryHashData result = new BinaryHashData();

            if (_data.Count > 0)
            {
                result._data.AddRange(provider.ComputeHash(_data.ToArray()));
            }
            return(result);
        }
Beispiel #26
0
 public static string encode_password(string password, string salt)
 {
     byte[] bytes = Encoding.Unicode.GetBytes(password);
     byte[] src   = Convert.FromBase64String(salt);
     byte[] dst   = new byte[src.Length + bytes.Length];
     Buffer.BlockCopy(src, 0, dst, 0, src.Length);
     Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
     System.Security.Cryptography.HashAlgorithm algorithm = System.Security.Cryptography.HashAlgorithm.Create("SHA1");
     byte[] inArray = algorithm.ComputeHash(dst);
     return(Convert.ToBase64String(inArray));
 }
Beispiel #27
0
 /// <summary>
 /// The compute hash.
 /// </summary>
 /// <param name="inputStream">
 /// The imput stream.
 /// </param>
 /// <returns>
 /// The <see cref="byte[]"/>.
 /// </returns>
 public byte[] ComputeHash(Stream inputStream)
 {
     try
     {
         return(hashAlgorithm != null?hashAlgorithm.ComputeHash(inputStream) : KeyContainer.ComputeHash(inputStream));
     }
     catch (Exception ex)
     {
         throw new Exception("Не удалось создать хэшер!!!!. " + ex.Message);
     }
 }
        public void ReusableTest(string name, Type expectedType)
        {
            System.Security.Cryptography.HashAlgorithm hashRepeater = HashAlgorithm.Create(name);
            System.Security.Cryptography.HashAlgorithm hashFresh    = null;

            for (int i = 0; i < TestVectors.Battery.All.Length - 1; i++)
            {
                hashFresh = HashAlgorithm.Create(name);
                CustomAssert.AreEqual(hashFresh.ComputeHash(TestVectors.Battery.All[i]), hashRepeater.ComputeHash(TestVectors.Battery.All[i]));
            }
        }
Beispiel #29
0
        private void WriteFile(Stream stream, string fileName)
        {
            string nzFileName = fileName + ".n!";

            using (FileStream streamWriter = File.Create(nzFileName))
            {
                stream.Seek(0, SeekOrigin.Begin);
                byte[] buffer = new byte[stream.Length];
                while (true)
                {
                    int r = stream.Read(buffer, 0, buffer.Length);
                    if (r > 0)
                    {
                        streamWriter.Write(buffer, 0, r);
                    }
                    else
                    {
                        break;
                    }
                }
            }

            System.Security.Cryptography.HashAlgorithm hash = System.Security.Cryptography.HashAlgorithm.Create();
                        
            FileStream stream1 = new FileStream(fileName, FileMode.Open);
            FileStream stream2 = new FileStream(nzFileName, FileMode.Open);

            byte[] hashbyte1 = hash.ComputeHash(stream1);
            byte[] hashbyte2 = hash.ComputeHash(stream2);
            stream1.Close();
            stream2.Close();

            if (BitConverter.ToString(hashbyte1) == BitConverter.ToString(hashbyte2))
            {
                File.Delete(nzFileName);
            }
            else
            {
                MessageBox.Show(string.Format("文件 '{0}' 与 {1} 存在差异,请在安装(更新)后手工合并。", fileName, nzFileName), "配置文件差异");
            }
        }
Beispiel #30
0
        public static byte[] GetSimpleHashBytes(this HeaderModel header)
        {
            HeaderModel simple = new HeaderModel()
            {
                Nonce = header.Nonce,
            };

            using (System.Security.Cryptography.HashAlgorithm sha256 = System.Security.Cryptography.SHA256.Create())
            {
                return(sha256.ComputeHash(Encoding.UTF8.GetBytes(simple.Serialize())));
            }
        }