Parallel brute force: Difference between revisions

m
syntax highlighting fixup automation
m (Minor edit to C++ code)
m (syntax highlighting fixup automation)
Line 15:
=={{header|Ada}}==
{{libheader|CryptAda}}
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
with CryptAda.Digests.Message_Digests.SHA_256;
Line 86:
Work := new Worker (First => C);
end loop;
end Brute_Force;</langsyntaxhighlight>
 
=={{header|BaCon}}==
<langsyntaxhighlight lang="qbasic">PRAGMA INCLUDE <openssl/sha.h>
PRAGMA LDFLAGS -lcrypto
 
Line 134:
NEXT
NEXT
WEND</langsyntaxhighlight>
{{out}}
<pre>
Line 144:
=={{header|C}}==
{{trans|C#}}
<langsyntaxhighlight lang="c">// $ gcc -o parabrutfor parabrutfor.c -fopenmp -lssl -lcrypto
// $ export OMP_NUM_THREADS=4
// $ ./parabrutfor
Line 214:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>apple => 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
Line 222:
=={{header|C sharp|C#}}==
 
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Text;
Line 262:
return true;
}
}</langsyntaxhighlight>
 
{{out}}
Line 271:
=={{header|C++}}==
{{libheader|OpenSSL}}
<langsyntaxhighlight lang="cpp">#include <atomic>
#include <cstdio>
#include <cstring>
Line 383:
pf.find_passwords(hashes);
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 395:
=={{header|Clojure}}==
{{libheader|clojure.math.combinatorics}}
<langsyntaxhighlight Clojurelang="clojure">(ns rosetta.brute-force
(:require [clojure.math.combinatorics :refer [selections]]) ;; https://github.com/clojure/math.combinatorics
(:import [java.util Arrays]
Line 475:
(some (partial check-candidate target-bytes sha256)
(selections space 5)))))))
</syntaxhighlight>
</lang>
{{out}}
<pre>Answer found for: 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b => apple
Line 484:
{{libheader|lparallel}}
{{libheader|ironclad}}
<langsyntaxhighlight lang="lisp">(defpackage #:parallel-brute-force
(:use #:cl
#:lparallel))
Line 529:
(end-kernel))))
(dolist (r results)
(format t "~A: ~A~%" (first r) (second r)))))</langsyntaxhighlight>
{{out}}
<pre>apple: 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
Line 537:
=={{header|D}}==
There is at least one more method not shown for doing the task in parallel, which uses the std.concurrency module instead.
<langsyntaxhighlight Dlang="d">import std.digest.sha;
import std.parallelism;
import std.range;
Line 590:
 
return true;
}</langsyntaxhighlight>
 
