繁体   English   中英

从命令行参数获取哈希

[英]Getting Hash from command line arguments

我正在尝试创建一个控制台或窗体,您将在其中将文件拖到各自的.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字符/字节,它将返回正确的结果
  • 它更短更干净

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM