Example #1
0
        //计算MD5
        public static string ComputeMD5(string fileName)
        {
            string tmpHashMD5 = string.Empty;

            //检查文件是否存在,如果文件存在则进行计算,否则返回空值
            if (System.IO.File.Exists(fileName))
            {
                using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    //计算文件的MD5值
                    System.Security.Cryptography.MD5 tmpCalculator = System.Security.Cryptography.MD5.Create();
                    byte[] tmpBuffer = tmpCalculator.ComputeHash(fs);
                    tmpCalculator.Clear();
                    //将字节数组转换成十六进制的字符串形式
                    StringBuilder tmpStrBuilder = new StringBuilder();

                    for (int i = 0; i < tmpBuffer.Length; i++)
                    {
                        tmpStrBuilder.Append(tmpBuffer[i].ToString("x2"));
                    }

                    tmpHashMD5 = tmpStrBuilder.ToString();
                } //关闭文件流
            }     //结束计算

            return(tmpHashMD5);
        }
Example #2
0
        public static string GetFileMd5(string filePath)
        {
            String hashMD5 = String.Empty;

            if (File.Exists(filePath))
            {
                using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    using (System.Security.Cryptography.MD5 calculator = System.Security.Cryptography.MD5.Create())
                    {
                        Byte[] buffer = calculator.ComputeHash(fs);
                        calculator.Clear();
                        StringBuilder stringBuilder = new StringBuilder();
                        for (int i = 0; i < buffer.Length; i++)
                        {
                            stringBuilder.Append(buffer[i].ToString("x2"));
                        }

                        hashMD5 = stringBuilder.ToString();
                    }
                }
            }

            return(hashMD5);
        }
Example #3
0
        public static string CalcFile(string localPath)
        {
            string hashMD5 = "";

            //检查文件是否存在,如果文件存在则进行计算,否则返回空值
            if (System.IO.File.Exists(localPath))
            {
                using (System.IO.FileStream fs = new System.IO.FileStream(localPath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    //计算文件的MD5值
                    System.Security.Cryptography.MD5 calculator = System.Security.Cryptography.MD5.Create();
                    Byte[] buffer = calculator.ComputeHash(fs);
                    calculator.Clear();
                    //将字节数组转换成十六进制的字符串形式
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < buffer.Length; i++)
                    {
                        stringBuilder.Append(buffer[i].ToString("x2"));
                    }
                    hashMD5 = stringBuilder.ToString();
                } //关闭文件流
            }     //结束计算

            return(hashMD5);
        }
Example #4
0
        /// <summary>
        /// ファイルからMD5形式のハッシュ値を取得する。
        /// ※ファイル全体からハッシュ値を取得するのは重すぎるため、先頭中間末尾からそれぞれ1KByteずつ
        /// サンプルしている。
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns>16進数のハッシュ文字列</returns>
        private string getFileMD5(string fileName)
        {
            //ファイルを開く
            FileStream fs = new FileStream(
                fileName,
                FileMode.Open,
                FileAccess.Read,
                FileShare.Read);

            byte[] fileData;

            // ファイル全体のMD5は重いため簡易版に置き換え
            //MD5CryptoServiceProviderオブジェクトを作成
            System.Security.Cryptography.MD5 md5 =
                System.Security.Cryptography.MD5.Create();

            // ファイルの先頭、中間、末尾からそれぞれ1KByteを読み込む(計3KByte)
            long      fileLen   = fs.Length;
            const int chankSize = 1024;

            if (fileLen >= 2147483648)
            {
                fileLen = 2147483648;
            }

            if (fileLen >= chankSize * 3)
            {
                fileData = new byte[chankSize * 3];
                var tempData = new byte[chankSize];
                fs.Read(fileData, 0, chankSize);
                fs.Seek((fileLen / 2) - chankSize / 2, SeekOrigin.Begin);
                fs.Read(fileData, chankSize, chankSize);
                fs.Seek(fileLen - chankSize, SeekOrigin.Begin);
                fs.Read(fileData, chankSize * 2, chankSize);
            }
            else
            {
                fileData = new byte[fileLen];
                fs.Read(fileData, 0, (int)fileLen);
            }
            byte[] bs = md5.ComputeHash(fileData);
            md5.Clear();

            //ファイルを閉じる
            fs.Close();

            //byte型配列を16進数の文字列に変換
            StringBuilder result = new StringBuilder();

            foreach (byte b in bs)
            {
                result.Append(b.ToString("x2"));
            }
            // ファイルサイズの4byte目までも追加
            result.Append(String.Format("{0:X8}", (int)fileLen));

            return(result.ToString());
        }
        /// <summary>
        ///  计算指定文件的MD5值
        /// </summary>
        /// <param name="fs">文件流</param>
        /// <returns>返回值的字符串形式</returns>
        public static Byte[] MD5(FileStream fs)
        {
            String hashMD5 = String.Empty;

            //计算文件的MD5值
            System.Security.Cryptography.MD5 calculator = System.Security.Cryptography.MD5.Create();
            Byte[] buffer = calculator.ComputeHash(fs);
            calculator.Clear();
            return(buffer);
        }//ComputeMD5
