コード例 #1
0
        /// <summary>
        /// Given a file path, compute the file hashes.
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="md5Hash"></param>
        /// <param name="sha1Hash"></param>
        /// <param name="sha256Hash"></param>
        public static void ComputeHashes(string filePath, out byte[] md5Hash, out byte[] sha1Hash, out byte[] sha256Hash)
        {
            using (var md5 = MD5Cng.Create())
                using (var sha1 = SHA1Cng.Create())
                    using (var sha256 = SHA256Cng.Create())
                        using (var input = File.OpenRead(filePath))
                        {
                            byte[] buffer = new byte[8192];
                            int    bytesRead;
                            while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                md5.TransformBlock(buffer, 0, bytesRead, buffer, 0);
                                sha1.TransformBlock(buffer, 0, bytesRead, buffer, 0);
                                sha256.TransformBlock(buffer, 0, bytesRead, buffer, 0);
                            }
                            // We have to call TransformFinalBlock, but we don't have any
                            // more data - just provide 0 bytes.
                            md5.TransformFinalBlock(buffer, 0, 0);
                            sha1.TransformFinalBlock(buffer, 0, 0);
                            sha256.TransformFinalBlock(buffer, 0, 0);

                            md5Hash    = md5.Hash;
                            sha1Hash   = sha1.Hash;
                            sha256Hash = sha256.Hash;
                        }
        }
コード例 #2
0
 public static string Hash(byte[] data)
 {
     using (var md5 = MD5Cng.Create())
     {
         return(BitConverter.ToString(md5.ComputeHash(data)).Replace("-", string.Empty));
     }
 }
コード例 #3
0
        //============================================================
        //	STATIC METHODS
        //============================================================
        #region GenerateHash(Stream stream, YahooMediaHashAlgorithm algorithm)
        /// <summary>
        /// Computes the hash value for the supplied <see cref="Stream"/> using the specified <see cref="YahooMediaHashAlgorithm"/>.
        /// </summary>
        /// <param name="stream">The input to compute the hash code for.</param>
        /// <param name="algorithm">A <see cref="YahooMediaHashAlgorithm"/> enumeration value that indicates the algorithm to use.</param>
        /// <returns>The <b>base64</b> encoded result of the computed hash code.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="stream"/> is a null reference (Nothing in Visual Basic).</exception>
        /// <exception cref="ArgumentException">The <paramref name="algorithm"/> is equal to <see cref="YahooMediaHashAlgorithm.None"/>.</exception>
        public static string GenerateHash(Stream stream, YahooMediaHashAlgorithm algorithm)
        {
            //------------------------------------------------------------
            //	Local members
            //------------------------------------------------------------
            string base64EncodedHash = String.Empty;
            MD5    md5  = MD5Cng.Create();
            SHA1   sha1 = SHA1Cng.Create();

            //------------------------------------------------------------
            //	Validate parameters
            //------------------------------------------------------------
            Guard.ArgumentNotNull(stream, "stream");
            if (algorithm == YahooMediaHashAlgorithm.None)
            {
                throw new ArgumentException(String.Format(null, "Unable to generate a hash value for the {0} algorithm.", algorithm), "algorithm");
            }

            if (algorithm == YahooMediaHashAlgorithm.MD5)
            {
                byte[] hash = md5.ComputeHash(stream);
                base64EncodedHash = Convert.ToBase64String(hash);
            }
            else if (algorithm == YahooMediaHashAlgorithm.Sha1)
            {
                byte[] hash = sha1.ComputeHash(stream);
                base64EncodedHash = Convert.ToBase64String(hash);
            }

            return(base64EncodedHash);
        }
コード例 #4
0
 /// <summary>
 /// CheckSum128 method implementation
 /// </summary>
 public static byte[] CheckSum128(byte[] value)
 {
     byte[] hash = null;
     using (MD5 md5 = MD5Cng.Create())
     {
         hash = md5.ComputeHash(value);
     }
     return(hash);
 }
コード例 #5
0
 public static string MD5Hash(string str)
 {
     using (var md5 = MD5Cng.Create())
     {
         var result    = md5.ComputeHash(Encoding.ASCII.GetBytes(str));
         var strResult = BitConverter.ToString(result);
         return(strResult.Replace("-", ""));
     }
 }
コード例 #6
0
        internal static string Compute(string str)
        {
            byte[] byteArr;
            string HashStr = "";

            byteArr = Encoding.ASCII.GetBytes(str);
            var md5Hash = MD5Cng.Create().ComputeHash(byteArr);

            HashStr = BitConverter.ToString(md5Hash).Replace("-", String.Empty).ToLower();
            return(HashStr);
        }