{{out}}
Line 602:
{{libheader| System.Threading}}
{{libheader| DCPsha256}}[[https://github.com/StephenGenusa/DCPCrypt]]
<syntaxhighlight lang="delphi">
<lang Delphi>
program Parallel_Brute_Force;
 
Line 677:
Writeln('Enter to exit');
readln;
end.</langsyntaxhighlight>
 
=={{header|Erlang}}==
There are a total of 8 tasks, each handling a different set of prefixes (abc, def, ghi, jkl, mno, pqr, stuv, wxyz)
<syntaxhighlight lang="erlang">
<lang Erlang>
#! /usr/bin/escript
-mode(compile).
Line 724:
 
[io:format("~s: ~s~n", Result) || Result <- Results].
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 734:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
(*
Nigel Galloway February 21st., 2017
Line 756:
 
for r in n1.Result@n2.Result@n3.Result@n4.Result@n5.Result@n6.Result@n7.Result@n8.Result do printfn "%s" r
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 768:
{{trans|Visual_Basic_.NET}}
{{trans|BaCon}}
<langsyntaxhighlight lang="freebasic">Function SHA_256(Byval message As String) As String
#Macro Ch (x, y, z)
(((x) And (y)) Xor ((Not (x)) And z))
Line 908:
PrintCode(i)
Next i
Sleep</langsyntaxhighlight>
 
=={{header|Frink}}==
This does not use any parallel processing but just demonstrates Frink's built-in password hashing.
<langsyntaxhighlight lang="frink">hashes = new set["1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad",
"3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b",
"74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f"]
Line 923:
if hashes.contains[hash]
println["$str: $hash"]
}</langsyntaxhighlight>
{{out}}
<pre>
Line 934:
This solution runs 26 goroutines, one for each possible password first letter.
Goroutines run in parallel on a multicore system.
<langsyntaxhighlight lang="go">package main
 
import (
Line 985:
return
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,003:
Compile with "-O2 -threaded"<br/>
7.391s elapsed on a 2.5 GHz Dual-Core Intel Core i7 Macbook Pro.
<langsyntaxhighlight lang="haskell">import Control.Concurrent (setNumCapabilities)
import Crypto.Hash (hashWith, SHA256 (..), Digest)
import Control.Monad (replicateM, join, (>=>))
Line 1,035:
setNumCapabilities cpus
printf "Using %d cores\n" cpus
mapM_ (uncurry (printf "%s -> %s\n")) (bruteForce cpus)</langsyntaxhighlight>
{{out}}
<pre>brute
Line 1,046:
 
<p>Here all the possible test strings are batched as a stream that is fed to worker threads via a single read channel (batchChan). Each worker thread listens to the read channel (batchChan) and will write to the write channel (resultChan) when it finds a match. The worker threads loop indefinitely returning to read the next message on the read channel (batchChan). The main thread listens to the write channel (resultChan) and terminates once all three messages have been received.</p>
<langsyntaxhighlight lang="haskell">import Control.Concurrent (forkIO, setNumCapabilities)
import Control.Concurrent.Chan (Chan, newChan, readChan, writeList2Chan)
import Control.Monad (replicateM, replicateM_, forever)
Line 1,098:
replicateM_ wCount (forkIO $ searchWorker batchChan resultChan)
writeList2Chan batchChan chunks
replicateM_ (length hashedValues) (readChan resultChan >>= uncurry (printf "%s -> %s\n") . first show)</langsyntaxhighlight>
{{out}}
<pre>brute2
Line 1,111:
This implementation runs 3 threads (one per hash to crack), and short-stops when a match for a hash is found.
 
<langsyntaxhighlight Javalang="java">import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
Line 1,206:
 
 
</syntaxhighlight>
</lang>
{{out}}<pre>Hash 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b has the following match : apple
Hash 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f has the following match : mmmmm
Line 1,213:
===Faster Alternative Version===
Combines ideas from the C++ solution and the above Java version. Execution time is about 1.6 seconds on my system (3.2 GHz Quad-Core Intel Core i5, macOS 10.15.3).
<langsyntaxhighlight Javalang="java">import javax.xml.bind.DatatypeConverter;
import java.security.*;
import java.util.*;
Line 1,294:
private byte[][] digests;
private AtomicInteger count = new AtomicInteger();
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,303:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">@everywhere using SHA
 
@everywhere function bruteForceRange(startSerial, numberToDo)
Line 1,324:
@everywhere perThread = div(26^5, Sys.CPU_CORES)
pmap(x -> bruteForceRange(x * perThread, perThread), 0:Sys.CPU_CORES-1)
</syntaxhighlight>
</lang>
{{out}}<pre>From worker 2: apple --> 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
From worker 3: zyzzx --> 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad
Line 1,331:
=={{header|Kotlin}}==
{{trans|C#}}
<langsyntaxhighlight lang="scala">// version 1.1.51
 
import java.security.MessageDigest
Line 1,383:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,394:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
 
<langsyntaxhighlight Mathematicalang="mathematica">testPassword[pass_String] :=
If[MemberQ[{16^^1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad,
16^^3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b,
Line 1,404:
ParallelDo[
testPassword[StringJoin[a, b, c, d, e]],
{a, chars}, {b, chars}, {c, chars}, {d, chars}, {e, chars}]</langsyntaxhighlight>
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE PBF;
FROM FormatString IMPORT FormatString;
FROM SHA256 IMPORT SHA256,Create,Destroy,HashBytes,Finalize,GetHash;
Line 1,571:
WriteLn;
ReadChar
END PBF.</langsyntaxhighlight>
{{out}}
<pre>apple 3A7BD3E2360A3D29EEA436FCFB7E44C735D117C42D1C1835420B6B9942DD4F1B
Line 1,582:
Using a thread for each starting character.
Note that the program must be compiled with option --threads:on.
<langsyntaxhighlight Nimlang="nim">import strutils, threadpool
import nimcrypto
 
Line 1,619:
spawn findHashes(a)
 
sync()</langsyntaxhighlight>
 
{{out}}
Line 1,628:
=={{header|Perl}}==
Uses threads library to do naive search using 26 threads ("aaaaa" .. "azzzz", "baaaa" .. "bzzzz", etc.). No effort is made to early exit.
<langsyntaxhighlight lang="perl">use Digest::SHA qw/sha256_hex/;
use threads;
use threads::shared;
Line 1,655:
$s++;
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,665:
=={{header|Phix}}==
Each thread processes one start letter at a time, until they are all done.
<!--<langsyntaxhighlight Phixlang="phix">(notonline)-->
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">\</span><span style="color: #000000;">sha256</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">\</span><span style="color: #000000;">VM</span><span style="color: #0000FF;">\</span><span style="color: #000000;">pThreadN</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span> <span style="color: #000080;font-style:italic;">-- (shd not be rqd on 0.8.1+)</span>
Line 1,727:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"completed with %d threads in %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">nthreads</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}} (with nthreads loop from 1 to 4, and for that case CPU use in Task Manager shows a very clear step pattern.)
<pre>
Line 1,749:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">UseSHA2Fingerprint()
 
NewList sha256fp.s()
Line 1,792:
EndIf
End
; EnableThread</langsyntaxhighlight>
{{out}}
<pre>apple => 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
Line 1,802:
=={{header|Python}}==
 
<langsyntaxhighlight lang="python">import multiprocessing
from hashlib import sha256
 
Line 1,828:
 
if __name__ == "__main__":
main()</langsyntaxhighlight>
 
{{out}}
Line 1,840:
the single threaded version.
 
<langsyntaxhighlight lang="racket">#lang racket/base
(require racket/place
racket/list
Line 1,938:
.
#"\21\25\335\200\17\352\254\357\337H\37\37\220p7J*\201\342x\200\361\2079m\266yX\262\a\313\255"))
"without parallelism, it works"))</langsyntaxhighlight>
 
{{out}}
Line 1,962:
(formerly Perl 6)
This solution can be changed from parallel to serial by removing the <code>.race</code> method.
<syntaxhighlight lang="raku" perl6line>use Digest::SHA256::Native;
constant @alpha2 = [X~] <a m p y z> xx 2;
constant @alpha3 = [X~] <e l m p x z> xx 3;
Line 1,980:
}
 
.say for flat @alpha2.race(:1batch).map: { find_it($_) };</langsyntaxhighlight>
{{Out}}
<pre>apple => 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b
Line 1,987:
 
Testers can adjust the run speed by replacing the @alpha constants with one of the below:
<syntaxhighlight lang="raku" line>
<lang perl6>
# True to actual RC task, but slowest
constant @alpha2 = 'aa' .. 'zz';
Line 1,995:
constant @alpha2 = [X~] <a m p y z> xx 2;
constant @alpha3 = [X~] <e l m p x z> xx 3;
</syntaxhighlight>
</lang>
 
=={{header|Rust}}==
Line 2,001:
In this solution the number of threads is the number of logical processors on the machine. `distribute_work()` distributes the work more or less equally between the threads.
 
<langsyntaxhighlight Rustlang="rust">// [dependencies]
// rust-crypto = "0.2.36"
// num_cpus = "1.7.0"
Line 2,120:
}
result.clone()
}</langsyntaxhighlight>
 
{{out}}
Line 2,136:
This example converts the collection of candidate strings into a ParVector as soon as possible, speeding up both the final step to generating the candidates and the search.
 
<langsyntaxhighlight lang="scala">import java.security.MessageDigest
 
import scala.collection.parallel.immutable.ParVector
Line 2,171:
digester.digest(str.getBytes("UTF-8")).map("%02x".format(_)).mkString
}
}</langsyntaxhighlight>
 