Example #6
0
        private string GetHash(string str)
        {
            var buf = System.Text.Encoding.UTF8.GetBytes(str);

            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();

            var hash = md5.ComputeHash(buf);

            md5.Clear();

            return(BitConverter.ToString(hash).ToLower().Replace("-", ""));
        }
Example #7
0
        private static string MD5(byte[] bytes)
        {
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] b   = md5.ComputeHash(bytes);
            string hex = "";

            foreach (byte b2 in b)
            {
                hex += b2.ToString("x0").PadLeft(2, '0');
            }
            md5.Clear();
            return(hex);
        }
Example #8
0
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (m_hash != null)
            {
                m_hash.Clear();
                m_hash = null;

                m_hashbuffer       = null;
                m_hashbufferLength = 0;
            }
        }
        /// <summary>
        /// MD5
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public static string MD5(byte[] buffer)
        {
            System.Security.Cryptography.MD5 calculator = System.Security.Cryptography.MD5.Create();
            buffer = calculator.ComputeHash(buffer);
            calculator.Clear();
            //将字节数组转换成十六进制的字符串形式
            StringBuilder stringBuilder = new StringBuilder();

            for (int i = 0; i < buffer.Length; i++)
            {
                stringBuilder.Append(buffer[i].ToString("x2"));
            }
            return(stringBuilder.ToString());
        }
Example #10
0
        public static string MD5(string str)
        {
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] b    = Encoding.UTF8.GetBytes(str);
            byte[] md5b = md5.ComputeHash(b);
            md5.Clear();
            StringBuilder sb = new StringBuilder();

            foreach (var item in md5b)
            {
                sb.Append(item.ToString("x2"));
            }
            return(sb.ToString());
        }
Example #11
0
        protected string MD5(string input)
        {
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
            byte[] hash       = md5.ComputeHash(inputBytes);
            md5.Clear();
            // step 2, convert byte array to hex string
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("x2").PadLeft(2, '0'));
            }
            return(sb.ToString());
        }
Example #12
0
        public static string CalcString(string str)
        {
            string hashMD5 = "";

            System.Security.Cryptography.MD5 calculator = System.Security.Cryptography.MD5.Create();
            Byte[] buffer = calculator.ComputeHash(Encoding.UTF8.GetBytes(str));
            calculator.Clear();
            //将字节数组转换成十六进制的字符串形式
            StringBuilder stringBuilder = new StringBuilder();

            for (int i = 0; i < buffer.Length; i++)
            {
                stringBuilder.Append(buffer[i].ToString("x2"));
            }
            hashMD5 = stringBuilder.ToString();
            return(hashMD5);
        }
Example #13
0
        private string CreateMD5Hash(string input)
        {
            // Use input string to calculate MD5 hash
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
            byte[] hashBytes  = md5.ComputeHash(inputBytes);
            md5.Clear();

            // Convert the byte array to hexadecimal string
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("x2"));
            }
            return(sb.ToString());
        }
Example #14
0
        public string MD5(string strConvertir)
        {
            // Convertimos la cadena de entrada en arreglo de bytes desde MD5
            System.Security.Cryptography.MD5 objMD5 = System.Security.Cryptography.MD5.Create();
            byte[] inbuf  = System.Text.Encoding.UTF8.GetBytes(strConvertir);
            byte[] outbuf = objMD5.ComputeHash(inbuf);
            objMD5.Clear();

            // Se formatea el arreglo de bytes en hexadecimal
            char   pad           = '0';
            string strConvertido = "";

            for (int i = 0; i <= outbuf.Length - 1; i++)
            {
                strConvertido += outbuf[i].ToString("x").PadLeft(2, pad);
            }

            return(strConvertido);
        }