コード例 #7
0
        public string Compute(string input)
        {
            var bytes      = Encoding.UTF8.GetBytes(input);
            var secureGuid = String.Empty;

            using (var sha = MD5Cng.Create())
            {
                var hash = sha.ComputeHash(bytes);
                var guid = new Guid(hash);
                secureGuid = guid.ToString();
            }
            return(secureGuid);
        }
コード例 #8
0
ファイル: HashHelper.cs プロジェクト: lonelyong/NgNet
        /// <summary>
        /// 计算文件的 MD5 值
        /// </summary>
        /// <param name="path">要计算 MD5 值的文件名和路径</param>
        /// <returns>MD5 值16进制字符串</returns>
        public static string GetFileMD5(string path)
        {
            if (System.IO.File.Exists(path) == false)
            {
                return(string.Empty);
            }

            FileStream fs  = new FileStream(path, FileMode.Open, FileAccess.Read);
            MD5        md5 = MD5Cng.Create();

            byte[] hashByts = md5.ComputeHash(fs);
            return(ConvertHashBytes(hashByts));
        }
コード例 #9
0
        /// <summary>
        /// 计算MD5Cng哈希值
        /// </summary>
        /// <param name="input">输入</param>
        /// <returns>结果</returns>
        public static string HashMD5Cng(string input, Encoding encoding = null)
        {
            encoding = encoding ?? AgileEncoding.Default;

            var md5Hash = MD5Cng.Create();

            byte[] datas = md5Hash.ComputeHash(encoding.GetBytes(input));

            var ret = new StringBuilder();

            for (var i = 0; i < datas.Length; i++)
            {
                ret.Append(datas[i].ToString("X2"));
            }
            return(ret.ToString());
        }
コード例 #10
0
        /// <summary>
        /// 利用MD5进行加密
        /// </summary>
        /// <param name="astr_Value"></param>
        /// <returns></returns>
        public static string EncryptMD5(string astr_Value)
        {
            string cl1 = astr_Value;
            string pwd = "";
            MD5    md5 = MD5Cng.Create();

            // 加密后是一个字节类型的数组
            byte[] s = md5.ComputeHash(Encoding.Unicode.GetBytes(cl1));
            // 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
            for (int i = 0; i < s.Length; i++)
            {
                // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符
                pwd = pwd + s[i].ToString("x");
            }

            return(pwd);
        }
コード例 #11
0
        public static Hashes CalculateHash(string filePath)
        {
            Hashes res = new Hashes()
            {
                sha1 = null, md5 = null
            };

            try
            {
                /*
                 * using(var sha1 = SHA1.Create())
                 * using (var md5 = MD5.Create())
                 * using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                 * {
                 *  md5.
                 *  hash = BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", string.Empty);
                 * }*/

                using (var md5 = MD5Cng.Create())       // Or MD5Cng.Create
                    using (var sha1 = SHA1Cng.Create()) // Or SHA1Cng.Create
                        using (var input = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            byte[] buffer = new byte[8192];
                            int    bytesRead;
                            while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                md5.TransformBlock(buffer, 0, bytesRead, buffer, 0);
                                sha1.TransformBlock(buffer, 0, bytesRead, buffer, 0);
                            }
                            // We have to call TransformFinalBlock, but we don't have any
                            // more data - just provide 0 bytes.
                            md5.TransformFinalBlock(buffer, 0, 0);
                            sha1.TransformFinalBlock(buffer, 0, 0);

                            res.md5  = BitConverter.ToString(md5.Hash).Replace("-", string.Empty);
                            res.sha1 = BitConverter.ToString(sha1.Hash).Replace("-", string.Empty);
                        }
            }
            catch (Exception e)
            {
                // This should never happen at this time, but we don't want to stuck the process if it happens.
            }
            return(res);
        }
コード例 #12
0
        internal static string Compute(FileStream streem)
        {
            byte[] byteArr = new byte[streem.Length];
            //List<byte> byteList = new List<byte>();
            string HashStr = "";

            /*int i = 0;
             * foreach (char temp in str.ToCharArray())
             * {
             *  byteList.Add((byte)temp);
             *  i++;
             * }
             * i = 0;*/
            streem.Read(byteArr, 0, (int)streem.Length);
            //byteArr = byteList.ToArray();
            var md5Hash = MD5Cng.Create().ComputeHash(byteArr);

            HashStr = BitConverter.ToString(md5Hash).Replace("-", String.Empty).ToLower();
            return(HashStr);
        }
