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;
}
下面是我获取文件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;
}
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);
}简单几句就搞定
和微软官方对比windows和office的sha1都没问题