从命令行参数获取哈希

本文关键字:哈希 获取 参数 命令行 | 更新日期: 2023-09-27 18:36:59

我正在尝试创建一个控制台或表单,您可以在其中将文件拖到各自的.exe程序将获取该文件并对其进行哈希处理,然后将剪贴板文本设置为预先生成的哈希。

这是我的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Windows.Forms;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        string path = args[0];          
        StreamReader wer = new StreamReader(path.ToString());
        wer.ReadToEnd();
        string qwe = wer.ToString();
        string ert = Hash(qwe);
        string password = "~" + ert + "~";
        Clipboard.SetText(password);
    }
    static public string Hash(string input)
    {
        MD5 md5 = MD5.Create();
        byte[] inputBytes = Encoding.ASCII.GetBytes(input);
        byte[] hash = md5.ComputeHash(inputBytes);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hash.Length; i++)
        {
            sb.Append(hash[i].ToString("X2"));
        }
        return sb.ToString();
    }
}
}

当我从发行版中获取单个.exe并将文件拖到上面时,我收到某种线程错误 - 我无法提供它,因为它在控制台中,而不是在 vb2010 中。感谢您的任何帮助

从命令行参数获取哈希

剪贴板 API 在内部使用 OLE,因此只能在 STA 线程上调用。与 WinForms 应用程序不同,控制台应用程序默认不使用 STA。

[STAThread] 属性添加到Main

[STAThread]
static void Main(string[] args)
{
    ...

只需按照异常消息告诉您的操作即可:

未处理的异常:System.Threading.ThreadStateException:当前线程必须 设置为单线程单元 (STA) 模式,然后才能进行 OLE 调用。确保您的 Main 函数已标记STAThreadAttribute


稍微清理一下程序:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Windows.Forms;
namespace HashToClipboard
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            string hexHash = Hash(args[0]);
            string password = "~" + hexHash + "~";
            Clipboard.SetText(password);
        }
        static public string Hash(string path)
        {
            using (var stream = File.OpenRead(path))
            using (var hasher = MD5.Create())
            {
                byte[] hash = hasher.ComputeHash(stream);
                string hexHash = BitConverter.ToString(hash).Replace("-", "");
                return hexHash;
            }
        }
    }
}

与您的程序相比,这有几个优点:

  • 它不需要同时将整个文件加载到 RAM 中
  • 如果文件包含非 ASCII 字符/字节,则返回正确的结果
  • 它会更短更干净