コード例 #13
0
        /// <summary>
        /// Generates a unique subscription ID that can be passed to <see cref="LiveCaptureSubscription()"/>
        /// </summary>
        /// <returns>The generated ID.</returns>
        /// <param name="connectionIndex">Client origin.</param>
        /// <param name="equpimentType">Equipment type.</param>
        /// <param name="equipmentIndex">Equipment index to observe.</param>
        public static ulong GenerateSubscriptionID(int connectionIndex, SensorType equpimentType, int equipmentIndex)
        {
            // concat arguments to input array
            byte[] bConnection = BitConverter.GetBytes(connectionIndex);
            byte[] bSensor     = BitConverter.GetBytes((int)equpimentType);
            byte[] bIndex      = BitConverter.GetBytes(equipmentIndex);
            byte[] input       = new byte[bConnection.Length + bSensor.Length + bIndex.Length];
            int    offset      = 0;

            Array.Copy(bConnection, 0, input, offset, bConnection.Length);
            offset += bConnection.Length;
            Array.Copy(bSensor, 0, input, offset, bSensor.Length);
            offset += bSensor.Length;
            Array.Copy(bIndex, 0, input, offset, bIndex.Length);
            // comptute some hash
            byte[] hash;
            using (MD5 md5 = MD5Cng.Create()) {
                hash = md5.ComputeHash(input);
            }
            // reduce the hash to a shorter value
            ulong checkSum = 0x0;

            if (hash.Length < sizeof(ulong))
            {
                // fail safe
                // generate something if the hash is somehow very short
                for (int i = 0; i < hash.Length; i++)
                {
                    checkSum |= ((ulong)hash[i] << (8 * i));
                }
                return(checkSum);
            }

            for (int i = 0; i + sizeof(ulong) <= hash.Length; i += sizeof(ulong))
            {
                checkSum ^= BitConverter.ToUInt64(hash, i);
            }

            return(checkSum);
        }
コード例 #14
0
ファイル: sha.cs プロジェクト: rasmus-z/CodeCleanupTools
    private static void Main(string[] args)
    {
        string filePath = null;

        if (args.Length == 1)
        {
            filePath = args[0];
        }

        if (!File.Exists(filePath))
        {
            Console.WriteLine("File doesn't exist:" + filePath);
            return;
        }

        var sha1   = Utilities.SHA1Hash(filePath);
        var sha256 = Utilities.SHA256Hash(filePath);
        var md5    = Utilities.Hash(filePath, MD5Cng.Create());

        Console.WriteLine($"SHA1:   {sha1}");
        Console.WriteLine($"SHA256: {sha256}");
        Console.WriteLine($"MD5:    {md5}");
    }
コード例 #15
0
ファイル: Security.cs プロジェクト: vizdr/SparEinKasse
        private static string GetPreCode(string input)
        {
            Byte[] preCode = Encoding.UTF8.GetBytes(input);

            using (MD5 coder = MD5Cng.Create())
            {
                coder.Initialize();
                preCode = coder.ComputeHash(preCode);
            }

            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data
            // and format each one as a hexadecimal string.
            for (int i = 0; i < preCode.Length; i++)
            {
                sBuilder.Append(preCode[i].ToString("x2"));
            }

            // Return the hexadecimal string.

            return(sBuilder.ToString());
        }
コード例 #16
0
ファイル: Hash.cs プロジェクト: xiaoyangjack/epii-csharp
        public string GetMD5Cng()
        {
            var hasher = MD5Cng.Create();

            return(ComputeHash(hasher));
        }
