当前位置: 首页 > backend >正文

C#写破解rar文件密码例程

1.

2.程序

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Windows.Forms;
using SharpCompress.Archives;
using SharpCompress.Archives.Rar;
using SharpCompress.Common;
using SharpCompress.Readers;namespace RarPasswordRecovery
{public partial class MainForm : Form{private BackgroundWorker worker;private long totalPasswords;private long testedPasswords;private Stopwatch stopwatch;private List<string> passwordList;private bool passwordFound;private string foundPassword;private bool isRunning;public MainForm(){InitializeComponent();InitializeBackgroundWorker();SetupUI();}private void InitializeBackgroundWorker(){worker = new BackgroundWorker{WorkerReportsProgress = true,WorkerSupportsCancellation = true};worker.DoWork += Worker_DoWork;worker.ProgressChanged += Worker_ProgressChanged;worker.RunWorkerCompleted += Worker_RunWorkerCompleted;}private void SetupUI(){// 设置窗体this.Text = "RAR密码恢复工具";this.Size = new Size(800, 500);this.MinimumSize = new Size(600, 400);this.BackColor = Color.FromArgb(45, 45, 65);this.ForeColor = Color.White;this.FormBorderStyle = FormBorderStyle.FixedSingle;this.StartPosition = FormStartPosition.CenterScreen;// 创建控件CreateControls();}private void CreateControls(){// 标题标签Label titleLabel = new Label{Text = "RAR压缩文件密码恢复",Font = new Font("Segoe UI", 16, FontStyle.Bold),AutoSize = true,Location = new Point(20, 15),ForeColor = Color.LightSkyBlue};this.Controls.Add(titleLabel);// RAR文件选择Label lblRarFile = new Label{Text = "RAR文件路径:",Location = new Point(20, 60),AutoSize = true};this.Controls.Add(lblRarFile);TextBox txtRarFilePath = new TextBox{Location = new Point(120, 57),Size = new Size(500, 25),Name = "txtRarFilePath",ReadOnly = true};this.Controls.Add(txtRarFilePath);Button btnBrowseRar = new Button{Text = "浏览...",Location = new Point(630, 55),Size = new Size(80, 25),Name = "btnBrowseRar",BackColor = Color.FromArgb(70, 70, 90),ForeColor = Color.White,FlatStyle = FlatStyle.Flat};btnBrowseRar.FlatAppearance.BorderSize = 0;btnBrowseRar.Click += BtnBrowseRar_Click;this.Controls.Add(btnBrowseRar);// 字典文件选择Label lblDictionary = new Label{Text = "密码字典文件:",Location = new Point(20, 100),AutoSize = true};this.Controls.Add(lblDictionary);TextBox txtDictionaryPath = new TextBox{Location = new Point(120, 97),Size = new Size(500, 25),Name = "txtDictionaryPath",ReadOnly = true};this.Controls.Add(txtDictionaryPath);Button btnBrowseDict = new Button{Text = "浏览...",Location = new Point(630, 95),Size = new Size(80, 25),Name = "btnBrowseDict",BackColor = Color.FromArgb(70, 70, 90),ForeColor = Color.White,FlatStyle = FlatStyle.Flat};btnBrowseDict.FlatAppearance.BorderSize = 0;btnBrowseDict.Click += BtnBrowseDict_Click;this.Controls.Add(btnBrowseDict);// 进度条ProgressBar progressBar = new ProgressBar{Location = new Point(20, 150),Size = new Size(690, 25),Name = "progressBar",Style = ProgressBarStyle.Continuous};this.Controls.Add(progressBar);// 状态标签Label lblStatus = new Label{Location = new Point(20, 185),Size = new Size(690, 20),Name = "lblStatus",Text = "就绪",TextAlign = ContentAlignment.MiddleLeft};this.Controls.Add(lblStatus);// 统计信息Label lblTotal = new Label{Location = new Point(20, 215),Size = new Size(200, 20),Name = "lblTotalPasswords",Text = "总密码数: 0"};this.Controls.Add(lblTotal);Label lblTested = new Label{Location = new Point(230, 215),Size = new Size(200, 20),Name = "lblTested",Text = "已尝试: 0"};this.Controls.Add(lblTested);Label lblSpeed = new Label{Location = new Point(440, 215),Size = new Size(200, 20),Name = "lblSpeed",Text = "速度: 0 p/s"};this.Controls.Add(lblSpeed);// 时间信息Label lblElapsed = new Label{Location = new Point(20, 245),Size = new Size(200, 20),Name = "lblElapsed",Text = "已用时间: 00:00:00"};this.Controls.Add(lblElapsed);Label lblRemaining = new Label{Location = new Point(230, 245),Size = new Size(200, 20),Name = "lblRemaining",Text = "剩余时间: --:--:--"};this.Controls.Add(lblRemaining);// 当前尝试密码Label lblCurrent = new Label{Text = "当前尝试密码:",Location = new Point(20, 280),AutoSize = true};this.Controls.Add(lblCurrent);TextBox txtCurrentPassword = new TextBox{Location = new Point(120, 277),Size = new Size(500, 25),Name = "txtCurrentPassword",ReadOnly = true,Font = new Font("Consolas", 10),BackColor = Color.FromArgb(30, 30, 40),ForeColor = Color.LightGreen};this.Controls.Add(txtCurrentPassword);// 按钮Button btnStart = new Button{Text = "开始恢复",Location = new Point(200, 320),Size = new Size(120, 35),Name = "btnStart",BackColor = Color.SeaGreen,FlatStyle = FlatStyle.Flat,Font = new Font("Segoe UI", 10, FontStyle.Bold)};btnStart.FlatAppearance.BorderSize = 0;btnStart.Click += BtnStart_Click;this.Controls.Add(btnStart);Button btnCancel = new Button{Text = "取消",Location = new Point(340, 320),Size = new Size(120, 35),Name = "btnCancel",Enabled = false,BackColor = Color.IndianRed,FlatStyle = FlatStyle.Flat,Font = new Font("Segoe UI", 10)};btnCancel.FlatAppearance.BorderSize = 0;btnCancel.Click += BtnCancel_Click;this.Controls.Add(btnCancel);// 法律声明LinkLabel linkLegal = new LinkLabel{Text = "使用条款和道德声明",Location = new Point(20, 370),AutoSize = true,LinkColor = Color.LightSkyBlue,ActiveLinkColor = Color.Cyan};linkLegal.LinkClicked += LinkLegal_LinkClicked;this.Controls.Add(linkLegal);// 状态图标PictureBox statusIcon = new PictureBox{Location = new Point(650, 320),Size = new Size(60, 60),SizeMode = PictureBoxSizeMode.Zoom};// 注意:在实际项目中,您需要添加自己的图标statusIcon.BackColor = Color.Transparent;this.Controls.Add(statusIcon);}private void BtnBrowseRar_Click(object sender, EventArgs e){using (OpenFileDialog openFileDialog = new OpenFileDialog()){openFileDialog.Filter = "RAR files (*.rar)|*.rar|All files (*.*)|*.*";openFileDialog.Title = "选择RAR文件";if (openFileDialog.ShowDialog() == DialogResult.OK){GetTextBox("txtRarFilePath").Text = openFileDialog.FileName;}}}private void BtnBrowseDict_Click(object sender, EventArgs e){using (OpenFileDialog openFileDialog = new OpenFileDialog()){openFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";openFileDialog.Title = "选择密码字典文件";if (openFileDialog.ShowDialog() == DialogResult.OK){GetTextBox("txtDictionaryPath").Text = openFileDialog.FileName;}}}private void BtnStart_Click(object sender, EventArgs e){TextBox txtRarFilePath = GetTextBox("txtRarFilePath");TextBox txtDictionaryPath = GetTextBox("txtDictionaryPath");if (string.IsNullOrWhiteSpace(txtRarFilePath.Text)){MessageBox.Show("请选择RAR文件", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);return;}if (string.IsNullOrWhiteSpace(txtDictionaryPath.Text)){MessageBox.Show("请选择密码字典文件", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);return;}if (!File.Exists(txtRarFilePath.Text)){MessageBox.Show("选择的RAR文件不存在", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);return;}if (!File.Exists(txtDictionaryPath.Text)){MessageBox.Show("选择的字典文件不存在", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);return;}// 重置UIpasswordFound = false;foundPassword = null;testedPasswords = 0;isRunning = true;GetProgressBar().Value = 0;GetLabel("lblStatus").Text = "加载密码字典...";GetLabel("lblTested").Text = "已尝试: 0";GetLabel("lblSpeed").Text = "速度: 0 p/s";GetLabel("lblElapsed").Text = "已用时间: 00:00:00";GetLabel("lblRemaining").Text = "剩余时间: --:--:--";GetTextBox("txtCurrentPassword").Text = "";GetButton("btnStart").Enabled = false;GetButton("btnCancel").Enabled = true;try{// 读取字典文件passwordList = File.ReadAllLines(txtDictionaryPath.Text).Where(p => !string.IsNullOrWhiteSpace(p)).Distinct().ToList();totalPasswords = passwordList.Count;if (totalPasswords == 0){MessageBox.Show("字典文件为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);ResetUI();return;}GetLabel("lblTotalPasswords").Text = $"总密码数: {totalPasswords:N0}";stopwatch = Stopwatch.StartNew();worker.RunWorkerAsync();}catch (Exception ex){MessageBox.Show($"读取字典文件错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);ResetUI();}}private void Worker_DoWork(object sender, DoWorkEventArgs e){BackgroundWorker worker = sender as BackgroundWorker;passwordFound = false;foundPassword = null;string rarFilePath = GetTextBox("txtRarFilePath").Text;try{// 尝试每个密码for (int i = 0; i < passwordList.Count; i++){if (worker.CancellationPending){e.Cancel = true;return;}string password = passwordList[i];testedPasswords++;try{// 修复:使用ReaderOptions传递密码var options = new ReaderOptions{Password = password,LookForHeader = true,DisableCheckIncomplete = true};// 尝试打开压缩文件using (var archive = RarArchive.Open(rarFilePath, options)){// 尝试访问第一个文件var entry = archive.Entries.FirstOrDefault();if (entry != null){// 尝试读取少量数据using (var stream = entry.OpenEntryStream()){byte[] buffer = new byte[10];stream.Read(buffer, 0, buffer.Length);// 如果成功读取数据,密码正确passwordFound = true;foundPassword = password;return;}}}}catch (SharpCompress.Common.CryptographicException){// 密码错误,继续尝试}catch (InvalidFormatException){// 密码错误或文件格式问题}catch (Exception ex){// 其他错误,记录并继续尝试worker.ReportProgress(0, $"密码 '{password}' 尝试失败: {ex.Message}");}// 每100次尝试报告一次进度if (testedPasswords % 100 == 0){int progress = (int)((double)testedPasswords / totalPasswords * 100);worker.ReportProgress(progress, password);}}}catch (Exception ex){worker.ReportProgress(0, $"错误: {ex.Message}");}}private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e){if (e.UserState is string currentPassword){GetTextBox("txtCurrentPassword").Text = currentPassword;}GetProgressBar().Value = e.ProgressPercentage;GetLabel("lblTested").Text = $"已尝试: {testedPasswords:N0} / {totalPasswords:N0}";// 计算速度double seconds = stopwatch.Elapsed.TotalSeconds;double passwordsPerSecond = seconds > 0 ? testedPasswords / seconds : 0;GetLabel("lblSpeed").Text = $"速度: {passwordsPerSecond:N1} p/s";// 计算剩余时间if (passwordsPerSecond > 0){long remaining = totalPasswords - testedPasswords;TimeSpan remainingTime = TimeSpan.FromSeconds(remaining / passwordsPerSecond);GetLabel("lblRemaining").Text = $"剩余时间: {remainingTime:hh\\:mm\\:ss}";}GetLabel("lblElapsed").Text = $"已用时间: {stopwatch.Elapsed:hh\\:mm\\:ss}";GetLabel("lblStatus").Text = "正在尝试恢复密码...";}private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e){stopwatch.Stop();isRunning = false;if (e.Cancelled){GetLabel("lblStatus").Text = "操作已取消";}else if (e.Error != null){GetLabel("lblStatus").Text = $"错误: {e.Error.Message}";}else if (passwordFound){GetLabel("lblStatus").Text = "密码已找到!";GetTextBox("txtCurrentPassword").Text = foundPassword;GetTextBox("txtCurrentPassword").ForeColor = Color.Lime;MessageBox.Show($"密码已找到: {foundPassword}", "成功",MessageBoxButtons.OK, MessageBoxIcon.Information);}else{GetLabel("lblStatus").Text = "在字典中未找到密码";GetTextBox("txtCurrentPassword").Text = "未找到匹配的密码";}GetButton("btnStart").Enabled = true;GetButton("btnCancel").Enabled = false;}private void BtnCancel_Click(object sender, EventArgs e){if (worker.IsBusy){worker.CancelAsync();GetButton("btnCancel").Enabled = false;GetLabel("lblStatus").Text = "正在取消操作...";}}private void LinkLegal_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e){MessageBox.Show("本工具仅供教育目的使用\n\n" +"仅限您合法拥有的文件使用\n\n" +"未经授权访问他人文件是违法行为\n\n" +"使用本工具即表示您同意承担所有责任","法律和道德声明",MessageBoxButtons.OK,MessageBoxIcon.Information);}private void ResetUI(){GetButton("btnStart").Enabled = true;GetButton("btnCancel").Enabled = false;}// Helper methods to get controls by nameprivate TextBox GetTextBox(string name) => this.Controls.Find(name, true).FirstOrDefault() as TextBox;private Label GetLabel(string name) => this.Controls.Find(name, true).FirstOrDefault() as Label;private Button GetButton(string name) => this.Controls.Find(name, true).FirstOrDefault() as Button;private ProgressBar GetProgressBar() => this.Controls.Find("progressBar", true).FirstOrDefault() as ProgressBar;}
}

http://www.xdnf.cn/news/14765.html

相关文章:

  • 【硬核数学】10. “价值标尺”-损失函数:信息论如何设计深度学习的损失函数《从零构建机器学习、深度学习到LLM的数学认知》
  • Android大图加载优化:BitmapRegionDecoder深度解析与实战
  • IDE/IoT/实践小熊派LiteOS工程配置、编译、烧录、调试(基于 bearpi-iot_std_liteos 源码)
  • 马斯克的 Neuralink:当意念突破肉体的边界,未来已来
  • 同步日志系统深度解析【链式调用】【宏定义】【固定缓冲区】【线程局部存储】【RAII】
  • 《汇编语言:基于X86处理器》第5章 过程(2)
  • C# 委托(为委托添加方法和从委托移除方法)
  • 暑假复习篇之类与对象
  • gantt-task-react的改造使用
  • 源码运行效果图(六)
  • cocos creator 3.8 - 精品源码 - 六边形消消乐(六边形叠叠乐、六边形堆叠战士)
  • 《自动控制原理 》- 第 1 章 自动控制的基本原理与方式
  • 计算机操作系统(十七)内存管理
  • OpenCV图像噪点消除五大滤波方法
  • 能否仅用两台服务器实现集群的高可用性??
  • 创建套接字时和填充地址时指定类型的异同
  • 【LeetCode 热题 100】438. 找到字符串中所有字母异位词——(解法三)不定长滑动窗口+数组
  • 使用docker编译onlyoffice server 8.2.2 成功版 含踩坑记录
  • C++ STL深度剖析:Stack、queue、deque容器适配器核心接口
  • FDA IND审评流程及临床研究暂停要点
  • Ubuntu20.04离线安装Realtek b852无线网卡驱动
  • Java基础(Maven配置)
  • Vue工程化实现约定式路由自动注册
  • 汇总表支持表头分组,查询组件查询框可以调整高度,DataEase开源BI工具v2.10.11 LTS版本发布
  • Linux基本指令篇 —— tac指令
  • 基于JavaWeb的校园失物招领系统设计与实现
  • C++11 <chrono> 库特性:从入门到精通
  • 在shell中直接调用使用R
  • Spring Boot整合Redis指南
  • 强化学习理论基础:从Q-learning到PPO的算法演进(2)