Example #15
0
        /// <summary>
        /// チェックサムを生成
        /// </summary>
        /// <param name="key">共有キー</param>
        /// <param name="values">値</param>
        /// <returns>MD5チェックサム</returns>
        public static string GenerateCheckSum(string key, params string[] values)
        {
            StringBuilder sb = new StringBuilder(key);

            System.Diagnostics.Debug.WriteLine("GenerateChecksum key:" + key);
            foreach (string val in values)
            {
                System.Diagnostics.Debug.WriteLine("AppendValue:" + val);
                sb.Append(val);
            }
            System.Security.Cryptography.MD5 ctx = System.Security.Cryptography.MD5.Create();
            byte[] data = Encoding.UTF8.GetBytes(sb.ToString());
            byte[] sum  = ctx.ComputeHash(data);
            ctx.Clear();

            string sum16 = BitConverter.ToString(sum).ToLower().Replace("-", "");

            System.Diagnostics.Debug.WriteLine("Checksum:" + sum16);
            return(sum16);
        }
Example #16
0
        }//ComputeMD5

        /// <summary>
        ///  计算指定文件的MD5值
        /// </summary>
        /// <param name="fileName">指定文件的完全限定名称</param>
        /// <returns>返回值的字符串形式</returns>
        public static String ComputeMD5(byte[] stream)
        {
            String hashMD5 = String.Empty;



            //计算文件的MD5值
            System.Security.Cryptography.MD5 calculator = System.Security.Cryptography.MD5.Create();
            Byte[] buffer = calculator.ComputeHash(stream);
            calculator.Clear();
            //将字节数组转换成十六进制的字符串形式
            StringBuilder stringBuilder = new StringBuilder();

            for (int i = 0; i < buffer.Length; i++)
            {
                stringBuilder.Append(buffer[i].ToString("x2"));
            }
            hashMD5 = stringBuilder.ToString();
            return(hashMD5);
        }//ComputeMD5
Example #17
0
        public static string ToMD5(this Stream stream)
        {
            //计算文件的MD5值
            System.Security.Cryptography.MD5 calculator = System.Security.Cryptography.MD5.Create();
            Byte[] buffer = calculator.ComputeHash(stream);
            calculator.Clear();

            //将字节数组转换成十六进制的字符串形式
            StringBuilder stringBuilder = new StringBuilder();

            for (int i = 0; i < buffer.Length; i++)
            {
                stringBuilder.Append(buffer[i].ToString("x2"));
            }
            var hashMD5 = stringBuilder.ToString();

            stream.Position = 0; // 重置位置,避免下一个使用者使用报错

            return(hashMD5);
        }
        ///MD5加密
        public static string GetMD5String(string input)
        {
            //1.创建一个md5对象
            System.Security.Cryptography.MD5 md5Obj = System.Security.Cryptography.MD5.Create();
            //1.1把字符串转换为byte[]
            byte[] buffer = System.Text.Encoding.Default.GetBytes(input);

            //2.通过md5对象计算给定值的md5
            byte[] md5Buffer = md5Obj.ComputeHash(buffer);
            //把byte[]数组转换为字符串
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < md5Buffer.Length; i++)
            {
                sb.Append(md5Buffer[i].ToString("x2"));
            }
            //3.释放资源
            md5Obj.Clear();
            // return sb.ToString();
            return(BitConverter.ToString(md5Buffer).Replace("-", "").ToLower());
        }
Example #19
0
        /// <summary>
        /// Encrypt checksum string
        /// </summary>
        /// <param name="plainText"></param>
        /// <returns></returns>
        private string Encrypt(string plainText)
        {
            // instant md5 object
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();

            // convert string to byte array
            byte[] data = md5.ComputeHash(Encoding.UTF8.GetBytes(plainText));

            // build encrypted text
            StringBuilder strBuilder = new StringBuilder();

            // re-format each byte in data as hexadecimal string
            for (int index = 0; index < data.Length; index++)
            {
                strBuilder.Append(data[index].ToString("x2"));
            }

            // clear md5 instant
            md5.Clear();

            return(strBuilder.ToString());
        }