An unfortunate side-effect of jumping straight into a ParVector, though, is that the entire list of candidate strings must be computed before attempting to find a match. This means that even modestly large charsets and/or strings can make the memory usage and runtime blow up.
Line 2,179:
Notice that def is used in place of val when working with the list of candidates. This is because val holds onto the head, which means it would fill up memory over time with the backlog of candidates already checked. Using def lets the program discard candidates after they are checked.
 
<langsyntaxhighlight lang="scala">import java.security.MessageDigest
 
import scala.annotation.tailrec
Line 2,227:
digester.digest(str.getBytes("UTF-8")).map("%02x".format(_)).mkString
}
}</langsyntaxhighlight>
 
As a final example, we can clean this code up with some method chaining and currying to get this:
 
<langsyntaxhighlight lang="scala">import java.security.MessageDigest
 
import scala.collection.parallel.immutable.ParVector
Line 2,264:
.map(_.to(ParVector).find(str => getHash(str) == hash)) //Convert each chunk into a ParVector and search it
.collectFirst{case Some(res) => res} //Get the first hit if one is found
}</langsyntaxhighlight>
 
{{out}}
Line 2,280:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func invert_sha256(hash) {
 
var letters = @('a'..'z')
Line 2,308:
var phrase = invert_sha256(t)
say "#{t} : #{phrase}"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,317:
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">import Foundation
import CryptoKit
 
Line 2,353:
}
}
}</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Imports System.Text
 
Module Module1
Line 2,409:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>mmmmm => 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f
Line 2,423:
 
Currently, parallel calculations are impossible in Wren-cli. However, if Wren is being embedded, it might be possible for a suitable host to run several Wren VM's in parallel and divide a task up between them to improve execution time.
<langsyntaxhighlight lang="ecmascript">import "/crypto" for Sha256
 
var hashes = [
Line 2,461:
var fib = Fiber.new(findHash)
fib.call(97+i)
}</langsyntaxhighlight>
 
{{out}}
Line 2,482:
Uses the message hashing extension library (DLL).
{{trans|==C sharp|C#}}
<langsyntaxhighlight lang="zkl">var [const] MsgHash=Import.lib("zklMsgHash");
var [const] gotEm=Atomic.Int(); // global signal for all threads
 
Line 2,502:
}
}
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">hashes:=T("3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b",
"74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f",
"1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad");
Line 2,517:
s+=n;
}
hashes2go.waitFor(0); // wait until all cracked, just exit, OS kills threads</langsyntaxhighlight>
<pre>
mmmmm --> 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f
10,327

edits