C#获取文件sha1总是与网上工具获取的结果不一样
下面是我获取文件sha1的代码
        private void bt_compute_Click(object sender, EventArgs e)
        {
            //计算文件MD5
            if(tb_filepath.Text=="")
            {
                MessageBox.Show("路径为空请重新选择文件!");
                return;
            }
            MD5 md5 = new MD5CryptoServiceProvider();
            FileStream get_file = new FileStream(openfilepath, FileMode.Open, FileAccess.Read, FileShare.Read);            
            byte[] hash_byte = md5.ComputeHash(get_file);
            string file_md5 = System.BitConverter.ToString(hash_byte);
            file_md5 = file_md5.Replace("-", "");
            tb_md5.Text = file_md5;
            //计算文件SHA1
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] sha1_byte = new byte[get_file.Length];
            get_file.Read(sha1_byte, 0, sha1_byte.Length);
            byte[] sha1_password = sha1.ComputeHash(sha1_byte);
            string file_sha1 = System.BitConverter.ToString(sha1_password);
            file_sha1 = file_sha1.Replace("-", "");
            tb_sha1.Text = file_sha1;
            //StringBuilder str = new StringBuilder();
            //for (int i = 0; i < sha1_password.Length; i++)
            //{
            //    str.Append(sha1_password[i].ToString("x2"));
            //}
            //tb_sha1.Text = str.ToString();            //显示文件名
            string filename = openfilepath.Substring(openfilepath.LastIndexOf("\\") + 1);
            lb_filename.Text = filename;
        }

解决方案 »

  1.   


                OpenFileDialog ofd = new OpenFileDialog();
                if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    FileStream fs = File.Open(ofd.FileName, FileMode.Open);
                    byte[] buffer = System.Security.Cryptography.SHA1.Create().ComputeHash(fs);
                    string sha1 = BitConverter.ToString(buffer).Replace("-", string.Empty);
                    MessageBox.Show(sha1);
                }简单几句就搞定
      

  2.   

    为什么用你这段代码算出来的sha1跟网上常见的sha1工具算出来的不一样呢?
      

  3.   

    我发现错误了!我在使用完文件流之后没有进行close所有会出现生成的sha1不正确的现象!不过具体原因我也不清楚呀
      

  4.   

    我看了一下,和网上的都一样啊。
    和微软官方对比windows和office的sha1都没问题
      

  5.   

    我发现错误了!我在使用文件流计算完MD5之后没有进行close,继续使用这个文件流计算sha1会出现生成的sha1不正确的现象!能不能跟我说一下原因呀?文件流不能这样使用吗?