// 文件加密 - 绿色工具箱 // 单文件零依赖(只用 .NET 自带加密库),C# 5.0 语法 // 功能:文件或整个文件夹 → 打包成单个 .gtenc 加密文件;AES-256-CBC + PBKDF2(10 万次) + HMAC-SHA256 防篡改 // 边界:不支持流式超大文件以外的特殊文件;不联网、不上传、不保存密码;忘记密码无法恢复 // 安全:先验 HMAC 再解密(错误密码/被篡改一律拒绝);解密路径做目录越界校验,防压缩包路径穿越 using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Security.Cryptography; using System.Text; using System.Windows.Forms; namespace GreenToolbox { public static class CryptOps { public static readonly byte[] Magic = new byte[] { (byte)'G', (byte)'T', (byte)'E', (byte)'N', (byte)'C', (byte)'1', 10 }; public const int SaltLen = 16; public const int IvLen = 16; public const int HmacLen = 32; public const int HeaderFixed = 7 + 1 + SaltLen + IvLen + 8; // 48 public const int Iterations = 100000; public const string Ext = ".gtenc"; public static void DeriveKeys(string password, byte[] salt, out byte[] aesKey, out byte[] macKey) { using (Rfc2898DeriveBytes d = new Rfc2898DeriveBytes(password, salt, Iterations)) { byte[] all = d.GetBytes(64); aesKey = new byte[32]; macKey = new byte[32]; Array.Copy(all, 0, aesKey, 0, 32); Array.Copy(all, 32, macKey, 0, 32); } } public static byte[] PackEntry(string name, byte[] data) { byte[] n = Encoding.UTF8.GetBytes(name == null ? "" : name); if (n.Length > 65535) throw new ArgumentException("文件名过长"); using (MemoryStream ms = new MemoryStream()) using (BinaryWriter w = new BinaryWriter(ms)) { w.Write((ushort)n.Length); w.Write(n); w.Write((long)data.Length); w.Write(data); w.Flush(); return ms.ToArray(); } } // 打包格式:重复 [路径长度 ushort][路径 UTF8][内容长度 long][内容],读到长度 0 结束 public static void PackTree(string rootDir, Stream output) { using (BinaryWriter w = new BinaryWriter(output, Encoding.UTF8, true)) { string root = Path.GetFullPath(rootDir).TrimEnd('\\', '/'); List files = new List(); CollectFiles(root, files); files.Sort(StringComparer.OrdinalIgnoreCase); foreach (string f in files) { string rel = f.Substring(root.Length).TrimStart('\\', '/').Replace('\\', '/'); byte[] n = Encoding.UTF8.GetBytes(rel); if (n.Length > 65535) continue; long len = new FileInfo(f).Length; w.Write((ushort)n.Length); w.Write(n); w.Write(len); using (FileStream fs = File.OpenRead(f)) { byte[] buf = new byte[65536]; long left = len; while (left > 0) { int read = fs.Read(buf, 0, (int)Math.Min(buf.Length, left)); if (read <= 0) break; w.Write(buf, 0, read); left -= read; } } w.Flush(); } w.Write((ushort)0); w.Flush(); } } static void CollectFiles(string dir, List into) { foreach (string f in Directory.GetFiles(dir)) { // 跳过加密文件自身,避免自己套自己 if (f.EndsWith(Ext, StringComparison.OrdinalIgnoreCase)) continue; into.Add(f); } foreach (string d in Directory.GetDirectories(dir)) CollectFiles(d, into); } // 解包到目标目录;返回解出的文件数。路径含 .. 或绝对路径一律拒绝(防穿越) public static int UnpackTree(Stream input, string destDir) { Directory.CreateDirectory(destDir); string root = Path.GetFullPath(destDir).TrimEnd('\\', '/') + "\\"; int count = 0; using (BinaryReader r = new BinaryReader(input, Encoding.UTF8, true)) { while (true) { ushort nlen; try { nlen = r.ReadUInt16(); } catch (EndOfStreamException) { break; } if (nlen == 0) break; string rel = Encoding.UTF8.GetString(r.ReadBytes(nlen)); long len = r.ReadInt64(); if (len < 0) throw new InvalidDataException("包结构损坏"); string safe = rel.Replace('/', '\\').TrimStart('\\'); if (safe.IndexOf("..", StringComparison.Ordinal) >= 0 || Path.IsPathRooted(safe)) throw new InvalidDataException("包内路径非法:" + rel); string full = Path.GetFullPath(Path.Combine(root, safe)); if (!full.StartsWith(root, StringComparison.OrdinalIgnoreCase)) throw new InvalidDataException("包内路径越界:" + rel); Directory.CreateDirectory(Path.GetDirectoryName(full)); using (FileStream fs = new FileStream(full, FileMode.Create, FileAccess.Write)) { byte[] buf = new byte[65536]; long left = len; while (left > 0) { int read = r.Read(buf, 0, (int)Math.Min(buf.Length, left)); if (read <= 0) throw new InvalidDataException("包提前结束"); fs.Write(buf, 0, read); left -= read; } } count++; } } return count; } public static string SafeFileName(string name) { if (string.IsNullOrEmpty(name)) return "未命名"; string n = name.Replace('\\', '/'); int cut = n.LastIndexOf('/'); if (cut >= 0) n = n.Substring(cut + 1); // 不能用 Path.GetFileName:文件名含 <> 时它会直接抛 char[] bad = Path.GetInvalidFileNameChars(); StringBuilder sb = new StringBuilder(); foreach (char c in n) { bool ok = true; foreach (char b in bad) if (c == b) { ok = false; break; } sb.Append(ok ? c : '_'); } string r = sb.ToString().Trim().TrimEnd('.'); return r.Length == 0 ? "未命名" : r; } // 重名时生成 "名字 (2).ext" public static string UniquePath(string dir, string fileName) { string full = Path.Combine(dir, fileName); if (!File.Exists(full) && !Directory.Exists(full)) return full; string baseName = Path.GetFileNameWithoutExtension(fileName); string ext = Path.GetExtension(fileName); for (int i = 2; i < 10000; i++) { string cand = Path.Combine(dir, baseName + " (" + i + ")" + ext); if (!File.Exists(cand) && !Directory.Exists(cand)) return cand; } return Path.Combine(dir, baseName + "_" + DateTime.Now.Ticks + ext); } public static string UniqueDir(string dir, string name) { string full = Path.Combine(dir, name); if (!Directory.Exists(full) && !File.Exists(full)) return full; for (int i = 2; i < 10000; i++) { string cand = Path.Combine(dir, name + " (" + i + ")"); if (!Directory.Exists(cand) && !File.Exists(cand)) return cand; } return Path.Combine(dir, name + "_" + DateTime.Now.Ticks); } // 加密一个文件到 targetPath,返回密文总字节 public static long EncryptFile(string srcFile, string targetPath, string password, byte[] innerNameOverride, bool isTree, byte[] treeBytes) { byte[] salt = new byte[SaltLen]; byte[] iv = new byte[IvLen]; using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) { rng.GetBytes(salt); rng.GetBytes(iv); } byte[] aesKey, macKey; DeriveKeys(password, salt, out aesKey, out macKey); byte[] headName = innerNameOverride != null ? innerNameOverride : Encoding.UTF8.GetBytes(Path.GetFileName(srcFile)); using (FileStream outFs = new FileStream(targetPath, FileMode.Create, FileAccess.ReadWrite)) { outFs.Write(Magic, 0, Magic.Length); outFs.WriteByte((byte)(isTree ? 1 : 0)); outFs.Write(salt, 0, salt.Length); outFs.Write(iv, 0, iv.Length); long lenPos = outFs.Position; outFs.Write(new byte[8], 0, 8); // 占位,稍后回填 using (RijndaelManaged aes = new RijndaelManaged()) { aes.KeySize = 256; aes.BlockSize = 128; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.Key = aesKey; aes.IV = iv; using (CryptoStream cs = new CryptoStream(outFs, aes.CreateEncryptor(), CryptoStreamMode.Write, true)) using (BinaryWriter w = new BinaryWriter(cs, Encoding.UTF8, true)) { w.Write((ushort)headName.Length); w.Write(headName); if (isTree) { w.Write((long)treeBytes.Length); w.Write(treeBytes); } else { long len = new FileInfo(srcFile).Length; w.Write(len); using (FileStream fs = File.OpenRead(srcFile)) { byte[] buf = new byte[65536]; long left = len; while (left > 0) { int read = fs.Read(buf, 0, (int)Math.Min(buf.Length, left)); if (read <= 0) break; w.Write(buf, 0, read); left -= read; } } } w.Flush(); } } // CryptoStream.Dispose 里做 FlushFinalBlock,顺序不能提前,否则 BinaryWriter 收尾时抛异常 long end = outFs.Position; long payloadLen = end - lenPos - 8; outFs.Position = lenPos; outFs.Write(BitConverter.GetBytes(payloadLen), 0, 8); outFs.Position = end; // HMAC 覆盖头部 + 密文 byte[] mac = ComputeHmac(outFs, 0, end, macKey); outFs.Write(mac, 0, mac.Length); outFs.Flush(); return outFs.Length; } } public static byte[] ComputeHmac(Stream s, long from, long to, byte[] macKey) { long save = s.Position; using (HMACSHA256 h = new HMACSHA256(macKey)) { s.Position = from; byte[] buf = new byte[65536]; long left = to - from; while (left > 0) { int read = s.Read(buf, 0, (int)Math.Min(buf.Length, left)); if (read <= 0) break; h.TransformBlock(buf, 0, read, null, 0); left -= read; } h.TransformFinalBlock(new byte[0], 0, 0); s.Position = save; return h.Hash; } } public class CryptResult { public bool Ok; public string Message = ""; public string OutputPath = ""; public long Size; public bool WasTree; } // 解密:先验 HMAC,再解密;输出到 outDir(空则同目录) public static CryptResult DecryptFile(string encFile, string outDir, string password) { CryptResult r = new CryptResult(); try { using (FileStream fs = new FileStream(encFile, FileMode.Open, FileAccess.Read)) { if (fs.Length < HeaderFixed + HmacLen + 16) { r.Message = "不是有效的加密文件(太短)"; return r; } byte[] head = new byte[HeaderFixed]; if (fs.Read(head, 0, HeaderFixed) != HeaderFixed) { r.Message = "读取头部失败"; return r; } for (int i = 0; i < Magic.Length; i++) if (head[i] != Magic[i]) { r.Message = "不是本工具生成的加密文件"; return r; } bool isTree = (head[7] & 1) == 1; byte[] salt = new byte[SaltLen]; byte[] iv = new byte[IvLen]; Array.Copy(head, 8, salt, 0, SaltLen); Array.Copy(head, 24, iv, 0, IvLen); long payloadLen = BitConverter.ToInt64(head, 40); long end = HeaderFixed + payloadLen; if (payloadLen <= 0 || end + HmacLen > fs.Length) { r.Message = "文件不完整或已损坏"; return r; } byte[] aesKey, macKey; DeriveKeys(password, salt, out aesKey, out macKey); byte[] want = new byte[HmacLen]; fs.Position = end; if (fs.Read(want, 0, HmacLen) != HmacLen) { r.Message = "读取校验码失败"; return r; } byte[] got = ComputeHmac(fs, 0, end, macKey); bool same = got.Length == want.Length; if (same) { for (int i = 0; i < got.Length; i++) if (got[i] != want[i]) { same = false; break; } } if (!same) { r.Message = "密码错误,或文件已被修改"; return r; } fs.Position = HeaderFixed; string target = string.IsNullOrEmpty(outDir) ? Path.GetDirectoryName(Path.GetFullPath(encFile)) : outDir; Directory.CreateDirectory(target); using (RijndaelManaged aes = new RijndaelManaged()) { aes.KeySize = 256; aes.BlockSize = 128; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.Key = aesKey; aes.IV = iv; using (CryptoStream cs = new CryptoStream(new LimitedStream(fs, payloadLen), aes.CreateDecryptor(), CryptoStreamMode.Read)) using (BinaryReader br = new BinaryReader(cs, Encoding.UTF8)) { ushort nlen = br.ReadUInt16(); string innerName = Encoding.UTF8.GetString(br.ReadBytes(nlen)); long dataLen = br.ReadInt64(); if (dataLen < 0) { r.Message = "内容长度非法"; return r; } if (isTree) { string dirName = SafeFileName(innerName); if (dirName.Length == 0) dirName = "解密内容"; string dest = UniqueDir(target, dirName); int n = UnpackTree(cs, dest); r.Ok = true; r.WasTree = true; r.OutputPath = dest; r.Message = "已解出 " + n + " 个文件"; r.Size = dataLen; return r; } string fname = SafeFileName(innerName); string full = UniquePath(target, fname); using (FileStream outFs = new FileStream(full, FileMode.Create, FileAccess.Write)) { byte[] buf = new byte[65536]; long left = dataLen; while (left > 0) { int read = cs.Read(buf, 0, (int)Math.Min(buf.Length, left)); if (read <= 0) { r.Message = "解密数据提前结束"; return r; } outFs.Write(buf, 0, read); left -= read; } } r.Ok = true; r.OutputPath = full; r.Size = dataLen; r.Message = "已解密"; return r; } } } } catch (CryptographicException) { r.Message = "解密失败:密码错误或文件损坏"; } catch (Exception ex) { r.Message = "解密失败:" + ex.Message; } return r; } // 只允许读限定长度的包装流,防止读到 HMAC 区间 class LimitedStream : Stream { Stream _inner; long _left; public LimitedStream(Stream inner, long len) { _inner = inner; _left = len; } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override long Length { get { return _left; } } public override long Position { get { return 0; } set { throw new NotSupportedException(); } } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { if (_left <= 0) return 0; int n = _inner.Read(buffer, offset, (int)Math.Min(count, _left)); if (n > 0) _left -= n; return n; } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } } public static string SizeText(long b) { if (b < 1024) return b + " B"; if (b < 1024 * 1024) return (b / 1024.0).ToString("0.0") + " KB"; if (b < 1024L * 1024 * 1024) return (b / 1024.0 / 1024.0).ToString("0.0") + " MB"; return (b / 1024.0 / 1024.0 / 1024.0).ToString("0.00") + " GB"; } } public class CryptForm : Form { ListBox _list; TextBox _pwd, _pwd2; CheckBox _showPwd, _keepOriginal; Button _addFiles, _addDir, _del, _clear, _enc, _dec, _openOut; ProgressBar _bar; Label _status; List _paths = new List(); public CryptForm() { Text = "文件加密 - 绿色工具箱"; ClientSize = new Size(620, 560); MinimumSize = new Size(580, 520); StartPosition = FormStartPosition.CenterScreen; Font = new Font("Microsoft YaHei UI", 9f); BackColor = Color.White; AllowDrop = true; Label title = new Label(); title.Text = "文件加密(AES-256)"; title.Font = new Font("Microsoft YaHei UI", 14f, FontStyle.Bold); title.SetBounds(16, 12, 340, 30); Label hint = new Label(); hint.Text = "文件或整个文件夹 → 打包成一个 .gtenc;密码只在你脑子里,忘了打不开。"; hint.ForeColor = Color.FromArgb(110, 110, 110); hint.SetBounds(16, 44, 580, 20); GroupBox gList = new GroupBox(); gList.Text = "要加密的文件 / 文件夹(可拖进来)"; gList.SetBounds(16, 70, 588, 250); _list = new ListBox(); _list.SetBounds(12, 24, 440, 178); _list.SelectionMode = SelectionMode.MultiExtended; _list.IntegralHeight = false; _addFiles = new Button(); _addFiles.Text = "添加文件…"; _addFiles.SetBounds(462, 24, 112, 30); _addFiles.Click += delegate { PickFiles(); }; _addDir = new Button(); _addDir.Text = "添加文件夹…"; _addDir.SetBounds(462, 60, 112, 30); _addDir.Click += delegate { PickDir(); }; _del = new Button(); _del.Text = "移除选中"; _del.SetBounds(462, 96, 112, 30); _del.Click += delegate { RemoveSelected(); }; _clear = new Button(); _clear.Text = "清空"; _clear.SetBounds(462, 132, 112, 30); _clear.Click += delegate { _paths.Clear(); RefreshList(); }; Label drop = new Label(); drop.Text = "也可以直接把文件和文件夹拖到这个窗口里"; drop.ForeColor = Color.FromArgb(140, 140, 140); drop.SetBounds(12, 208, 440, 22); GroupBox gPwd = new GroupBox(); gPwd.Text = "密码"; gPwd.SetBounds(16, 330, 588, 108); Label p1 = new Label(); p1.Text = "密码"; p1.SetBounds(14, 26, 40, 20); _pwd = new TextBox(); _pwd.SetBounds(56, 23, 300, 24); _pwd.UseSystemPasswordChar = true; Label p2 = new Label(); p2.Text = "再输一次"; p2.SetBounds(14, 60, 70, 20); _pwd2 = new TextBox(); _pwd2.SetBounds(86, 57, 270, 24); _pwd2.UseSystemPasswordChar = true; _showPwd = new CheckBox(); _showPwd.Text = "显示密码"; _showPwd.SetBounds(370, 58, 90, 22); _showPwd.CheckedChanged += delegate { _pwd.UseSystemPasswordChar = !_showPwd.Checked; _pwd2.UseSystemPasswordChar = !_showPwd.Checked; }; Label pw = new Label(); pw.Text = "至少 6 位;文件里没有后门,忘记密码谁也没法恢复"; pw.ForeColor = Color.FromArgb(150, 150, 150); pw.SetBounds(370, 26, 210, 20); _keepOriginal = new CheckBox(); _keepOriginal.Text = "加密成功后删除原文件(默认保留)"; _keepOriginal.SetBounds(16, 448, 320, 22); _enc = new Button(); _enc.Text = "加密"; _enc.SetBounds(16, 480, 130, 42); _enc.Font = new Font("Microsoft YaHei UI", 10.5f, FontStyle.Bold); _enc.BackColor = Color.FromArgb(37, 148, 92); _enc.ForeColor = Color.White; _enc.FlatStyle = FlatStyle.Flat; _enc.Click += delegate { DoEncrypt(); }; _dec = new Button(); _dec.Text = "解密"; _dec.SetBounds(158, 480, 130, 42); _dec.Font = new Font("Microsoft YaHei UI", 10.5f, FontStyle.Bold); _dec.Click += delegate { DoDecrypt(); }; _openOut = new Button(); _openOut.Text = "打开输出目录"; _openOut.SetBounds(300, 480, 130, 42); _openOut.Click += delegate { OpenOutDir(); }; _bar = new ProgressBar(); _bar.SetBounds(16, 530, 320, 8); _bar.Style = ProgressBarStyle.Marquee; _bar.Visible = false; _status = new Label(); _status.SetBounds(442, 486, 168, 40); _status.Text = "待机"; _status.ForeColor = Color.FromArgb(110, 110, 110); Controls.Add(title); Controls.Add(hint); Controls.Add(gList); Controls.Add(gPwd); Controls.Add(_keepOriginal); Controls.Add(_enc); Controls.Add(_dec); Controls.Add(_openOut); Controls.Add(_bar); Controls.Add(_status); gList.Controls.Add(_list); gList.Controls.Add(_addFiles); gList.Controls.Add(_addDir); gList.Controls.Add(_del); gList.Controls.Add(_clear); gList.Controls.Add(drop); gPwd.Controls.Add(p1); gPwd.Controls.Add(_pwd); gPwd.Controls.Add(p2); gPwd.Controls.Add(_pwd2); gPwd.Controls.Add(_showPwd); gPwd.Controls.Add(pw); // 停靠布局按 z-order 逆序计算:列表最先布局 Controls.SetChildIndex(gList, 0); Controls.SetChildIndex(gPwd, 1); Controls.SetChildIndex(_status, 2); Controls.SetChildIndex(_bar, 3); Controls.SetChildIndex(_openOut, 4); Controls.SetChildIndex(_dec, 5); Controls.SetChildIndex(_enc, 6); DragEnter += delegate(object s, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; }; DragDrop += delegate(object s, DragEventArgs e) { string[] files = e.Data.GetData(DataFormats.FileDrop) as string[]; if (files == null) return; foreach (string f in files) AddPath(f); }; } string LastOutDir = ""; void AddPath(string p) { if (string.IsNullOrEmpty(p)) return; if (!_paths.Contains(p)) _paths.Add(p); } void RefreshList() { _list.BeginUpdate(); _list.Items.Clear(); foreach (string p in _paths) { bool dir = Directory.Exists(p); _list.Items.Add((dir ? "[文件夹] " : "[文件] ") + p); } _list.EndUpdate(); _status.Text = _paths.Count == 0 ? "待机" : ("已选 " + _paths.Count + " 项"); } void PickFiles() { using (OpenFileDialog d = new OpenFileDialog()) { d.Multiselect = true; d.Filter = "所有文件|*.*"; if (d.ShowDialog(this) == DialogResult.OK) { foreach (string f in d.FileNames) AddPath(f); RefreshList(); } } } void PickDir() { using (FolderBrowserDialog d = new FolderBrowserDialog()) { d.Description = "选择要加密的文件夹(里面所有内容会打包成一个文件)"; if (d.ShowDialog(this) == DialogResult.OK) { AddPath(d.SelectedPath); RefreshList(); } } } void RemoveSelected() { List keep = new List(); for (int i = 0; i < _paths.Count; i++) { bool sel = false; foreach (int j in _list.SelectedIndices) if (j == i) { sel = true; break; } if (!sel) keep.Add(_paths[i]); } _paths = keep; RefreshList(); } void OpenOutDir() { string dir = LastOutDir; if (string.IsNullOrEmpty(dir) || !Directory.Exists(dir)) { if (_paths.Count > 0) dir = Path.GetDirectoryName(_paths[0]); } if (!string.IsNullOrEmpty(dir) && Directory.Exists(dir)) System.Diagnostics.Process.Start("explorer.exe", "\"" + dir + "\""); } bool GetPassword(bool confirm) { string p = _pwd.Text; if (p.Length < 6) { MessageBox.Show("密码至少 6 位。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); _pwd.Focus(); return false; } if (confirm && p != _pwd2.Text) { MessageBox.Show("两次输入的密码不一致。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); _pwd2.Focus(); return false; } return true; } void DoEncrypt() { if (_paths.Count == 0) { MessageBox.Show("先添加要加密的文件或文件夹。", "提示"); return; } if (!GetPassword(true)) return; string pwd = _pwd.Text; _enc.Enabled = false; _dec.Enabled = false; _bar.Visible = true; int okCount = 0; int failCount = 0; StringBuilder errs = new StringBuilder(); LastOutDir = ""; try { foreach (string p in _paths) { try { string outPath; if (Directory.Exists(p)) { string dirName = new DirectoryInfo(p).Name; byte[] tree; using (MemoryStream ms = new MemoryStream()) { CryptOps.PackTree(p, ms); tree = ms.ToArray(); } outPath = CryptOps.UniquePath(Path.GetDirectoryName(Path.GetFullPath(p)), dirName + CryptOps.Ext); CryptOps.EncryptFile(null, outPath, pwd, Encoding.UTF8.GetBytes(dirName), true, tree); if (string.IsNullOrEmpty(LastOutDir)) LastOutDir = Path.GetDirectoryName(outPath); } else if (File.Exists(p)) { if (p.EndsWith(CryptOps.Ext, StringComparison.OrdinalIgnoreCase)) throw new Exception("这已经是加密文件了"); outPath = CryptOps.UniquePath(Path.GetDirectoryName(Path.GetFullPath(p)), Path.GetFileName(p) + CryptOps.Ext); CryptOps.EncryptFile(p, outPath, pwd, null, false, null); LastOutDir = Path.GetDirectoryName(outPath); } else throw new Exception("路径不存在"); okCount++; if (_keepOriginal.Checked) { try { if (File.Exists(p)) File.Delete(p); } catch { } } } catch (Exception ex) { failCount++; errs.AppendLine(Path.GetFileName(p) + ":" + ex.Message); } } } finally { _bar.Visible = false; _enc.Enabled = true; _dec.Enabled = true; } _status.Text = "加密完成 " + okCount + (failCount > 0 ? ",失败 " + failCount : ""); if (failCount > 0) MessageBox.Show("部分项目失败:\r\n" + errs.ToString(), "结果", MessageBoxButtons.OK, MessageBoxIcon.Warning); else MessageBox.Show("加密完成,共 " + okCount + " 项。\r\n加密文件和原文件在同一目录。", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information); if (!_keepOriginal.Checked) return; _paths.RemoveAll(delegate(string p) { return !File.Exists(p) && !Directory.Exists(p); }); RefreshList(); } void DoDecrypt() { if (_paths.Count == 0) { MessageBox.Show("先添加 .gtenc 加密文件。", "提示"); return; } if (!GetPassword(false)) return; string pwd = _pwd.Text; _enc.Enabled = false; _dec.Enabled = false; _bar.Visible = true; int okCount = 0, failCount = 0; StringBuilder errs = new StringBuilder(); try { foreach (string p in _paths) { if (Directory.Exists(p)) { failCount++; errs.AppendLine(p + ":这是文件夹,不是加密文件"); continue; } CryptOps.CryptResult r = CryptOps.DecryptFile(p, Path.GetDirectoryName(Path.GetFullPath(p)), pwd); if (r.Ok) { okCount++; LastOutDir = Path.GetDirectoryName(r.OutputPath); } else { failCount++; errs.AppendLine(Path.GetFileName(p) + ":" + r.Message); } } } finally { _bar.Visible = false; _enc.Enabled = true; _dec.Enabled = true; } _status.Text = "解密完成 " + okCount + (failCount > 0 ? ",失败 " + failCount : ""); if (failCount > 0) MessageBox.Show("有 " + failCount + " 项没能解开:\r\n" + errs.ToString(), "结果", MessageBoxButtons.OK, MessageBoxIcon.Warning); else MessageBox.Show("解密完成,共 " + okCount + " 项。", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information); } } public static class CryptSelfTest { static int _pass, _fail; static List _lines = new List(); static void Check(string name, object got, object want) { bool ok = string.Equals(got == null ? "" : got.ToString(), want == null ? "" : want.ToString()); if (ok) { _pass++; _lines.Add(" [ok] " + name); } else { _fail++; _lines.Add(" [!!] " + name + " got=" + got + " want=" + want); } } public static int Run(string dir) { _pass = 0; _fail = 0; _lines = new List(); _lines.Add("文件加密 自测 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); string root = string.IsNullOrEmpty(dir) ? Path.Combine(Path.GetTempPath(), "gt-crypt") : dir; try { if (Directory.Exists(root)) Directory.Delete(root, true); Directory.CreateDirectory(root); // 1. 单文件往返 string src = Path.Combine(root, "报告 2026.txt"); string content = "hello 绿色工具箱\r\n第二行 with english and 中文混排\r\n"; File.WriteAllText(src, content, new UTF8Encoding(false)); string enc = Path.Combine(root, "报告.gtenc"); long size = CryptOps.EncryptFile(src, enc, "abc123456", null, false, null); Check("生成了加密文件", File.Exists(enc), true); Check("密文比明文大(有头与填充)", size > new FileInfo(src).Length, true); Check("密文里看不到明文", File.ReadAllText(enc, Encoding.UTF8).IndexOf("绿色工具箱") < 0, true); CryptOps.CryptResult r = CryptOps.DecryptFile(enc, Path.Combine(root, "out1"), "abc123456"); Check("解密成功", r.Ok, true); Check("还原文件名正确", Path.GetFileName(r.OutputPath), "报告 2026.txt"); Check("内容一字不差", File.ReadAllText(r.OutputPath, Encoding.UTF8), content); // 2. 密码错误 CryptOps.CryptResult bad = CryptOps.DecryptFile(enc, Path.Combine(root, "out2"), "abc123457"); Check("错密码拒绝", bad.Ok, false); Check("错密码给提示", bad.Message.IndexOf("密码") >= 0, true); Check("错密码不产生文件", Directory.Exists(Path.Combine(root, "out2")) ? Directory.GetFiles(Path.Combine(root, "out2")).Length : 0, 0); // 3. 篡改检测(改密文中间一个字节) string enc2 = Path.Combine(root, "篡改.gtenc"); File.Copy(enc, enc2, true); byte[] bytes = File.ReadAllBytes(enc2); bytes[bytes.Length - 40] ^= 0x5A; File.WriteAllBytes(enc2, bytes); CryptOps.CryptResult tam = CryptOps.DecryptFile(enc2, Path.Combine(root, "out3"), "abc123456"); Check("篡改被拒", tam.Ok, false); Check("篡改提示不可信", tam.Message.IndexOf("修改") >= 0 || tam.Message.IndexOf("损坏") >= 0, true); // 4. 空文件 string empty = Path.Combine(root, "空.txt"); File.WriteAllBytes(empty, new byte[0]); string encEmpty = Path.Combine(root, "空.gtenc"); CryptOps.EncryptFile(empty, encEmpty, "pass123456", null, false, null); CryptOps.CryptResult er = CryptOps.DecryptFile(encEmpty, Path.Combine(root, "out4"), "pass123456"); Check("空文件也能往返", er.Ok && new FileInfo(er.OutputPath).Length == 0, true); // 5. 文件夹打包往返 string tree = Path.Combine(root, "素材库"); Directory.CreateDirectory(Path.Combine(tree, "子目录")); File.WriteAllText(Path.Combine(tree, "a.txt"), "AAA", new UTF8Encoding(false)); File.WriteAllText(Path.Combine(tree, "子目录", "b.txt"), "BBB 中文", new UTF8Encoding(false)); byte[] packed; using (MemoryStream ms = new MemoryStream()) { CryptOps.PackTree(tree, ms); packed = ms.ToArray(); } Check("打包后不为空", packed.Length > 0, true); string unpackRoot = Path.Combine(root, "解包测试"); int n; using (MemoryStream ms2 = new MemoryStream(packed)) { n = CryptOps.UnpackTree(ms2, unpackRoot); } Check("解出 2 个文件", n, 2); Check("子目录结构保留", File.Exists(Path.Combine(unpackRoot, "子目录", "b.txt")), true); Check("内容保留", File.ReadAllText(Path.Combine(unpackRoot, "子目录", "b.txt"), Encoding.UTF8), "BBB 中文"); string encDir = Path.Combine(root, "素材库.gtenc"); CryptOps.EncryptFile(null, encDir, "pass123456", Encoding.UTF8.GetBytes("素材库"), true, packed); CryptOps.CryptResult dr = CryptOps.DecryptFile(encDir, Path.Combine(root, "out5"), "pass123456"); Check("文件夹解密成功", dr.Ok, true); Check("还原成目录", Directory.Exists(dr.OutputPath), true); Check("目录名还原", Path.GetFileName(dr.OutputPath), "素材库"); Check("目录内文件到位", File.Exists(Path.Combine(dr.OutputPath, "a.txt")), true); // 6. 重名不覆盖 CryptOps.CryptResult again = CryptOps.DecryptFile(enc, Path.Combine(root, "out1"), "abc123456"); Check("同名不覆盖,自动改名", Path.GetFileName(again.OutputPath), "报告 2026 (2).txt"); Check("原文件内容没被动", File.ReadAllText(Path.Combine(root, "out1", "报告 2026.txt"), Encoding.UTF8), content); // 7. 路径安全 Check("文件名消毒:去掉目录", CryptOps.SafeFileName("../../etc/passwd"), "passwd"); Check("文件名消毒:非法字符", CryptOps.SafeFileName("ac.txt").IndexOf('<') < 0, true); Check("非法包路径被拒", PackUnsafe(root), "拒绝"); // 8. 头标识 byte[] head = new byte[7]; using (FileStream fs = File.OpenRead(enc)) fs.Read(head, 0, 7); Check("魔数正确", Encoding.ASCII.GetString(head), "GTENC1\n"); Check("扩展名固定", CryptOps.Ext, ".gtenc"); Check("体积文本 KB", CryptOps.SizeText(2048), "2.0 KB"); } catch (Exception ex) { _fail++; _lines.Add(" [!!] 异常:" + ex.Message + " @ " + ex.StackTrace.Split('\n')[0]); } _lines.Add("通过 " + _pass + " / " + (_pass + _fail)); string all = string.Join("\r\n", _lines.ToArray()) + "\r\n"; Console.WriteLine(all); try { Directory.CreateDirectory(root); File.WriteAllText(Path.Combine(root, "selftest-filecrypt.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } // 构造一个含 ../ 的恶意包,验证会被拒绝 static string PackUnsafe(string root) { string bad = Path.Combine(root, "bad.bin"); using (FileStream fs = new FileStream(bad, FileMode.Create, FileAccess.Write)) using (BinaryWriter w = new BinaryWriter(fs)) { byte[] n = Encoding.UTF8.GetBytes("../escape.txt"); w.Write((ushort)n.Length); w.Write(n); w.Write((long)3); w.Write(Encoding.UTF8.GetBytes("bad")); w.Write((ushort)0); } try { using (FileStream fs = File.OpenRead(bad)) { CryptOps.UnpackTree(fs, Path.Combine(root, "unsafe_out")); } return "没拒绝"; } catch (InvalidDataException) { return "拒绝"; } } } static class Program { [STAThread] static void Main(string[] args) { if (args != null && args.Length > 0 && args[0] == "--selftest") { Environment.Exit(CryptSelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new CryptForm()); } } }