コード例 #17
0
            private void Run()
            {
                // Create x files of y mb  files and write to their streams
                var assFI       = new FileInfo(new Uri(typeof(Program).Assembly.Location).LocalPath);
                var shadowspawn = new FileInfo(Path.Combine(assFI.DirectoryName, "shadowspawn.exe"));

                if (!shadowspawn.Exists)
                {
                    Error($"[Shadowspawn] {shadowspawn.FullName} doesn't exists", -1);
                }


                Section("Clean up");
                RecreateDirs(ShadowBackupDI, DirectBackupDI, DataDI);

                // Setup the files
                Section("Creating files");

                for (int i = 0; i < Count; i++)
                {
                    var fi = GetFile(DataDI, SizeMB, i);
                    fi.Directory.Create();


                    // Using the file flag no buffering and write through seems to fool shadowspawn
                    FileOptions FileFlagNoBuffering = (FileOptions)0x20000000;
                    var         stream = new FileStream(fi.FullName, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, 8, FileOptions.WriteThrough | FileFlagNoBuffering);
                    fi.Refresh();
                    Info($"[{i}] Creating: {fi.FullName}");
                    Trace($"[{i}] LastWrite: {fi.LastWriteTime}");
                    stream.SetLength(SizeBytes);
                    m_streams[i] = stream;
                }

                var blockCount = SizeMB * Count;

                Section($"Writing blocks 0 -> {blockCount}");

                using (var md5 = MD5Cng.Create())
                {
                    for (int i = 0; i < blockCount; i++)
                    {
                        if (s_cancelSrc.IsCancellationRequested)
                        {
                            break;
                        }
                        s_indent = 0;
                        Section($"Loop#{i}");
                        s_indent++;

                        rnd.NextBytes(m_buffer);
                        var dataHash = Convert.ToBase64String(md5.ComputeHash(m_buffer));
                        Trace($"[Memory] Hash: {dataHash}");

                        // Update the block information
                        m_helper.Update(i);
                        WriteStream();

                        // Read the hash to make sure properly written
                        ReadFile(DataDI);
                        var writtenHash = Convert.ToBase64String(md5.ComputeHash(m_buffer));
                        Trace($"[DataDI] Hash: {dataHash}");

                        if (!string.Equals(dataHash, writtenHash))
                        {
                            Error($"[Write], hash mismatch: {dataHash} != {writtenHash}", -11);
                        }

                        //// Plain copy
                        //DirectCopy();

                        //ReadFile(DirectBackupDI);
                        //var directHash = Convert.ToBase64String(md5.ComputeHash(m_buffer));
                        //Trace($"[DirectCopy] Hash: {directHash}");

                        //if (!string.Equals(dataHash, directHash))
                        //{
                        //    Error($"[DirectCopy], hash mismatch: {dataHash} != {directHash}", -12);
                        //}

                        // Shadow Copy
                        MakeShadowCopy(shadowspawn);

                        // Now read the block from backup
                        ReadFile(ShadowBackupDI);
                        var shadowHash = Convert.ToBase64String(md5.ComputeHash(m_buffer));
                        Trace($"[ShadowCopy] Hash: {shadowHash}");

                        if (!string.Equals(dataHash, shadowHash))
                        {
                            Error($"[ShadowCopy], hash mismatch: {dataHash} != {shadowHash}", -13);
                        }
                    }
                }
            }
