// 哈希校验 - 绿色工具箱 // 单文件零依赖,C# 5.0 语法(net48 自带 csc 可编译) // 功能:文件 MD5/SHA1/SHA256 计算 + 校验比对 + 拖拽支持 using System; using System.ComponentModel; using System.Drawing; using System.IO; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Windows.Forms; namespace GreenToolbox { public class HashToolForm : Form { private static readonly Color COL_GREEN = Color.FromArgb(0, 145, 88); private static readonly Color COL_GREEN_DARK = Color.FromArgb(0, 110, 66); private static readonly Color COL_BG = Color.White; private static readonly Color COL_PANEL = Color.FromArgb(245, 249, 246); private static readonly Color COL_TEXT = Color.FromArgb(34, 40, 36); private static readonly Color COL_GRAY = Color.FromArgb(120, 130, 124); private static readonly Color COL_OK = Color.FromArgb(0, 145, 88); private static readonly Color COL_BAD = Color.FromArgb(200, 50, 50); private TextBox txtFile; private Button btnPick; private Button btnCalc; private CheckBox chkMd5; private CheckBox chkSha1; private CheckBox chkSha256; private TextBox txtMd5; private TextBox txtSha1; private TextBox txtSha256; private Button btnCopyMd5; private Button btnCopySha1; private Button btnCopySha256; private TextBox txtExpect; private Label lblCompare; private Label lblStatus; private ProgressBar progress; private BackgroundWorker worker; private string lastResults = ""; public HashToolForm() { InitUi(); worker = new BackgroundWorker(); worker.WorkerReportsProgress = true; worker.DoWork += new DoWorkEventHandler(WorkerDoWork); worker.ProgressChanged += new ProgressChangedEventHandler(WorkerProgress); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(WorkerDone); } private void InitUi() { this.Text = "哈希校验 - 绿色工具箱"; this.Font = new Font("Microsoft YaHei UI", 9.5f); this.BackColor = COL_BG; this.ForeColor = COL_TEXT; this.ClientSize = new Size(760, 560); this.MinimumSize = new Size(660, 480); this.AllowDrop = true; this.DragEnter += new DragEventHandler(FormDragEnter); this.DragDrop += new DragEventHandler(FormDragDrop); int x = 20, y = 16; Label lblTitle = new Label(); lblTitle.Text = "计算文件 MD5 / SHA1 / SHA256,用于校验下载文件是否完整"; lblTitle.Location = new Point(x, y); lblTitle.AutoSize = true; lblTitle.ForeColor = COL_GRAY; this.Controls.Add(lblTitle); y += 30; txtFile = new TextBox(); txtFile.Location = new Point(x, y); txtFile.Size = new Size(600, 26); txtFile.ReadOnly = true; txtFile.BackColor = COL_PANEL; this.Controls.Add(txtFile); btnPick = new Button(); btnPick.Text = "选择文件"; btnPick.Location = new Point(628, y - 1); btnPick.Size = new Size(110, 28); btnPick.BackColor = COL_GREEN; btnPick.ForeColor = Color.White; btnPick.FlatStyle = FlatStyle.Flat; btnPick.FlatAppearance.BorderSize = 0; btnPick.Click += new EventHandler(BtnPickClick); this.Controls.Add(btnPick); y += 42; Label lblAlg = new Label(); lblAlg.Text = "算法:"; lblAlg.Location = new Point(x, y + 3); lblAlg.AutoSize = true; this.Controls.Add(lblAlg); chkMd5 = new CheckBox(); chkMd5.Text = "MD5"; chkMd5.Checked = true; chkMd5.Location = new Point(x + 55, y); chkMd5.AutoSize = true; this.Controls.Add(chkMd5); chkSha1 = new CheckBox(); chkSha1.Text = "SHA1"; chkSha1.Checked = true; chkSha1.Location = new Point(x + 115, y); chkSha1.AutoSize = true; this.Controls.Add(chkSha1); chkSha256 = new CheckBox(); chkSha256.Text = "SHA256"; chkSha256.Checked = true; chkSha256.Location = new Point(x + 178, y); chkSha256.AutoSize = true; this.Controls.Add(chkSha256); btnCalc = new Button(); btnCalc.Text = "开始计算"; btnCalc.Location = new Point(628, y - 4); btnCalc.Size = new Size(110, 30); btnCalc.BackColor = COL_GREEN; btnCalc.ForeColor = Color.White; btnCalc.FlatStyle = FlatStyle.Flat; btnCalc.FlatAppearance.BorderSize = 0; btnCalc.Click += new EventHandler(BtnCalcClick); this.Controls.Add(btnCalc); y += 38; progress = new ProgressBar(); progress.Location = new Point(x, y); progress.Size = new Size(718, 6); this.Controls.Add(progress); y += 18; txtMd5 = MakeHashRow("MD5 ", x, ref y); btnCopyMd5 = MakeCopyRow(txtMd5, x, ref y); txtSha1 = MakeHashRow("SHA1 ", x, ref y); btnCopySha1 = MakeCopyRow(txtSha1, x, ref y); txtSha256 = MakeHashRow("SHA256 ", x, ref y); btnCopySha256 = MakeCopyRow(txtSha256, x, ref y); Label lblExpect = new Label(); lblExpect.Text = "校验比对(粘贴官方给的哈希值,自动比对):"; lblExpect.Location = new Point(x, y); lblExpect.AutoSize = true; this.Controls.Add(lblExpect); y += 24; txtExpect = new TextBox(); txtExpect.Location = new Point(x, y); txtExpect.Size = new Size(600, 26); txtExpect.TextChanged += new EventHandler(ExpectChanged); this.Controls.Add(txtExpect); lblCompare = new Label(); lblCompare.Text = ""; lblCompare.Location = new Point(628, y + 4); lblCompare.AutoSize = true; lblCompare.Font = new Font("Microsoft YaHei UI", 10f, FontStyle.Bold); this.Controls.Add(lblCompare); y += 44; lblStatus = new Label(); lblStatus.Text = "支持把文件拖进窗口。大文件在后台计算,界面不会卡。"; lblStatus.Location = new Point(x, y); lblStatus.AutoSize = true; lblStatus.ForeColor = COL_GRAY; this.Controls.Add(lblStatus); Label lblFoot = new Label(); lblFoot.Text = "绿色版:不安装、不联网、无广告。哈希值可粘贴到 VirusTotal 等平台二次核对。"; lblFoot.Location = new Point(x, this.ClientSize.Height - 26); lblFoot.AutoSize = true; lblFoot.ForeColor = COL_GRAY; this.Controls.Add(lblFoot); } private TextBox MakeHashRow(string tag, int x, ref int y) { Label l = new Label(); l.Text = tag; l.Location = new Point(x, y + 4); l.AutoSize = true; l.ForeColor = COL_GRAY; this.Controls.Add(l); TextBox t = new TextBox(); t.Location = new Point(x + 62, y); t.Size = new Size(538, 26); t.ReadOnly = true; t.Font = new Font("Consolas", 9.5f); t.BackColor = COL_PANEL; this.Controls.Add(t); y += 34; return t; } private Button MakeCopyRow(TextBox target, int x, ref int y) { Button b = new Button(); b.Text = "复制"; b.Location = new Point(606, y - 35); b.Size = new Size(60, 26); b.FlatStyle = FlatStyle.Flat; b.FlatAppearance.BorderColor = COL_GREEN; b.ForeColor = COL_GREEN_DARK; b.Tag = target; b.Click += new EventHandler(CopyClick); this.Controls.Add(b); return b; } private void FormDragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; } private void FormDragDrop(object sender, DragEventArgs e) { string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); if (files != null && files.Length > 0) { txtFile.Text = files[0]; StartCalc(); } } private void BtnPickClick(object sender, EventArgs e) { using (OpenFileDialog d = new OpenFileDialog()) { d.Title = "选择要计算哈希的文件"; if (d.ShowDialog() == DialogResult.OK) { txtFile.Text = d.FileName; StartCalc(); } } } private void BtnCalcClick(object sender, EventArgs e) { StartCalc(); } private void StartCalc() { if (txtFile.Text.Length == 0 || !File.Exists(txtFile.Text)) { lblStatus.Text = "请先选择一个存在的文件。"; return; } if (worker.IsBusy) return; SetHashValue(txtMd5, ""); SetHashValue(txtSha1, ""); SetHashValue(txtSha256, ""); lblCompare.Text = ""; btnCalc.Enabled = false; progress.Value = 0; lblStatus.Text = "正在计算…"; bool[] alg = new bool[] { chkMd5.Checked, chkSha1.Checked, chkSha256.Checked }; worker.RunWorkerAsync(new object[] { txtFile.Text, alg }); } private void WorkerDoWork(object sender, DoWorkEventArgs e) { object[] args = (object[])e.Argument; string path = (string)args[0]; bool[] alg = (bool[])args[1]; string md5 = alg[0] ? ComputeHash(path, "MD5", (BackgroundWorker)sender) : ""; string sha1 = alg[1] ? ComputeHash(path, "SHA1", (BackgroundWorker)sender) : ""; string sha256 = alg[2] ? ComputeHash(path, "SHA256", (BackgroundWorker)sender) : ""; e.Result = new string[] { md5, sha1, sha256, path }; } private string ComputeHash(string path, string algo, BackgroundWorker bw) { return HashOps.Compute(path, algo, bw); } private void WorkerProgress(object sender, ProgressChangedEventArgs e) { progress.Value = e.ProgressPercentage; } private void WorkerDone(object sender, RunWorkerCompletedEventArgs e) { btnCalc.Enabled = true; progress.Value = 100; string[] r = (string[])e.Result; SetHashValue(txtMd5, r[0]); SetHashValue(txtSha1, r[1]); SetHashValue(txtSha256, r[2]); FileInfo fi = new FileInfo(r[3]); lblStatus.Text = "完成:" + fi.Name + "(" + FormatSize(fi.Length) + ")"; lastResults = r[0] + "\r\n" + r[1] + "\r\n" + r[2]; if (txtExpect.Text.Trim().Length > 0) DoCompare(); } private string FormatSize(long bytes) { return HashOps.FormatSize(bytes); } private void SetHashValue(TextBox t, string v) { t.Text = v; } private void CopyClick(object sender, EventArgs e) { Button b = (Button)sender; TextBox t = (TextBox)b.Tag; if (t.Text.Length > 0) { Clipboard.SetText(t.Text); lblStatus.Text = "已复制 " + b.Text.Replace("复制", "") + " 值到剪贴板。"; } } private void ExpectChanged(object sender, EventArgs e) { DoCompare(); } private void DoCompare() { string state = HashOps.CompareState(txtExpect.Text, txtMd5.Text, txtSha1.Text, txtSha256.Text); lblCompare.Text = state; if (state.Length == 0) return; if (state == HashOps.ST_MATCH) lblCompare.ForeColor = COL_OK; else if (state == HashOps.ST_DIFF) lblCompare.ForeColor = COL_BAD; else lblCompare.ForeColor = COL_GRAY; } } // ── 与界面解耦的纯逻辑,--selftest 直接调这里 ───────────────────────── public static class HashOps { public const string ST_NONE = ""; public const string ST_MATCH = "✔ 一致"; public const string ST_DIFF = "✘ 不一致"; public const string ST_BADFORMAT = "? 格式未知"; public const string ST_WAIT = "待计算"; // 分块读,1MB 一块,边读边报进度 —— 大文件不会把内存吃满 public static string Compute(string path, string algo, BackgroundWorker bw) { using (HashAlgorithm h = HashAlgorithm.Create(algo)) using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { long total = fs.Length; byte[] buf = new byte[1024 * 1024]; long read = 0; int n; while ((n = fs.Read(buf, 0, buf.Length)) > 0) { h.TransformBlock(buf, 0, n, null, 0); read += n; int pct = total > 0 ? (int)(read * 100 / total) : 100; if (bw != null && bw.WorkerReportsProgress) bw.ReportProgress(pct); } h.TransformFinalBlock(buf, 0, 0); return Hex(h.Hash); } } public static string Hex(byte[] hash) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < hash.Length; i++) sb.Append(hash[i].ToString("x2")); return sb.ToString(); } public static string CompareState(string expectRaw, string md5, string sha1, string sha256) { string expect = (expectRaw == null ? "" : expectRaw.Trim()).ToLower(); if (expect.Length == 0) return ST_NONE; string[] cand = new string[] { md5 == null ? "" : md5.ToLower(), sha1 == null ? "" : sha1.ToLower(), sha256 == null ? "" : sha256.ToLower() }; for (int i = 0; i < cand.Length; i++) if (cand[i].Length > 0 && cand[i] == expect) return ST_MATCH; bool anyFilled = cand[0].Length > 0 || cand[1].Length > 0 || cand[2].Length > 0; if (!anyFilled) return ST_WAIT; // 32/40/64 分别是 MD5/SHA1/SHA256 的长度,其它长度说明粘错了东西 if (expect.Length != 32 && expect.Length != 40 && expect.Length != 64) return ST_BADFORMAT; return ST_DIFF; } public static string FormatSize(long bytes) { if (bytes < 1024) return bytes + " B"; if (bytes < 1024 * 1024) return (bytes / 1024.0).ToString("0.#") + " KB"; if (bytes < 1024L * 1024 * 1024) return (bytes / 1024.0 / 1024).ToString("0.##") + " MB"; return (bytes / 1024.0 / 1024 / 1024).ToString("0.##") + " GB"; } } // 命令行自测:不弹窗,纯逻辑跑一遍,退出码 0 = 全过,1 = 有失败 public static class SelfTest { private static int _pass = 0; private static int _fail = 0; private static System.Collections.Generic.List _lines = new System.Collections.Generic.List(); private static string Esc(string s) { if (s == null) return ""; if (s.Length > 90) s = s.Substring(0, 90) + "…"; return s.Replace("\r", "\\r").Replace("\n", "\\n"); } private static void Check(string name, string got, string want) { if (got == null) got = ""; if (want == null) want = ""; if (got == want) { _pass++; _lines.Add(" [ok] " + name); } else { _fail++; _lines.Add(" [!!] " + name + " 期望[" + Esc(want) + "] 实际[" + Esc(got) + "]"); } } public static int Run(string dir) { if (string.IsNullOrEmpty(dir)) dir = Path.Combine(Path.GetTempPath(), "greentool-hash-selftest"); string fSmall = Path.Combine(dir, "h-abc.txt"); string fEmpty = Path.Combine(dir, "h-empty.txt"); string fBig = Path.Combine(dir, "h-big.bin"); string fCjk = Path.Combine(dir, "h-中文.txt"); try { Directory.CreateDirectory(dir); _lines.Add("哈希校验 自测(" + dir + ")"); BackgroundWorker bw = new BackgroundWorker(); // 未启动 → ReportProgress 是空操作 // ── 已知答案:abc ── File.WriteAllBytes(fSmall, new byte[] { 0x61, 0x62, 0x63 }); Check("abc 的 MD5", HashOps.Compute(fSmall, "MD5", bw), "900150983cd24fb0d6963f7d28e17f72"); Check("abc 的 SHA1", HashOps.Compute(fSmall, "SHA1", bw), "a9993e364706816aba3e25717850c26c9cd0d89d"); Check("abc 的 SHA256", HashOps.Compute(fSmall, "SHA256", bw), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); // ── 空文件 ── File.WriteAllBytes(fEmpty, new byte[0]); Check("空文件 MD5", HashOps.Compute(fEmpty, "MD5", bw), "d41d8cd98f00b204e9800998ecf8427e"); Check("空文件 SHA256", HashOps.Compute(fEmpty, "SHA256", bw), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); // ── 中文内容 + 中文文件名 ── File.WriteAllText(fCjk, "绿色工具箱 hash 自测", new UTF8Encoding(false)); string cjk1 = HashOps.Compute(fCjk, "SHA256", bw); string cjk2 = HashOps.Compute(fCjk, "SHA256", bw); Check("同一文件两次计算结果一致", cjk1, cjk2); Check("中文文件哈希是 64 位小写十六进制", (cjk1.Length == 64 && cjk1 == cjk1.ToLower()) ? "ok" : cjk1, "ok"); // ── 大文件:3 MB,跨多个 1MB 分块 —— 分块拼接最容易在这里出错 ── byte[] big = new byte[3 * 1024 * 1024 + 777]; for (int i = 0; i < big.Length; i++) big[i] = (byte)((i * 31 + 7) & 0xFF); File.WriteAllBytes(fBig, big); using (MD5 m = MD5.Create()) Check("3MB 文件分块计算的 MD5 与一次性计算相同", HashOps.Compute(fBig, "MD5", bw), HashOps.Hex(m.ComputeHash(big))); using (SHA1 s1 = SHA1.Create()) Check("3MB 文件分块计算的 SHA1 与一次性计算相同", HashOps.Compute(fBig, "SHA1", bw), HashOps.Hex(s1.ComputeHash(big))); using (SHA256 s2 = SHA256.Create()) Check("3MB 文件分块计算的 SHA256 与一次性计算相同", HashOps.Compute(fBig, "SHA256", bw), HashOps.Hex(s2.ComputeHash(big))); // ── 文件不存在要明确报错,不能静默返回空 ── bool threw = false; try { HashOps.Compute(Path.Combine(dir, "h-not-exist.bin"), "MD5", bw); } catch { threw = true; } Check("文件不存在时抛异常(由界面提示,不静默)", threw ? "threw" : "silent", "threw"); // ── 校验比对:四种状态都要对 ── string md5abc = "900150983cd24fb0d6963f7d28e17f72"; Check("期望值和 MD5 一致 → 一致", HashOps.CompareState(md5abc, md5abc, "", ""), HashOps.ST_MATCH); Check("期望值大写也能认", HashOps.CompareState(md5abc.ToUpper(), md5abc, "", ""), HashOps.ST_MATCH); Check("期望值前后有空格也能认", HashOps.CompareState(" " + md5abc + " ", md5abc, "", ""), HashOps.ST_MATCH); Check("期望值和 SHA256 一致 → 一致", HashOps.CompareState("ab" + new string('c', 62), "", "", "ab" + new string('c', 62)), HashOps.ST_MATCH); Check("长度合法但内容不同 → 不一致", HashOps.CompareState(new string('a', 32), md5abc, "", ""), HashOps.ST_DIFF); Check("长度不对 → 格式未知", HashOps.CompareState("abc123", md5abc, "", ""), HashOps.ST_BADFORMAT); Check("还没算 → 待计算", HashOps.CompareState(md5abc, "", "", ""), HashOps.ST_WAIT); Check("没填期望值 → 不显示", HashOps.CompareState(" ", md5abc, "", ""), HashOps.ST_NONE); // ── 体积格式化 ── Check("0 字节", HashOps.FormatSize(0), "0 B"); Check("1023 字节还是 B", HashOps.FormatSize(1023), "1023 B"); Check("1024 字节是 1 KB", HashOps.FormatSize(1024), "1 KB"); Check("1536 字节是 1.5 KB", HashOps.FormatSize(1536), "1.5 KB"); Check("1 MB", HashOps.FormatSize(1024L * 1024), "1 MB"); Check("1.5 GB", HashOps.FormatSize(1024L * 1024 * 1024 * 3 / 2), "1.5 GB"); } catch (Exception ex) { _fail++; _lines.Add(" [!!] 自测中途异常:" + ex.GetType().Name + " " + ex.Message); } finally { string[] made = new string[] { "h-abc.txt", "h-empty.txt", "h-big.bin", "h-中文.txt" }; foreach (string f in made) { string p = Path.Combine(dir, f); if (File.Exists(p)) { try { File.Delete(p); } catch { } } } } _lines.Add(""); if (_fail == 0) _lines.Add("结果:共 " + (_pass + _fail) + " 项,全部通过 ✓"); else _lines.Add("结果:共 " + (_pass + _fail) + " 项,通过 " + _pass + ",失败 " + _fail + " ✗"); string all = string.Join("\r\n", _lines.ToArray()); Console.WriteLine(all); try { File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "selftest-hash.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } } static class Program { [STAThread] static void Main(string[] args) { if (args != null && args.Length > 0 && args[0] == "--selftest") { Environment.Exit(SelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new HashToolForm()); } } }