// 密码生成器 - 绿色工具箱(桌面版) // C# 5.0 语法,零依赖。用系统加密级随机数(RNGCryptoServiceProvider)+ 拒绝采样,避免取模偏差 using System; using System.Collections.Generic; using System.Drawing; using System.Globalization; using System.Security.Cryptography; using System.Text; using System.Windows.Forms; namespace GreenToolbox { // ===== 纯函数区(可自测) ===== public static class PassOps { public const string UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public const string LOWER = "abcdefghijklmnopqrstuvwxyz"; public const string DIGITS = "0123456789"; public const string SYMBOLS = "!@#$%^&*()-_=+[]{};:,.?/"; // 肉眼容易混的字符:0/O、1/l/I/|,以及引号反斜杠(复制到代码里常被转义) public const string CONFUSING = "0Oo1lI|`'\"\\"; public static string BuildAlphabet(bool upper, bool lower, bool digits, bool symbols, bool excludeConfusing) { StringBuilder sb = new StringBuilder(); if (upper) sb.Append(UPPER); if (lower) sb.Append(LOWER); if (digits) sb.Append(DIGITS); if (symbols) sb.Append(SYMBOLS); string all = sb.ToString(); if (!excludeConfusing) return all; StringBuilder filtered = new StringBuilder(); for (int i = 0; i < all.Length; i++) { if (CONFUSING.IndexOf(all[i]) < 0) filtered.Append(all[i]); } return filtered.ToString(); } // 位数:4~128。太短没意义,太长很多站点直接不让用 public static int ClampLength(int n) { if (n < 4) return 4; if (n > 128) return 128; return n; } public static int ClampCount(int n) { if (n < 1) return 1; if (n > 50) return 50; return n; } // 熵 = 长度 × log2(字符集大小)。用这个给用户一个「强不强」的客观数字 public static double EntropyBits(int alphabetSize, int length) { if (alphabetSize <= 1 || length <= 0) return 0; return length * (Math.Log(alphabetSize) / Math.Log(2)); } public static string StrengthLabel(double bits) { if (bits < 28) return "很弱"; if (bits < 40) return "弱"; if (bits < 60) return "中等"; if (bits < 80) return "强"; return "很强"; } public static string StrengthText(int alphabetSize, int length) { double b = EntropyBits(alphabetSize, length); return string.Format(CultureInfo.InvariantCulture, "字符集 {0} 个 · 约 {1:0} 位熵 · {2}", alphabetSize, b, StrengthLabel(b)); } // 每类字符至少出现一次:有人把生成的密码贴到要求「必须含数字」的站点, // 纯随机 20 位里偶尔一个数字都没有,这种坑要让工具自己兜住 public static bool HasAllClasses(string pwd, bool upper, bool lower, bool digits, bool symbols) { bool u = false, l = false, d = false, s = false; for (int i = 0; i < pwd.Length; i++) { char c = pwd[i]; if (UPPER.IndexOf(c) >= 0) u = true; else if (LOWER.IndexOf(c) >= 0) l = true; else if (DIGITS.IndexOf(c) >= 0) d = true; else s = true; } if (upper && !u) return false; if (lower && !l) return false; if (digits && !d) return false; if (symbols && !s) return false; return true; } public static bool AllInAlphabet(string pwd, string alphabet) { if (pwd == null || alphabet == null || alphabet.Length == 0) return false; for (int i = 0; i < pwd.Length; i++) { if (alphabet.IndexOf(pwd[i]) < 0) return false; } return true; } // 拒绝采样:直接 % 会偏向小数字(2^32 不能被 62 整除),密码学场景必须避免 public static int NextInt(RandomNumberGenerator rng, int maxExclusive) { if (maxExclusive <= 0) return 0; uint limit = uint.MaxValue - (uint.MaxValue % (uint)maxExclusive); byte[] buf = new byte[4]; while (true) { rng.GetBytes(buf); uint v = BitConverter.ToUInt32(buf, 0); if (v < limit) return (int)(v % (uint)maxExclusive); } } public static string Generate(RandomNumberGenerator rng, int length, string alphabet, bool upper, bool lower, bool digits, bool symbols) { length = ClampLength(length); if (alphabet.Length == 0) return ""; // 修一轮可能把另一类唯一的字符盖掉(4 位四类全开时尤其容易), // 所以修完要校验,不行就重来;20 次都不行就走兜底 for (int attempt = 0; attempt < 20; attempt++) { char[] pwd = new char[length]; for (int i = 0; i < length; i++) pwd[i] = alphabet[NextInt(rng, alphabet.Length)]; RepairClasses(pwd, alphabet, upper, lower, digits, symbols, rng); string s = new string(pwd); if (HasAllClasses(s, upper, lower, digits, symbols)) return Shuffle(pwd, rng); } // 兜底:每类固定占一位(互不重叠),其余位置随机填,最后打乱。 // 打乱不改变字符组成,所以这个结果一定四类齐全 string[] required = new string[4]; int need = 0; if (upper) required[need++] = UPPER; if (lower) required[need++] = LOWER; if (digits) required[need++] = DIGITS; if (symbols) required[need++] = SYMBOLS; char[] fb = new char[length]; for (int i = 0; i < length; i++) fb[i] = alphabet[NextInt(rng, alphabet.Length)]; for (int k = 0; k < need && k < length; k++) { List avail = new List(); for (int i = 0; i < required[k].Length; i++) if (alphabet.IndexOf(required[k][i]) >= 0) avail.Add(required[k][i]); if (avail.Count > 0) fb[k] = avail[NextInt(rng, avail.Count)]; } return Shuffle(fb, rng); } private static string Shuffle(char[] pwd, RandomNumberGenerator rng) { for (int i = pwd.Length - 1; i > 0; i--) { int j = NextInt(rng, i + 1); char t = pwd[i]; pwd[i] = pwd[j]; pwd[j] = t; } return new string(pwd); } private static void RepairClasses(char[] pwd, string alphabet, bool upper, bool lower, bool digits, bool symbols, RandomNumberGenerator rng) { string[] required = new string[4]; int need = 0; if (upper) required[need++] = UPPER; if (lower) required[need++] = LOWER; if (digits) required[need++] = DIGITS; if (symbols) required[need++] = SYMBOLS; for (int k = 0; k < need && k < pwd.Length; k++) { string cls = required[k]; // 该类字符可能被「排除易混淆」全滤掉了,那就别强求 List avail = new List(); for (int i = 0; i < cls.Length; i++) if (alphabet.IndexOf(cls[i]) >= 0) avail.Add(cls[i]); if (avail.Count == 0) continue; bool have = false; for (int i = 0; i < pwd.Length; i++) if (avail.Contains(pwd[i])) { have = true; break; } if (have) continue; pwd[k] = avail[NextInt(rng, avail.Count)]; } } } public class PassForm : Form { private static readonly Color COL_GREEN = Color.FromArgb(0, 145, 88); private static readonly Color COL_GRAY = Color.FromArgb(120, 130, 124); private static readonly Color COL_LINE = Color.FromArgb(224, 230, 226); private NumericUpDown numLen, numCount; private CheckBox chkUpper, chkLower, chkDigits, chkSymbols, chkEasy; private ListBox list; private Label lblStrength, lblTip; private RandomNumberGenerator rng = RandomNumberGenerator.Create(); public PassForm() { InitUi(); RefreshStrength(); } private void InitUi() { this.Text = "密码生成器 - 绿色工具箱"; this.Font = new Font("Microsoft YaHei UI", 9.5f); this.BackColor = Color.White; this.ForeColor = Color.FromArgb(34, 40, 36); this.ClientSize = new Size(620, 520); this.MinimumSize = new Size(560, 470); this.StartPosition = FormStartPosition.CenterScreen; int x = 18, y = 14; Label l0 = new Label(); l0.Text = "用系统加密级随机数生成密码,不联网、不保存、关掉即无痕。"; l0.AutoSize = true; l0.ForeColor = COL_GRAY; l0.Location = new Point(x, y); this.Controls.Add(l0); y += 30; Label l1 = new Label(); l1.Text = "长度"; l1.AutoSize = true; l1.Location = new Point(x, y + 5); this.Controls.Add(l1); numLen = new NumericUpDown(); numLen.Minimum = 4; numLen.Maximum = 128; numLen.Value = 16; numLen.Location = new Point(x + 44, y + 2); numLen.Size = new Size(70, 26); numLen.ValueChanged += delegate { RefreshStrength(); }; this.Controls.Add(numLen); Label l2 = new Label(); l2.Text = "生成条数"; l2.AutoSize = true; l2.Location = new Point(x + 132, y + 5); this.Controls.Add(l2); numCount = new NumericUpDown(); numCount.Minimum = 1; numCount.Maximum = 50; numCount.Value = 5; numCount.Location = new Point(x + 206, y + 2); numCount.Size = new Size(60, 26); this.Controls.Add(numCount); y += 38; chkUpper = AddCheck("大写 A-Z", x, y, true); chkLower = AddCheck("小写 a-z", x + 110, y, true); chkDigits = AddCheck("数字 0-9", x + 220, y, true); chkSymbols = AddCheck("符号 !@#", x + 330, y, true); chkEasy = AddCheck("排除易混字符 0O1lI|", x, y + 28, true); y += 66; Button btnGen = new Button(); btnGen.Text = "生成"; btnGen.Location = new Point(x, y); btnGen.Size = new Size(100, 34); btnGen.BackColor = COL_GREEN; btnGen.ForeColor = Color.White; btnGen.FlatStyle = FlatStyle.Flat; btnGen.FlatAppearance.BorderSize = 0; btnGen.Click += new EventHandler(GenClick); this.Controls.Add(btnGen); Button btnCopyAll = new Button(); btnCopyAll.Text = "复制全部"; btnCopyAll.Location = new Point(x + 110, y); btnCopyAll.Size = new Size(100, 34); btnCopyAll.FlatStyle = FlatStyle.Flat; btnCopyAll.FlatAppearance.BorderColor = COL_LINE; btnCopyAll.Click += new EventHandler(CopyAllClick); this.Controls.Add(btnCopyAll); Button btnCopyOne = new Button(); btnCopyOne.Text = "复制选中"; btnCopyOne.Location = new Point(x + 220, y); btnCopyOne.Size = new Size(100, 34); btnCopyOne.FlatStyle = FlatStyle.Flat; btnCopyOne.FlatAppearance.BorderColor = COL_LINE; btnCopyOne.Click += new EventHandler(CopyOneClick); this.Controls.Add(btnCopyOne); y += 46; lblStrength = new Label(); lblStrength.Text = ""; lblStrength.AutoSize = true; lblStrength.ForeColor = COL_GREEN; lblStrength.Location = new Point(x, y); this.Controls.Add(lblStrength); y += 26; list = new ListBox(); list.Location = new Point(x, y); list.Size = new Size(566, 250); list.Font = new Font("Consolas", 11f); list.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom; list.HorizontalScrollbar = true; list.DoubleClick += new EventHandler(CopyOneClick); this.Controls.Add(list); y += 258; lblTip = new Label(); lblTip.Text = "提示:双击某条即复制。密码不会写到磁盘,关掉窗口就没了。"; lblTip.AutoSize = false; lblTip.Size = new Size(566, 22); lblTip.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; lblTip.ForeColor = COL_GRAY; lblTip.Location = new Point(x, y); this.Controls.Add(lblTip); } private CheckBox AddCheck(string text, int x, int y, bool on) { CheckBox cb = new CheckBox(); cb.Text = text; cb.AutoSize = true; cb.Checked = on; cb.Location = new Point(x, y); cb.ForeColor = Color.FromArgb(60, 68, 64); cb.CheckedChanged += delegate { RefreshStrength(); }; this.Controls.Add(cb); return cb; } private string Alphabet() { return PassOps.BuildAlphabet(chkUpper.Checked, chkLower.Checked, chkDigits.Checked, chkSymbols.Checked, chkEasy.Checked); } private void RefreshStrength() { string alpha = Alphabet(); if (alpha.Length == 0) { lblStrength.Text = "至少勾一种字符类型"; lblStrength.ForeColor = Color.FromArgb(190, 70, 60); return; } lblStrength.ForeColor = COL_GREEN; lblStrength.Text = PassOps.StrengthText(alpha.Length, (int)numLen.Value); } private void GenClick(object sender, EventArgs e) { string alpha = Alphabet(); if (alpha.Length == 0) { MessageBox.Show("至少勾一种字符类型,比如「小写 a-z」。", "没有字符可选", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } int len = PassOps.ClampLength((int)numLen.Value); int count = PassOps.ClampCount((int)numCount.Value); list.BeginUpdate(); list.Items.Clear(); for (int i = 0; i < count; i++) { list.Items.Add(PassOps.Generate(rng, len, alpha, chkUpper.Checked, chkLower.Checked, chkDigits.Checked, chkSymbols.Checked)); } list.EndUpdate(); RefreshStrength(); } private void CopyAllClick(object sender, EventArgs e) { if (list.Items.Count == 0) { MessageBox.Show("先点「生成」。", "还没有密码", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < list.Items.Count; i++) { if (i > 0) sb.AppendLine(); sb.Append(list.Items[i].ToString()); } try { Clipboard.SetText(sb.ToString()); lblTip.Text = "已复制 " + list.Items.Count + " 条到剪贴板。"; } catch { lblTip.Text = "复制失败:剪贴板被别的程序占用。"; } } private void CopyOneClick(object sender, EventArgs e) { if (list.SelectedItem == null) return; try { Clipboard.SetText(list.SelectedItem.ToString()); lblTip.Text = "已复制选中的那一条。"; } catch { lblTip.Text = "复制失败:剪贴板被别的程序占用。"; } } } public static class PassSelfTest { private static int _pass = 0; private static int _fail = 0; private static List _lines = new List(); private static string Esc(string s) { if (s == null) return ""; 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) + "]"); } } private static void CheckTrue(string name, bool ok, string detail) { Check(name, ok ? "yes" : "no", "yes"); if (!ok && detail != null) _lines.Add(" 详情:" + Esc(detail)); } public static int Run(string dir) { try { _lines.Add("密码生成器 自测"); // ── 字符集组合 ── Check("只要小写", PassOps.BuildAlphabet(false, true, false, false, false), PassOps.LOWER); Check("只要数字", PassOps.BuildAlphabet(false, false, true, false, false), "0123456789"); Check("大小写+数字的长度", PassOps.BuildAlphabet(true, true, true, false, false).Length.ToString(), "62"); Check("四类全开长度", PassOps.BuildAlphabet(true, true, true, true, false).Length.ToString(), (62 + PassOps.SYMBOLS.Length).ToString()); Check("全不勾是空串", PassOps.BuildAlphabet(false, false, false, false, false), ""); CheckTrue("排除易混后不含 0", PassOps.BuildAlphabet(true, true, true, false, true).IndexOf('0') < 0, null); CheckTrue("排除易混后不含 O", PassOps.BuildAlphabet(true, true, true, false, true).IndexOf('O') < 0, null); CheckTrue("排除易混后不含 1lI", PassOps.BuildAlphabet(true, true, true, false, true).IndexOf('1') < 0 && PassOps.BuildAlphabet(true, true, true, false, true).IndexOf('l') < 0 && PassOps.BuildAlphabet(true, true, true, false, true).IndexOf('I') < 0, null); CheckTrue("排除易混后不含引号反斜杠", PassOps.BuildAlphabet(true, true, true, true, true).IndexOf('\\') < 0, null); Check("排除后剩 8 个数字(0 和 1 被排除)", (PassOps.BuildAlphabet(false, false, true, false, true).Length).ToString(), "8"); Check("排除后小写剩 24 个", (PassOps.BuildAlphabet(false, true, false, false, true).Length).ToString(), "24"); // ── 长度/条数夹取 ── Check("长度下限 4", PassOps.ClampLength(1).ToString(), "4"); Check("长度上限 128", PassOps.ClampLength(999).ToString(), "128"); Check("正常长度不动", PassOps.ClampLength(16).ToString(), "16"); Check("条数下限 1", PassOps.ClampCount(0).ToString(), "1"); Check("条数上限 50", PassOps.ClampCount(500).ToString(), "50"); // ── 熵与强度 ── Check("62 字符集 16 位约 95 位熵", PassOps.EntropyBits(62, 16).ToString("0.0", CultureInfo.InvariantCulture), "95.3"); Check("8 位小写约 37.6 位熵", PassOps.EntropyBits(26, 8).ToString("0.0", CultureInfo.InvariantCulture), "37.6"); Check("熵为 0 的边界", PassOps.EntropyBits(1, 10).ToString("0.0", CultureInfo.InvariantCulture), "0.0"); Check("很弱", PassOps.StrengthLabel(20), "很弱"); Check("弱", PassOps.StrengthLabel(35), "弱"); Check("中等", PassOps.StrengthLabel(50), "中等"); Check("强", PassOps.StrengthLabel(70), "强"); Check("很强", PassOps.StrengthLabel(90), "很强"); CheckTrue("强度文案含熵值", PassOps.StrengthText(62, 16).Contains("95"), PassOps.StrengthText(62, 16)); // ── 随机数:范围与分布 ── RandomNumberGenerator rng = RandomNumberGenerator.Create(); bool inRange = true; for (int i = 0; i < 2000; i++) { int v = PassOps.NextInt(rng, 62); if (v < 0 || v > 61) { inRange = false; break; } } CheckTrue("NextInt 永远落在 [0,62)", inRange, null); Check("NextInt(1) 恒为 0", PassOps.NextInt(rng, 1).ToString(), "0"); // 分布检查:每个桶都该被摸到(1000 次抽 10 桶,漏桶概率极低) int[] buckets = new int[10]; for (int i = 0; i < 1000; i++) buckets[PassOps.NextInt(rng, 10)]++; int empty = 0; for (int i = 0; i < buckets.Length; i++) if (buckets[i] == 0) empty++; CheckTrue("10 个桶全被覆盖(无取模偏差导致的偏科)", empty == 0, "空桶数 " + empty); // ── 生成结果约束 ── string alpha = PassOps.BuildAlphabet(true, true, true, true, true); string p1 = PassOps.Generate(rng, 16, alpha, true, true, true, true); Check("生成长度正确", p1.Length.ToString(), "16"); CheckTrue("每个字符都在字符集内", PassOps.AllInAlphabet(p1, alpha), p1); CheckTrue("四类齐全", PassOps.HasAllClasses(p1, true, true, true, true), p1); // 跑 200 次,确认类别补齐一直有效(这是最容易漏的边界) int bad = 0; for (int i = 0; i < 200; i++) { string g = PassOps.Generate(rng, 8, alpha, true, true, true, true); if (!PassOps.HasAllClasses(g, true, true, true, true)) bad++; } Check("200 次生成全都四类齐全", bad.ToString(), "0"); // 短密码(4 位)也要能补齐四类 string p4 = PassOps.Generate(rng, 4, alpha, true, true, true, true); CheckTrue("4 位也能四类齐全", PassOps.HasAllClasses(p4, true, true, true, true), p4); // 打乱有效:前 4 位不该总是「一大写一小写一数字一符号」的固定顺序 int samePrefix = 0; for (int i = 0; i < 30; i++) { string g = PassOps.Generate(rng, 8, alpha, true, true, true, true); bool u = PassOps.UPPER.IndexOf(g[0]) >= 0; bool l = PassOps.LOWER.IndexOf(g[1]) >= 0; bool d = PassOps.DIGITS.IndexOf(g[2]) >= 0; if (u && l && d) samePrefix++; } CheckTrue("前三位不是固定类别顺序", samePrefix < 5, "出现 " + samePrefix + " 次"); // 只要数字时不该冒出字母 string onlyDigits = PassOps.BuildAlphabet(false, false, true, false, false); string pd = PassOps.Generate(rng, 20, onlyDigits, false, false, true, false); CheckTrue("只勾数字时结果全数字", PassOps.AllInAlphabet(pd, "0123456789"), pd); // 两次生成不该相同(100 位密码碰撞概率可忽略) string a = PassOps.Generate(rng, 100, alpha, true, true, true, true); string b = PassOps.Generate(rng, 100, alpha, true, true, true, true); CheckTrue("两次生成不相同", a != b, null); // ── 类别判定本身 ── CheckTrue("纯字母不含数字被识别", !PassOps.HasAllClasses("abcDEF", true, true, true, false), null); CheckTrue("空密码不算齐全", !PassOps.HasAllClasses("", true, false, false, false), null); CheckTrue("空字符集判定为不在集合内", !PassOps.AllInAlphabet("a", ""), null); CheckTrue("null 不崩", !PassOps.AllInAlphabet(null, PassOps.LOWER), null); } catch (Exception ex) { _fail++; _lines.Add(" [!!] 自测中途异常:" + ex.GetType().Name + " " + ex.Message); } _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 { System.IO.File.WriteAllText( System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "selftest-passgen.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } } public static class PassProgram { [STAThread] public static void Main(string[] args) { if (args != null && args.Length > 0 && args[0] == "--selftest") { Environment.Exit(PassSelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new PassForm()); } } }