Есть ли способ ускорить мой код, чтобы найти хэш md5, начинающийся с нулей?C#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 Есть ли способ ускорить мой код, чтобы найти хэш md5, начинающийся с нулей?

Сообщение Anonymous »

Это просто хобби, никаких официальных или серьезных дел. Однако у меня есть вопрос; при запуске этого кода он вычисляет около 400 миллионов хешей md5 за первую секунду, затем число падает до ~ 10 миллионов хэшей в секунду, есть ли способ ускорить это?
Вот это код:

Код: Выделить всё

using System;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Paddings;

public class SimdMD5HashFinder
{
private static readonly int numberOfThreads = 16; // Number of threads (cores)
private static readonly CancellationTokenSource cts = new CancellationTokenSource(); // Cancellation token for cancellation management
private const int batchSize = 25000000; // Number of random byte arrays to process in each batch
private const int byteArraySize = 16; // Size of each random byte array (16 bytes for MD5 input)
public static ulong n = 0;

[DllImport("kernel32.dll")]
private static extern IntPtr GetCurrentThread();

[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr SetThreadAffinityMask(IntPtr hThread, IntPtr dwThreadAffinityMask);

public static void Main(string[] args)
{
Console.WriteLine("Starting multiple threads to find MD5 hashes with the first three bytes equal to zero...");

Task[] tasks = new Task[numberOfThreads];

for (int i = 0; i < numberOfThreads; i++)
{
int threadId = i; // Capture the current thread index
tasks[i] = Task.Run(() => FindHash(threadId));
}

// Wait for tasks to complete
Task.WaitAll(tasks);

Console.WriteLine("All threads have completed or a match was found.");
Console.ReadKey();
}

private static void FindHash(int threadId)
{
// Pin the thread to a specific CPU core
PinThreadToCore(threadId);

// Create MD5 digest object from BouncyCastle
MD5Digest md5 = new MD5Digest();
byte[] randomBytes = new byte[batchSize * byteArraySize]; // Single large array to hold all random bytes for the batch
byte[] hashBytes = new byte[md5.GetDigestSize()]; // MD5 hash is always 16 bytes
RandomNumberGenerator rng = RandomNumberGenerator.Create();

while (!cts.Token.IsCancellationRequested) // Loop until cancellation is requested
{
n += (ulong)batchSize; // Increment n by batchSize

if (n % 1000000 == 0)
{
Console.WriteLine(n);
}

// Fill the large buffer with random bytes
rng.GetBytes(randomBytes);
// Process the buffer in chunks, each chunk is a 16-byte random array
for (int i = 0; i < randomBytes.Length; i += byteArraySize)
{
// Calculate MD5 hash of the 16-byte chunk
md5.BlockUpdate(randomBytes, i, byteArraySize);
md5.DoFinal(hashBytes, 0);

// Check if the first three bytes of the hash are all zero
if (hashBytes[0] == 0 && hashBytes[1] == 0 && hashBytes[2] == 0 && hashBytes[3] == 0)
{
Console.WriteLine($"\nThread {threadId} found a match!");
Console.WriteLine($"Random Bytes:    {BitConverter.ToString(randomBytes, i, byteArraySize).Replace("-", "").ToLower()}"); // Show the chunk of random bytes as hex
Console.WriteLine($"MD5  Hash Bytes: {BitConverter.ToString(hashBytes).Replace("-", "").ToLower()}");
// Signal cancellation to stop all other threads
cts.Cancel();
return; // Exit the method once a match is found
}

// Reset the MD5 digest for the next round
md5.Reset();
}
}
}

// Method to pin a thread to a specific core
private static void PinThreadToCore(int coreId)
{
IntPtr mask = new IntPtr(1 

Подробнее здесь: [url]https://stackoverflow.com/questions/79119004/is-there-a-way-to-speed-up-my-code-to-find-an-md5-hash-that-starts-with-all-zero[/url]
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C#»