コード例 #18
0
        /// <summary>ハッシュ(キー無し)サービスプロバイダの生成</summary>
        /// <param name="eha">ハッシュ(キー無し)サービスプロバイダの列挙型</param>
        /// <returns>ハッシュ(キー無し)サービスプロバイダ</returns>
        /// <remarks>
        /// EnumHashAlgorithmから、HashAlgorithmを生成するために追加。
        /// HashAlgorithm.Create(HashNameConst.SHA256) は .NET Core 2 で動作せず。
        /// - KeyedHashAlgorithm.Create("HMACSHA1") throw PNSE (on .NET Core 2
        ///   https://github.com/dotnet/standard/issues/530#issuecomment-375043416
        /// </remarks>
        public static HashAlgorithm CreateHashAlgorithmSP(EnumHashAlgorithm eha)
        {
            // ハッシュ(キー無し)サービスプロバイダ
            HashAlgorithm ha = null;

            if (eha == EnumHashAlgorithm.Default)
            {
                // 既定の暗号化サービスプロバイダ
                ha = HashAlgorithmCmnFunc.GetHashAlgorithmFromNameString(); // devps(1703)
            }

            #region MD5
            else if (eha == EnumHashAlgorithm.MD5_CSP)
            {
                // MD5CryptoServiceProviderサービスプロバイダ
                ha = MD5CryptoServiceProvider.Create(); // devps(1703)
            }
#if NETSTD
#else
            else if (eha == EnumHashAlgorithm.MD5_CNG)
            {
                // MD5Cngサービスプロバイダ
                ha = MD5Cng.Create(); // devps(1703)
            }
#endif
            #endregion

            #region RIPEMD160
            else if (eha == EnumHashAlgorithm.RIPEMD160_M)
            {
#if NETSTD
                ha = null; // BouncyCastleを使用する。
#else
                // RIPEMD160Managedサービスプロバイダ
                ha = RIPEMD160Managed.Create(); // devps(1703)
#endif
            }
            #endregion

            #region SHA1
            else if (eha == EnumHashAlgorithm.SHA1_CSP)
            {
                // SHA1CryptoServiceProviderサービスプロバイダ
                ha = SHA1CryptoServiceProvider.Create(); // devps(1703)
            }
#if NETSTD
#else
            else if (eha == EnumHashAlgorithm.SHA1_CNG)
            {
                // SHA1Cngサービスプロバイダ
                ha = SHA1Cng.Create(); // devps(1703)
            }
#endif
            else if (eha == EnumHashAlgorithm.SHA1_M)
            {
                // SHA1Managedサービスプロバイダ
                ha = SHA1Managed.Create(); // devps(1703)
            }
            #endregion

            #region SHA256
            else if (eha == EnumHashAlgorithm.SHA256_CSP)
            {
                // SHA256CryptoServiceProviderサービスプロバイダ
                ha = SHA256CryptoServiceProvider.Create(); // devps(1703)
            }
#if NETSTD
#else
            else if (eha == EnumHashAlgorithm.SHA256_CNG)
            {
                // SHA256Cngサービスプロバイダ
                ha = SHA256Cng.Create(); // devps(1703)
            }
#endif
            else if (eha == EnumHashAlgorithm.SHA256_M)
            {
                // SHA256Managedサービスプロバイダ
                ha = SHA256Managed.Create(); // devps(1703)
            }
            #endregion

            #region SHA384
            else if (eha == EnumHashAlgorithm.SHA384_CSP)
            {
                // SHA384CryptoServiceProviderサービスプロバイダ
                ha = SHA384CryptoServiceProvider.Create(); // devps(1703)
            }
#if NETSTD
#else
            else if (eha == EnumHashAlgorithm.SHA384_CNG)
            {
                // SHA384Cngサービスプロバイダ
                ha = SHA384Cng.Create(); // devps(1703)
            }
#endif
            else if (eha == EnumHashAlgorithm.SHA384_M)
            {
                // SHA384Managedサービスプロバイダ
                ha = SHA384Managed.Create(); // devps(1703)
            }
            #endregion

            #region SHA512
            else if (eha == EnumHashAlgorithm.SHA512_CSP)
            {
                // SHA512CryptoServiceProviderサービスプロバイダ
                ha = SHA512CryptoServiceProvider.Create(); // devps(1703)
            }
#if NETSTD
#else
            else if (eha == EnumHashAlgorithm.SHA512_CNG)
            {
                // SHA512Cngサービスプロバイダ
                ha = SHA512Cng.Create(); // devps(1703)
            }
#endif
            else if (eha == EnumHashAlgorithm.SHA512_M)
            {
                // SHA512Managedサービスプロバイダ
                ha = SHA512Managed.Create(); // devps(1703)
            }
            #endregion

            else
            {
                // 既定の暗号化サービスプロバイダ
                ha = HashAlgorithmCmnFunc.GetHashAlgorithmFromNameString(); // devps(1703)
            }

            return(ha);
        }
コード例 #19
0
ファイル: frmHashTool.cs プロジェクト: drizzt/ctr_toolkit
        // ReSharper disable AccessToStaticMemberViaDerivedType
        private void setHashAlgorithm()
        {
            switch (cbAlgo.SelectedIndex)
            {
            case 0:
                switch (cbOption.SelectedIndex)
                {
                case 0: _ha = SHA256.Create();
                    break;

                case 1: _ha = SHA256Cng.Create();
                    break;

                case 2: _ha = HMACSHA256.Create();
                    break;
                }
                break;

            case 1:
                switch (cbOption.SelectedIndex)
                {
                case 0: _ha = SHA512.Create();
                    break;

                case 1: _ha = SHA512Cng.Create();
                    break;

                case 2: _ha = HMACSHA512.Create();
                    break;
                }
                break;

            case 2:
                switch (cbOption.SelectedIndex)
                {
                case 0: _ha = SHA1.Create();
                    break;

                case 1: _ha = SHA1Cng.Create();
                    break;

                case 2: _ha = HMACSHA1.Create();
                    break;
                }
                break;

            case 3:
                switch (cbOption.SelectedIndex)
                {
                case 0: _ha = MD5.Create();
                    break;

                case 1: _ha = MD5Cng.Create();
                    break;

                case 2: _ha = HMACMD5.Create();
                    break;
                }
                break;

            case 4:
                //stays null for Modbus-CRC16
                break;

            case 5:
                _ha = new Crc32();
                break;
            }
        }