Example #20
0
        /// <summary>
        ///  计算指定文件的MD5值
        /// </summary>
        /// <param name="fileName">指定文件的完全限定名称</param>
        /// <returns>返回值的字符串形式</returns>
        public static String GetMD5(String fileName)
        {
            String hashMD5 = String.Empty;

            //检查文件是否存在,如果文件存在则进行计算,否则返回空值
            if (File.Exists(fileName))
            {
                using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    //计算文件的MD5值
                    System.Security.Cryptography.MD5 calculator = System.Security.Cryptography.MD5.Create();
                    Byte[] buffer = calculator.ComputeHash(fs);
                    calculator.Clear();
                    //将字节数组转换成十六进制的字符串形式
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < buffer.Length; i++)
                    {
                        stringBuilder.Append(buffer[i].ToString("x2"));
                    }
                    hashMD5 = stringBuilder.ToString();
                } //关闭文件流
            }     //结束计算
            return(hashMD5);
        }         //ComputeMD5
Example #21
0
        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            this.contextMenuStripTreeNode.Items.Clear();
            if (e.Button == MouseButtons.Right && e.Node != null)
            {
                var selectedNode = e.Node;
                treeView1.SelectedNode = selectedNode;
                if (selectedNode.Parent != null) //file node selected
                {
                    ToolStripMenuItem menu1 = new ToolStripMenuItem();
                    menu1.Text   = "open path";
                    menu1.Click += new System.EventHandler((sender1, e1) =>
                    {
                        Process p             = new Process();
                        p.StartInfo.FileName  = "explorer.exe";
                        p.StartInfo.Arguments = @"/e,/select," + selectedNode.Text;
                        p.Start();
                    });

                    ToolStripMenuItem menu2 = new ToolStripMenuItem();
                    menu2.Text   = "open file";
                    menu2.Click += new System.EventHandler((sender1, e1) =>
                    {
                        Process p             = new Process();
                        p.StartInfo.FileName  = "explorer.exe";
                        p.StartInfo.Arguments = selectedNode.Text;
                        p.Start();
                    });

                    ToolStripMenuItem menu3 = new ToolStripMenuItem();
                    menu3.Text   = "delete";
                    menu3.Click += new System.EventHandler((sender1, e1) =>
                    {
                        if (MessageBox.Show("are you sure to delete this file?", "warning", MessageBoxButtons.OKCancel) == DialogResult.OK)
                        {
                            FileInfo file = new FileInfo(selectedNode.Text);
                            file.Delete();
                            selectedNode.Parent.Nodes.Remove(selectedNode);
                        }
                    });
                    this.contextMenuStripTreeNode.Items.Clear();
                    this.contextMenuStripTreeNode.Items.AddRange(new ToolStripItem[] { menu1, menu2, menu3 });
                    this.contextMenuStripTreeNode.Show(MousePosition.X, MousePosition.Y);
                }
                else //fileGroup node selected
                {
                    ToolStripMenuItem menu1 = new ToolStripMenuItem();
                    menu1.Text   = "compute hash";
                    menu1.Click += new System.EventHandler((sender1, e1) =>
                    {
                        List <string> md5list = new List <string>();

                        foreach (TreeNode fileNode in selectedNode.Nodes)
                        {
                            System.Security.Cryptography.MD5 calcer = System.Security.Cryptography.MD5.Create();
                            FileStream fs = new FileStream(fileNode.Text, FileMode.Open);
                            var hash      = calcer.ComputeHash(fs);
                            calcer.Clear();
                            fs.Close();
                            StringBuilder stringBuilder = new StringBuilder();
                            for (int i = 0; i < hash.Length; i++)
                            {
                                stringBuilder.Append(hash[i].ToString("x2"));
                            }
                            md5list.Add(stringBuilder.ToString());
                        }
                        string str = "";
                        foreach (var item in md5list)
                        {
                            str += item + "\r\n";
                        }
                        MessageBox.Show(str);
                    });
                    ToolStripMenuItem menu2 = new ToolStripMenuItem();
                    menu2.Text   = "compare content";
                    menu2.Click += new System.EventHandler((sender1, e1) =>
                    {
                        bool issame = CompareFile(selectedNode.Nodes[0].Text, selectedNode.Nodes[1].Text);
                        MessageBox.Show(issame ? "内容完全一致" : "内容不一致");
                    });

                    this.contextMenuStripTreeNode.Items.Clear();
                    this.contextMenuStripTreeNode.Items.AddRange(new ToolStripItem[] { menu1, menu2 });
                    this.contextMenuStripTreeNode.Show(MousePosition.X, MousePosition.Y);
                }
            }
        }